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,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Test/Perf/Utilities/PerfTestBase.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.CompilerServices; namespace Roslyn.Test.Performance.Utilities { /// <summary> /// An abstract class that concrete perf-tests implement in order to be run. /// </summary> public abstract class PerfTest : RelativeDirectory { /// <summary> /// Constructor for PerfTest that sets up the correct working path location. /// </summary> /// <param name="workingFile"></param> public PerfTest([CallerFilePath] string workingFile = "") : base(workingFile) { } /// <summary> /// Setup is called once for every test on a run. This is where you should do all /// setup, including downloading files and preparing paths. /// </summary> public abstract void Setup(); /// <summary> /// The body of the test. In most cases, this method will be shelling out to an /// external tool. /// </summary> public abstract void Test(); /// <summary> /// The number of iterations that the test should run for. /// </summary> public virtual int Iterations => 1; /// <summary> /// The human-readable name of the test. /// </summary> public abstract string Name { get; } /// <summary> /// The name of the process that the profiler should pay attention to. /// /// 'csc' is an example. /// </summary> public abstract string MeasuredProc { get; } /// <summary> /// Returns true if the test provides its own CPC scenarios. /// </summary> public abstract bool ProvidesScenarios { get; } /// <summary> /// A list of scenarios. /// </summary> /// <returns></returns> public abstract string[] GetScenarios(); public virtual ITraceManager GetTraceManager() { return TraceManagerFactory.GetBestTraceManager(); } } }
// Licensed to the .NET Foundation under one or more 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.CompilerServices; namespace Roslyn.Test.Performance.Utilities { /// <summary> /// An abstract class that concrete perf-tests implement in order to be run. /// </summary> public abstract class PerfTest : RelativeDirectory { /// <summary> /// Constructor for PerfTest that sets up the correct working path location. /// </summary> /// <param name="workingFile"></param> public PerfTest([CallerFilePath] string workingFile = "") : base(workingFile) { } /// <summary> /// Setup is called once for every test on a run. This is where you should do all /// setup, including downloading files and preparing paths. /// </summary> public abstract void Setup(); /// <summary> /// The body of the test. In most cases, this method will be shelling out to an /// external tool. /// </summary> public abstract void Test(); /// <summary> /// The number of iterations that the test should run for. /// </summary> public virtual int Iterations => 1; /// <summary> /// The human-readable name of the test. /// </summary> public abstract string Name { get; } /// <summary> /// The name of the process that the profiler should pay attention to. /// /// 'csc' is an example. /// </summary> public abstract string MeasuredProc { get; } /// <summary> /// Returns true if the test provides its own CPC scenarios. /// </summary> public abstract bool ProvidesScenarios { get; } /// <summary> /// A list of scenarios. /// </summary> /// <returns></returns> public abstract string[] GetScenarios(); public virtual ITraceManager GetTraceManager() { return TraceManagerFactory.GetBestTraceManager(); } } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Compilers/Core/Portable/InternalUtilities/SpecializedCollections.Empty.Enumerable.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; namespace Roslyn.Utilities { internal partial class SpecializedCollections { private partial class Empty { internal class Enumerable<T> : IEnumerable<T> { // PERF: cache the instance of enumerator. // accessing a generic static field is kinda slow from here, // but since empty enumerables are singletons, there is no harm in having // one extra instance field private readonly IEnumerator<T> _enumerator = Enumerator<T>.Instance; public IEnumerator<T> GetEnumerator() { return _enumerator; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; namespace Roslyn.Utilities { internal partial class SpecializedCollections { private partial class Empty { internal class Enumerable<T> : IEnumerable<T> { // PERF: cache the instance of enumerator. // accessing a generic static field is kinda slow from here, // but since empty enumerables are singletons, there is no harm in having // one extra instance field private readonly IEnumerator<T> _enumerator = Enumerator<T>.Instance; public IEnumerator<T> GetEnumerator() { return _enumerator; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } } } } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/VisualStudio/Core/Def/EditorConfigSettings/CodeStyle/View/CodeStyleSeverityControl.xaml.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.Windows.Automation; using System.Windows.Controls; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.CodeStyle.View { /// <summary> /// Interaction logic for CodeStyleSeverityControl.xaml /// </summary> internal partial class CodeStyleSeverityControl : UserControl { private readonly ComboBox _comboBox; private readonly CodeStyleSetting _setting; public CodeStyleSeverityControl(CodeStyleSetting setting) { InitializeComponent(); _setting = setting; _comboBox = new ComboBox() { ItemsSource = new[] { ServicesVSResources.Refactoring_Only, ServicesVSResources.Suggestion, ServicesVSResources.Warning, ServicesVSResources.Error } }; _comboBox.SelectedIndex = setting.Severity switch { DiagnosticSeverity.Hidden => 0, DiagnosticSeverity.Info => 1, DiagnosticSeverity.Warning => 2, DiagnosticSeverity.Error => 3, _ => throw new InvalidOperationException(), }; _comboBox.SelectionChanged += ComboBox_SelectionChanged; _comboBox.SetValue(AutomationProperties.NameProperty, ServicesVSResources.Severity); _ = RootGrid.Children.Add(_comboBox); } private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { var severity = _comboBox.SelectedIndex switch { 0 => DiagnosticSeverity.Hidden, 1 => DiagnosticSeverity.Info, 2 => DiagnosticSeverity.Warning, 3 => DiagnosticSeverity.Error, _ => throw new InvalidOperationException(), }; if (_setting.Severity != severity) { _setting.ChangeSeverity(severity); } } } }
// Licensed to the .NET Foundation under one or more 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.Windows.Automation; using System.Windows.Controls; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.CodeStyle.View { /// <summary> /// Interaction logic for CodeStyleSeverityControl.xaml /// </summary> internal partial class CodeStyleSeverityControl : UserControl { private readonly ComboBox _comboBox; private readonly CodeStyleSetting _setting; public CodeStyleSeverityControl(CodeStyleSetting setting) { InitializeComponent(); _setting = setting; _comboBox = new ComboBox() { ItemsSource = new[] { ServicesVSResources.Refactoring_Only, ServicesVSResources.Suggestion, ServicesVSResources.Warning, ServicesVSResources.Error } }; _comboBox.SelectedIndex = setting.Severity switch { DiagnosticSeverity.Hidden => 0, DiagnosticSeverity.Info => 1, DiagnosticSeverity.Warning => 2, DiagnosticSeverity.Error => 3, _ => throw new InvalidOperationException(), }; _comboBox.SelectionChanged += ComboBox_SelectionChanged; _comboBox.SetValue(AutomationProperties.NameProperty, ServicesVSResources.Severity); _ = RootGrid.Children.Add(_comboBox); } private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { var severity = _comboBox.SelectedIndex switch { 0 => DiagnosticSeverity.Hidden, 1 => DiagnosticSeverity.Info, 2 => DiagnosticSeverity.Warning, 3 => DiagnosticSeverity.Error, _ => throw new InvalidOperationException(), }; if (_setting.Severity != severity) { _setting.ChangeSeverity(severity); } } } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Compilers/CSharp/Test/Symbol/DocumentationComments/DestructorDocumentationCommentTests.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.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class DestructorDocumentationCommentTests : CSharpTestBase { private readonly CSharpCompilation _compilation; private readonly NamespaceSymbol _acmeNamespace; private readonly NamedTypeSymbol _widgetClass; public DestructorDocumentationCommentTests() { _compilation = CreateCompilationWithMscorlib40AndDocumentationComments(@"namespace Acme { class Widget: IProcess { /// <summary>Destructor Documentation</summary> ~Widget() {...} } } "); _acmeNamespace = (NamespaceSymbol)_compilation.GlobalNamespace.GetMembers("Acme").Single(); _widgetClass = _acmeNamespace.GetTypeMembers("Widget").Single(); } [Fact] public void TestDestructor() { Assert.Equal("M:Acme.Widget.Finalize", _widgetClass.GetMembers("Finalize").Single().GetDocumentationCommentId()); Assert.Equal( @"<member name=""M:Acme.Widget.Finalize""> <summary>Destructor Documentation</summary> </member> ", _widgetClass.GetMembers("Finalize").Single().GetDocumentationCommentXml()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class DestructorDocumentationCommentTests : CSharpTestBase { private readonly CSharpCompilation _compilation; private readonly NamespaceSymbol _acmeNamespace; private readonly NamedTypeSymbol _widgetClass; public DestructorDocumentationCommentTests() { _compilation = CreateCompilationWithMscorlib40AndDocumentationComments(@"namespace Acme { class Widget: IProcess { /// <summary>Destructor Documentation</summary> ~Widget() {...} } } "); _acmeNamespace = (NamespaceSymbol)_compilation.GlobalNamespace.GetMembers("Acme").Single(); _widgetClass = _acmeNamespace.GetTypeMembers("Widget").Single(); } [Fact] public void TestDestructor() { Assert.Equal("M:Acme.Widget.Finalize", _widgetClass.GetMembers("Finalize").Single().GetDocumentationCommentId()); Assert.Equal( @"<member name=""M:Acme.Widget.Finalize""> <summary>Destructor Documentation</summary> </member> ", _widgetClass.GetMembers("Finalize").Single().GetDocumentationCommentXml()); } } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/VisualStudio/VisualBasic/Impl/Options/NamingStylesOptionPage.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.Runtime.InteropServices Imports System.Windows Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Notification Imports Microsoft.VisualStudio.ComponentModelHost Imports Microsoft.VisualStudio.LanguageServices.Implementation.Options Imports Microsoft.VisualStudio.LanguageServices.Implementation.Options.Style Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options <Guid(Guids.VisualBasicOptionPageNamingStyleIdString)> Friend Class NamingStylesOptionPage Inherits AbstractOptionPage Private _grid As NamingStyleOptionPageControl Private _notificationService As INotificationService Protected Overrides Function CreateOptionPage(serviceProvider As IServiceProvider, optionStore As OptionStore) As AbstractOptionPageControl Dim componentModel = DirectCast(serviceProvider.GetService(GetType(SComponentModel)), IComponentModel) Dim workspace = componentModel.GetService(Of VisualStudioWorkspace) _notificationService = workspace.Services.GetService(Of INotificationService) _grid = New NamingStyleOptionPageControl(optionStore, _notificationService, LanguageNames.VisualBasic) Return _grid End Function Protected Overrides Sub OnApply(e As PageApplyEventArgs) If _grid.ContainsErrors() Then _notificationService.SendNotification(ServicesVSResources.Some_naming_rules_are_incomplete_Please_complete_or_remove_them) e.ApplyBehavior = ApplyKind.Cancel Return End If MyBase.OnApply(e) 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.Runtime.InteropServices Imports System.Windows Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Notification Imports Microsoft.VisualStudio.ComponentModelHost Imports Microsoft.VisualStudio.LanguageServices.Implementation.Options Imports Microsoft.VisualStudio.LanguageServices.Implementation.Options.Style Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options <Guid(Guids.VisualBasicOptionPageNamingStyleIdString)> Friend Class NamingStylesOptionPage Inherits AbstractOptionPage Private _grid As NamingStyleOptionPageControl Private _notificationService As INotificationService Protected Overrides Function CreateOptionPage(serviceProvider As IServiceProvider, optionStore As OptionStore) As AbstractOptionPageControl Dim componentModel = DirectCast(serviceProvider.GetService(GetType(SComponentModel)), IComponentModel) Dim workspace = componentModel.GetService(Of VisualStudioWorkspace) _notificationService = workspace.Services.GetService(Of INotificationService) _grid = New NamingStyleOptionPageControl(optionStore, _notificationService, LanguageNames.VisualBasic) Return _grid End Function Protected Overrides Sub OnApply(e As PageApplyEventArgs) If _grid.ContainsErrors() Then _notificationService.SendNotification(ServicesVSResources.Some_naming_rules_are_incomplete_Please_complete_or_remove_them) e.ApplyBehavior = ApplyKind.Cancel Return End If MyBase.OnApply(e) End Sub End Class End Namespace
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.zh-Hant.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="zh-Hant" original="../VBFeaturesResources.resx"> <body> <trans-unit id="Add_Await"> <source>Add Await</source> <target state="translated">新增 Await</target> <note /> </trans-unit> <trans-unit id="Add_Await_and_ConfigureAwaitFalse"> <source>Add Await and 'ConfigureAwait(false)'</source> <target state="translated">新增 Await 及 'ConfigureAwait(false)'</target> <note /> </trans-unit> <trans-unit id="Add_Obsolete"> <source>Add &lt;Obsolete&gt;</source> <target state="translated">新增 &lt;已淘汰&gt;</target> <note /> </trans-unit> <trans-unit id="Add_missing_Imports"> <source>Add missing Imports</source> <target state="translated">新增缺少的 Import</target> <note>{Locked="Import"}</note> </trans-unit> <trans-unit id="Add_Shadows"> <source>Add 'Shadows'</source> <target state="translated">新增 'Shadows'</target> <note>{Locked="Shadows"} "Shadows" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Apply_Imports_directive_placement_preferences"> <source>Apply Imports directive placement preferences</source> <target state="translated">套用 Import 指示詞放置喜好設定</target> <note>{Locked="Import"} "Import" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Apply_Me_qualification_preferences"> <source>Apply Me qualification preferences</source> <target state="translated">套用 Me 資格喜好設定</target> <note>{Locked="Me"} "Me" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Change_to_DirectCast"> <source>Change to 'DirectCast'</source> <target state="translated">變更為 'DirectCast'</target> <note /> </trans-unit> <trans-unit id="Change_to_TryCast"> <source>Change to 'TryCast'</source> <target state="translated">變更為 'TryCast'</target> <note /> </trans-unit> <trans-unit id="Insert_0"> <source>Insert '{0}'.</source> <target state="translated">插入 '{0}'。</target> <note /> </trans-unit> <trans-unit id="Delete_the_0_statement1"> <source>Delete the '{0}' statement.</source> <target state="translated">刪除 '{0}' 陳述式。</target> <note /> </trans-unit> <trans-unit id="Create_event_0_in_1"> <source>Create event {0} in {1}</source> <target state="translated">在 {1} 中建立事件 {0}</target> <note /> </trans-unit> <trans-unit id="Insert_the_missing_End_Property_statement"> <source>Insert the missing 'End Property' statement.</source> <target state="translated">插入遺漏的 'End Property' 陳述式。</target> <note /> </trans-unit> <trans-unit id="Insert_the_missing_0"> <source>Insert the missing '{0}'.</source> <target state="translated">插入遺漏的 '{0}'。</target> <note /> </trans-unit> <trans-unit id="Inline_temporary_variable"> <source>Inline temporary variable</source> <target state="translated">內嵌暫存變數</target> <note /> </trans-unit> <trans-unit id="Conflict_s_detected"> <source>Conflict(s) detected.</source> <target state="translated">偵測到衝突。</target> <note /> </trans-unit> <trans-unit id="Introduce_Using_statement"> <source>Introduce 'Using' statement</source> <target state="translated">引入 'Using' 陳述式</target> <note>{Locked="Using"} "Using" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Make_0_inheritable"> <source>Make '{0}' inheritable</source> <target state="translated">將 '{0}' 設為可繼承</target> <note /> </trans-unit> <trans-unit id="Make_private_field_ReadOnly_when_possible"> <source>Make private field ReadOnly when possible</source> <target state="translated">盡可能地將私人欄位設為 ReadOnly</target> <note>{Locked="ReadOnly"} "ReadOnly" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Move_the_0_statement_to_line_1"> <source>Move the '{0}' statement to line {1}.</source> <target state="translated">將 '{0}' 陳述式移至行 {1}。</target> <note /> </trans-unit> <trans-unit id="Delete_the_0_statement2"> <source>Delete the '{0}' statement.</source> <target state="translated">刪除 '{0}' 陳述式。</target> <note /> </trans-unit> <trans-unit id="Multiple_Types"> <source>&lt;Multiple Types&gt;</source> <target state="translated">&lt;多項類型&gt;</target> <note /> </trans-unit> <trans-unit id="Organize_Imports"> <source>Organize Imports</source> <target state="translated">整理 Import</target> <note>{Locked="Import"}</note> </trans-unit> <trans-unit id="Remove_shared_keyword_from_module_member"> <source>Remove 'Shared' keyword from Module member</source> <target state="translated">從模組成員移除 'Shared' 關鍵字</target> <note>{Locked="Shared"} "Shared" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Shared_constructor"> <source>Shared constructor</source> <target state="translated">共用建構函式</target> <note /> </trans-unit> <trans-unit id="Type_a_name_here_to_declare_a_new_field"> <source>Type a name here to declare a new field.</source> <target state="translated">於此輸入名稱以宣告新的欄位。</target> <note /> </trans-unit> <trans-unit id="Note_colon_Space_completion_is_disabled_to_avoid_potential_interference_To_insert_a_name_from_the_list_use_tab"> <source>Note: Space completion is disabled to avoid potential interference. To insert a name from the list, use tab.</source> <target state="translated">注意: 空格完成的功能已停用,以免造成可能的干擾。若要插入清單中的名稱,請使用 Tab 鍵。</target> <note /> </trans-unit> <trans-unit id="_0_Events"> <source>({0} Events)</source> <target state="translated">({0} 個事件)</target> <note /> </trans-unit> <trans-unit id="new_field"> <source>&lt;new field&gt;</source> <target state="translated">&lt;新欄位&gt;</target> <note /> </trans-unit> <trans-unit id="Type_a_name_here_to_declare_a_parameter_If_no_preceding_keyword_is_used_ByVal_will_be_assumed_and_the_argument_will_be_passed_by_value"> <source>Type a name here to declare a parameter. If no preceding keyword is used; 'ByVal' will be assumed and the argument will be passed by value.</source> <target state="translated">於此輸入名稱以宣告參數。若之前未出現任何關鍵字,將假設使用 'ByVal',且引數將依值傳遞。</target> <note /> </trans-unit> <trans-unit id="parameter_name"> <source>&lt;parameter name&gt;</source> <target state="translated">&lt;參數名稱&gt;</target> <note /> </trans-unit> <trans-unit id="Type_a_new_name_for_the_column_followed_by_Otherwise_the_original_column_name_with_be_used"> <source>Type a new name for the column, followed by '='. Otherwise, the original column name with be used.</source> <target state="translated">輸入資料行的新名稱,其後接著 '='。否則將會使用原始的資料行名稱。</target> <note /> </trans-unit> <trans-unit id="Note_colon_Use_tab_for_automatic_completion_space_completion_is_disabled_to_avoid_interfering_with_a_new_name"> <source>Note: Use tab for automatic completion; space completion is disabled to avoid interfering with a new name.</source> <target state="translated">注意: 若要自動完成可使用 Tab 鍵; 而空格完成功能已停用,以免干擾新名稱。</target> <note /> </trans-unit> <trans-unit id="result_alias"> <source>&lt;result alias&gt;</source> <target state="translated">&lt;結果別名&gt;</target> <note /> </trans-unit> <trans-unit id="Type_a_new_variable_name"> <source>Type a new variable name</source> <target state="translated">輸入新的變數名稱</target> <note /> </trans-unit> <trans-unit id="Note_colon_Space_and_completion_are_disabled_to_avoid_potential_interference_To_insert_a_name_from_the_list_use_tab"> <source>Note: Space and '=' completion are disabled to avoid potential interference. To insert a name from the list, use tab.</source> <target state="translated">注意: 空格和 '=' 完成的功能已停用,以免造成可能的干擾。若要插入清單中的名稱,請使用 Tab 鍵。</target> <note /> </trans-unit> <trans-unit id="new_resource"> <source>&lt;new resource&gt;</source> <target state="translated">&lt;新資源&gt;</target> <note /> </trans-unit> <trans-unit id="AddHandler_statement"> <source>AddHandler statement</source> <target state="translated">AddHandler 陳述式</target> <note /> </trans-unit> <trans-unit id="RemoveHandler_statement"> <source>RemoveHandler statement</source> <target state="translated">RemoveHandler 陳述式</target> <note /> </trans-unit> <trans-unit id="_0_function"> <source>{0} function</source> <target state="translated">{0} 函式</target> <note /> </trans-unit> <trans-unit id="CType_function"> <source>CType function</source> <target state="translated">CType 函式</target> <note /> </trans-unit> <trans-unit id="DirectCast_function"> <source>DirectCast function</source> <target state="translated">DirectCast 函式</target> <note /> </trans-unit> <trans-unit id="TryCast_function"> <source>TryCast function</source> <target state="translated">TryCast 函式</target> <note /> </trans-unit> <trans-unit id="GetType_function"> <source>GetType function</source> <target state="translated">GetType 函式</target> <note /> </trans-unit> <trans-unit id="GetXmlNamespace_function"> <source>GetXmlNamespace function</source> <target state="translated">GetXmlNamespace 函式</target> <note /> </trans-unit> <trans-unit id="Mid_statement"> <source>Mid statement</source> <target state="translated">Mid 陳述式</target> <note /> </trans-unit> <trans-unit id="Fix_Incorrect_Function_Return_Type"> <source>Fix Incorrect Function Return Type</source> <target state="translated">修正不正確的函式傳回類型</target> <note /> </trans-unit> <trans-unit id="Simplify_name_0"> <source>Simplify name '{0}'</source> <target state="translated">簡化名稱 '{0}'</target> <note /> </trans-unit> <trans-unit id="Simplify_member_access_0"> <source>Simplify member access '{0}'</source> <target state="translated">簡化成員存取 '{0}'</target> <note /> </trans-unit> <trans-unit id="Remove_Me_qualification"> <source>Remove 'Me' qualification</source> <target state="translated">移除 'Me' 限定性條件</target> <note>{Locked="Me"} "Me" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Name_can_be_simplified"> <source>Name can be simplified</source> <target state="translated">可以簡化名稱</target> <note /> </trans-unit> <trans-unit id="can_t_determine_valid_range_of_statements_to_extract_out"> <source>can't determine valid range of statements to extract out</source> <target state="translated">無法決定要擷取的有效陳述式範圍</target> <note /> </trans-unit> <trans-unit id="Not_all_code_paths_return"> <source>Not all code paths return</source> <target state="translated">未傳回所有程式碼路徑</target> <note /> </trans-unit> <trans-unit id="contains_invalid_selection"> <source>contains invalid selection</source> <target state="translated">包含無效的選取範圍</target> <note /> </trans-unit> <trans-unit id="the_selection_contains_syntactic_errors"> <source>the selection contains syntactic errors</source> <target state="translated">選取範圍包含語法錯誤</target> <note /> </trans-unit> <trans-unit id="Selection_can_t_be_crossed_over_preprocessors"> <source>Selection can't be crossed over preprocessors</source> <target state="translated">選取範圍不可跨多部前置處理器</target> <note /> </trans-unit> <trans-unit id="Selection_can_t_contain_throw_without_enclosing_catch_block"> <source>Selection can't contain throw without enclosing catch block</source> <target state="translated">選取範圍不可包含未納入 catch 區塊的 Throw</target> <note /> </trans-unit> <trans-unit id="Selection_can_t_be_parts_of_constant_initializer_expression"> <source>Selection can't be parts of constant initializer expression</source> <target state="translated">選取範圍不可為常數初始設定式運算式的任何部分</target> <note /> </trans-unit> <trans-unit id="Argument_used_for_ByRef_parameter_can_t_be_extracted_out"> <source>Argument used for ByRef parameter can't be extracted out</source> <target state="translated">無法擷取用於 ByRef 參數的引數</target> <note /> </trans-unit> <trans-unit id="all_static_local_usages_defined_in_the_selection_must_be_included_in_the_selection"> <source>all static local usages defined in the selection must be included in the selection</source> <target state="translated">選取範圍中必須包含選取範圍中所定義的所有靜態區域使用方式</target> <note /> </trans-unit> <trans-unit id="Implicit_member_access_can_t_be_included_in_the_selection_without_containing_statement"> <source>Implicit member access can't be included in the selection without containing statement</source> <target state="translated">沒有包含陳述式的選取範圍中,不可包含隱含成員存取</target> <note /> </trans-unit> <trans-unit id="Selection_must_be_part_of_executable_statements"> <source>Selection must be part of executable statements</source> <target state="translated">選取範圍必須是可執行之陳述式的一部分</target> <note /> </trans-unit> <trans-unit id="next_statement_control_variable_doesn_t_have_matching_declaration_statement"> <source>next statement control variable doesn't have matching declaration statement</source> <target state="translated">下一個陳述式控制變數沒有相符的宣告陳述式</target> <note /> </trans-unit> <trans-unit id="Selection_doesn_t_contain_any_valid_node"> <source>Selection doesn't contain any valid node</source> <target state="translated">選取範圍不包含任何有效的節點</target> <note /> </trans-unit> <trans-unit id="no_valid_statement_range_to_extract_out"> <source>no valid statement range to extract out</source> <target state="translated">沒有可擷取內容的有效陳述式範圍</target> <note /> </trans-unit> <trans-unit id="Invalid_selection"> <source>Invalid selection</source> <target state="translated">選取範圍無效</target> <note /> </trans-unit> <trans-unit id="Deprecated"> <source>Deprecated</source> <target state="translated">取代</target> <note /> </trans-unit> <trans-unit id="Extension"> <source>Extension</source> <target state="translated">擴充功能</target> <note /> </trans-unit> <trans-unit id="Awaitable"> <source>Awaitable</source> <target state="translated">可等候</target> <note /> </trans-unit> <trans-unit id="Awaitable_Extension"> <source>Awaitable, Extension</source> <target state="translated">可等候的擴充功能</target> <note /> </trans-unit> <trans-unit id="new_variable"> <source>&lt;new variable&gt;</source> <target state="translated">&lt;新變數&gt;</target> <note /> </trans-unit> <trans-unit id="Creates_a_delegate_procedure_instance_that_references_the_specified_procedure_AddressOf_procedureName"> <source>Creates a delegate procedure instance that references the specified procedure. AddressOf &lt;procedureName&gt;</source> <target state="translated">建立會參考指定程序的委派程序執行個體。 AddressOf &lt;procedureName&gt;</target> <note /> </trans-unit> <trans-unit id="Indicates_that_an_external_procedure_has_another_name_in_its_DLL"> <source>Indicates that an external procedure has another name in its DLL.</source> <target state="translated">表示外部程序在其 DLL 中有另一個名稱。</target> <note /> </trans-unit> <trans-unit id="Performs_a_short_circuit_logical_conjunction_on_two_expressions_Returns_True_if_both_operands_evaluate_to_True_If_the_first_expression_evaluates_to_False_the_second_is_not_evaluated_result_expression1_AndAlso_expression2"> <source>Performs a short-circuit logical conjunction on two expressions. Returns True if both operands evaluate to True. If the first expression evaluates to False, the second is not evaluated. &lt;result&gt; = &lt;expression1&gt; AndAlso &lt;expression2&gt;</source> <target state="translated">在兩個運算式上執行最少運算邏輯結合。若兩個運算元都評估為 True,即傳回 True。若第一個運算式評估為 False,則不會評估第二個運算式。 &lt;result&gt; = &lt;expression1&gt; AndAlso &lt;expression2&gt;</target> <note /> </trans-unit> <trans-unit id="Performs_a_logical_conjunction_on_two_Boolean_expressions_or_a_bitwise_conjunction_on_two_numeric_expressions_For_Boolean_expressions_returns_True_if_both_operands_evaluate_to_True_Both_expressions_are_always_evaluated_result_expression1_And_expression2"> <source>Performs a logical conjunction on two Boolean expressions, or a bitwise conjunction on two numeric expressions. For Boolean expressions, returns True if both operands evaluate to True. Both expressions are always evaluated. &lt;result&gt; = &lt;expression1&gt; And &lt;expression2&gt;</source> <target state="translated">在兩布林運算式上執行邏輯結合,或在兩個數值運算式上執行位元結合。對於布林運算式而言,若兩個運算元都評估為 True,即傳回 True。兩個運算式都會進行評估。 &lt;result&gt; = &lt;expression1&gt; And &lt;expression2&gt;</target> <note /> </trans-unit> <trans-unit id="Used_in_a_Declare_statement_The_Ansi_modifier_specifies_that_Visual_Basic_should_marshal_all_strings_to_ANSI_values_and_should_look_up_the_procedure_without_modifying_its_name_during_the_search_If_no_character_set_is_specified_ANSI_is_the_default"> <source>Used in a Declare statement. The Ansi modifier specifies that Visual Basic should marshal all strings to ANSI values, and should look up the procedure without modifying its name during the search. If no character set is specified, ANSI is the default.</source> <target state="translated">用在 Declare 陳述式中。Ansi 修飾元會指定 Visual Basic 應將所有字串封送處理成 ANSI 值,且在搜尋期間,應查詢程序但不要修改其名稱。若未指定字元集,預設值就是 ANSI。</target> <note /> </trans-unit> <trans-unit id="Specifies_a_data_type_in_a_declaration_statement"> <source>Specifies a data type in a declaration statement.</source> <target state="translated">在宣告陳述式中指定資料類型。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_an_attribute_at_the_beginning_of_a_source_file_applies_to_the_entire_assembly_Otherwise_the_attribute_will_apply_only_to_an_individual_programming_element_such_as_a_class_or_property"> <source>Specifies that an attribute at the beginning of a source file applies to the entire assembly. Otherwise the attribute will apply only to an individual programming element, such as a class or property.</source> <target state="translated">指定在原始程式檔開頭的屬性,會套用到整個組件。否則,屬性將只會套用到個別的程式設計元素,例如類別或屬性。</target> <note /> </trans-unit> <trans-unit id="Indicates_an_asynchronous_method_that_can_use_the_Await_operator"> <source>Indicates an asynchronous method that can use the Await operator.</source> <target state="translated">指出可以使用 Await 運算子的非同步方法。</target> <note /> </trans-unit> <trans-unit id="Used_in_a_Declare_statement_The_Auto_modifier_specifies_that_Visual_Basic_should_marshal_strings_according_to_NET_Framework_rules_and_should_determine_the_base_character_set_of_the_run_time_platform_and_possibly_modify_the_external_procedure_name_if_the_initial_search_fails"> <source>Used in a Declare statement. The Auto modifier specifies that Visual Basic should marshal strings according to .NET Framework rules, and should determine the base character set of the run-time platform and possibly modify the external procedure name if the initial search fails.</source> <target state="translated">用在 Declare 陳述式中。Auto 修飾元可指定 Visual Basic 應該根據 .NET Framework 規則封送處理字串,且應判斷執行階段平台的基礎字元集,若初始搜尋失敗,還可能修改外部程序名稱。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_an_argument_is_passed_in_such_a_way_that_the_called_procedure_can_change_the_underlying_value_of_the_argument_in_the_calling_code"> <source>Specifies that an argument is passed in such a way that the called procedure can change the underlying value of the argument in the calling code.</source> <target state="translated">將引數的傳遞方式,指定為可讓呼叫的程序能變更呼叫程式碼中引數的基礎值。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_an_argument_is_passed_in_such_a_way_that_the_called_procedure_or_property_cannot_change_the_underlying_value_of_the_argument_in_the_calling_code"> <source>Specifies that an argument is passed in such a way that the called procedure or property cannot change the underlying value of the argument in the calling code.</source> <target state="translated">將引數的傳遞方式,指定為可讓呼叫的程序或屬性無法變更呼叫程式碼中引數的基礎值。</target> <note /> </trans-unit> <trans-unit id="Declares_the_name_of_a_class_and_introduces_the_definitions_of_the_variables_properties_and_methods_that_make_up_the_class"> <source>Declares the name of a class and introduces the definitions of the variables, properties, and methods that make up the class.</source> <target state="translated">宣告類別的名稱,並引進組成類別之變數、屬性與方法的定義。</target> <note /> </trans-unit> <trans-unit id="Generates_a_string_concatenation_of_two_expressions"> <source>Generates a string concatenation of two expressions.</source> <target state="translated">產生兩個運算式的字串串連。</target> <note /> </trans-unit> <trans-unit id="Declares_and_defines_one_or_more_constants"> <source>Declares and defines one or more constants.</source> <target state="translated">宣告並定義一或多個常數。</target> <note /> </trans-unit> <trans-unit id="Use_In_for_a_type_that_will_only_be_used_for_ByVal_arguments_to_functions"> <source>Use 'In' for a type that will only be used for ByVal arguments to functions.</source> <target state="translated">針對只用於函式中 ByVal 引數的類型,使用 'In'。</target> <note /> </trans-unit> <trans-unit id="Use_Out_for_a_type_that_will_only_be_used_as_a_return_from_functions"> <source>Use 'Out' for a type that will only be used as a return from functions.</source> <target state="translated">針對只用做為函式傳回值的類型,使用 'Out'。</target> <note /> </trans-unit> <trans-unit id="Returns_the_result_of_explicitly_converting_an_expression_to_a_specified_data_type_object_structure_class_or_interface_CType_Object_As_Expression_Object_As_Type_As_Type"> <source>Returns the result of explicitly converting an expression to a specified data type, object, structure, class, or interface. CType(Object As Expression, Object As Type) As Type</source> <target state="translated">傳回運算式明確轉換成指定之資料類型、物件、結構、類別或介面的結果。 CType(Object As Expression, Object As Type) As Type</target> <note /> </trans-unit> <trans-unit id="Specifies_that_an_event_has_additional_specialized_code_for_adding_handlers_removing_handlers_and_raising_events"> <source>Specifies that an event has additional, specialized code for adding handlers, removing handlers, and raising events.</source> <target state="translated">指定事件有額外的特定程式碼,可加入處理常式、移除處理常式,以及引發事件。</target> <note /> </trans-unit> <trans-unit id="Declares_a_reference_to_a_procedure_implemented_in_an_external_file"> <source>Declares a reference to a procedure implemented in an external file.</source> <target state="translated">宣告實作在外部檔案中之程序的參考。</target> <note /> </trans-unit> <trans-unit id="Identifies_a_property_as_the_default_property_of_its_class_structure_or_interface"> <source>Identifies a property as the default property of its class, structure, or interface.</source> <target state="translated">找出為其類別、結構或介面之預設屬性的屬性。</target> <note /> </trans-unit> <trans-unit id="Used_to_declare_a_delegate_A_delegate_is_a_reference_type_that_refers_to_a_shared_method_of_a_type_or_to_an_instance_method_of_an_object_Any_procedure_that_is_convertible_or_that_has_matching_parameter_types_and_return_type_may_be_used_to_create_an_instance_of_this_delegate_class"> <source>Used to declare a delegate. A delegate is a reference type that refers to a shared method of a type or to an instance method of an object. Any procedure that is convertible, or that has matching parameter types and return type may be used to create an instance of this delegate class.</source> <target state="translated">用於宣告委派。委派是一種參考類型,其會參考類型的共用方法,或物件的執行個體方法。任何可轉換的程序,或是參數類型與傳回類型相符的程序,都可用以建立此委派類別的執行個體。</target> <note /> </trans-unit> <trans-unit id="Declares_and_allocates_storage_space_for_one_or_more_variables_Dim_var_bracket_As_bracket_New_bracket_dataType_bracket_boundList_bracket_bracket_bracket_initializer_bracket_bracket_var2_bracket"> <source>Declares and allocates storage space for one or more variables. Dim {&lt;var&gt; [As [New] dataType [(boundList)]][= initializer]}[, var2]</source> <target state="translated">宣告一或多個變數,並為其配置儲存空間。 Dim {&lt;var&gt; [As [New] dataType [(boundList)]][= initializer]}[, var2]</target> <note /> </trans-unit> <trans-unit id="Divides_two_numbers_and_returns_a_floating_point_result"> <source>Divides two numbers and returns a floating-point result.</source> <target state="translated">將兩個數值相除,傳回浮點結果。</target> <note /> </trans-unit> <trans-unit id="Terminates_a_0_block"> <source>Terminates a {0} block.</source> <target state="translated">結束 {0} 區塊。</target> <note /> </trans-unit> <trans-unit id="Terminates_an_0_block"> <source>Terminates an {0} block.</source> <target state="translated">結束 {0} 區塊。</target> <note /> </trans-unit> <trans-unit id="Terminates_the_definition_of_a_0_statement"> <source>Terminates the definition of a {0} statement.</source> <target state="translated">結束 {0} 陳述式的定義。</target> <note /> </trans-unit> <trans-unit id="Terminates_the_definition_of_an_0_statement"> <source>Terminates the definition of an {0} statement.</source> <target state="translated">結束 {0} 陳述式的定義。</target> <note /> </trans-unit> <trans-unit id="Declares_an_enumeration_and_defines_the_values_of_its_members"> <source>Declares an enumeration and defines the values of its members.</source> <target state="translated">宣告列舉,並定義其成員的值。</target> <note /> </trans-unit> <trans-unit id="Compares_two_expressions_and_returns_True_if_they_are_equal_Otherwise_returns_False"> <source>Compares two expressions and returns True if they are equal. Otherwise, returns False.</source> <target state="translated">比較兩個運算式,若兩者相等,即傳回 True; 否則傳回 False。</target> <note /> </trans-unit> <trans-unit id="Used_to_release_array_variables_and_deallocate_the_memory_used_for_their_elements"> <source>Used to release array variables and deallocate the memory used for their elements.</source> <target state="translated">用以釋放陣列變數,並取消配置其元素所使用的記憶體。</target> <note /> </trans-unit> <trans-unit id="Declares_a_user_defined_event"> <source>Declares a user-defined event.</source> <target state="translated">宣告使用者定義的事件。</target> <note /> </trans-unit> <trans-unit id="Exits_a_Sub_procedure_and_transfers_execution_immediately_to_the_statement_following_the_call_to_the_Sub_procedure"> <source>Exits a Sub procedure and transfers execution immediately to the statement following the call to the Sub procedure.</source> <target state="translated">結束 Sub 程序,並將執行立即轉移到接在 Sub 程序呼叫之後的陳述式。</target> <note /> </trans-unit> <trans-unit id="Raises_a_number_to_the_power_of_another_number"> <source>Raises a number to the power of another number.</source> <target state="translated">將數字的次方指定為另一個數字。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_the_external_procedure_being_referenced_in_the_Declare_statement_is_a_Function"> <source>Specifies that the external procedure being referenced in the Declare statement is a Function.</source> <target state="translated">指定 Declare 陳述式中所參考的外部程序是 Function。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_the_external_procedure_being_referenced_in_the_Declare_statement_is_a_Sub"> <source>Specifies that the external procedure being referenced in the Declare statement is a Sub.</source> <target state="translated">指定 Declare 陳述式中所參考的外部程序是 Sub。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_one_or_more_declared_programming_elements_are_accessible_only_from_within_the_assembly_that_contains_their_declaration"> <source>Specifies that one or more declared programming elements are accessible only from within the assembly that contains their declaration.</source> <target state="translated">指定一或多個宣告的程式設計元素,只能從包含其宣告的組件加以存取。</target> <note /> </trans-unit> <trans-unit id="Specifies_a_collection_and_a_range_variable_to_use_in_a_query"> <source>Specifies a collection and a range variable to use in a query.</source> <target state="translated">指定查詢中所使用的集合與範圍變數。</target> <note /> </trans-unit> <trans-unit id="Declares_the_name_parameters_and_code_that_define_a_Function_procedure_that_is_a_procedure_that_returns_a_value_to_the_calling_code"> <source>Declares the name, parameters, and code that define a Function procedure, that is, a procedure that returns a value to the calling code.</source> <target state="translated">宣告定義 Function 程序的名稱、參數與程式碼; 也就是説,這種程序會對呼叫的程式碼傳回值。</target> <note /> </trans-unit> <trans-unit id="Constrains_a_generic_type_parameter_to_require_that_any_type_argument_passed_to_it_be_a_reference_type"> <source>Constrains a generic type parameter to require that any type argument passed to it be a reference type.</source> <target state="translated">將泛型類型參數限制為傳遞給它的所有類型引數,都必須要是參考類型。</target> <note /> </trans-unit> <trans-unit id="Specifies_a_constructor_constraint_on_a_generic_type_parameter"> <source>Specifies a constructor constraint on a generic type parameter.</source> <target state="translated">指定泛型類型參數的建構函式條件約束。</target> <note /> </trans-unit> <trans-unit id="Constrains_a_generic_type_parameter_to_require_that_any_type_argument_passed_to_it_be_a_value_type"> <source>Constrains a generic type parameter to require that any type argument passed to it be a value type.</source> <target state="translated">將泛型類型參數限制為傳遞給它的所有類型引數,都必須要是實值類型。</target> <note /> </trans-unit> <trans-unit id="Declares_a_Get_property_procedure_that_is_used_to_return_the_current_value_of_a_property"> <source>Declares a Get property procedure that is used to return the current value of a property.</source> <target state="translated">宣告用以傳回屬性目前值的 Get 屬性程序。</target> <note /> </trans-unit> <trans-unit id="Compares_two_expressions_and_returns_True_if_the_first_is_greater_than_the_second_Otherwise_returns_False"> <source>Compares two expressions and returns True if the first is greater than the second. Otherwise, returns False.</source> <target state="translated">比較兩個運算式,若第一個運算式大於第二個運算式,即傳回 True; 否則傳回 False。</target> <note /> </trans-unit> <trans-unit id="Compares_two_expressions_and_returns_True_if_the_first_is_greater_than_or_equal_to_the_second_Otherwise_returns_False"> <source>Compares two expressions and returns True if the first is greater than or equal to the second. Otherwise, returns False.</source> <target state="translated">比較兩個運算式,若第一個運算式大於或等於第二個運算式,即傳回 True; 否則傳回 False。</target> <note /> </trans-unit> <trans-unit id="Declares_that_a_procedure_handles_a_specified_event"> <source>Declares that a procedure handles a specified event.</source> <target state="translated">宣告程序會處理指定的事件。</target> <note /> </trans-unit> <trans-unit id="Indicates_that_a_class_or_structure_member_is_providing_the_implementation_for_a_member_defined_in_an_interface"> <source>Indicates that a class or structure member is providing the implementation for a member defined in an interface.</source> <target state="translated">表示類別或結構成員將提供介面中定義之成員的實作。</target> <note /> </trans-unit> <trans-unit id="Specifies_one_or_more_interfaces_or_interface_members_that_must_be_implemented_in_the_class_or_structure_definition_in_which_the_Implements_statement_appears"> <source>Specifies one or more interfaces, or interface members, that must be implemented in the class or structure definition in which the Implements statement appears.</source> <target state="translated">指定必須在出現 Implements 陳述式的類別或結構定義中實作的一或多個介面或介面成員。</target> <note /> </trans-unit> <trans-unit id="Imports_all_or_specified_elements_of_a_namespace_into_a_file"> <source>Imports all or specified elements of a namespace into a file.</source> <target state="translated">將命名空間的所有元素或指定元素,匯入至檔案。</target> <note /> </trans-unit> <trans-unit id="Specifies_the_group_that_the_loop_variable_in_a_For_Each_statement_is_to_traverse"> <source>Specifies the group that the loop variable in a For Each statement is to traverse.</source> <target state="translated">指定 For Each 陳述式中迴圈變數要周遊的群組。</target> <note /> </trans-unit> <trans-unit id="Specifies_the_group_that_the_loop_variable_is_to_traverse_in_a_For_Each_statement_or_specifies_the_range_variable_in_a_query"> <source>Specifies the group that the loop variable is to traverse in a For Each statement, or specifies the range variable in a query.</source> <target state="translated">指定 For Each 陳述式中迴圈變數要周遊的群組,或指定查詢中的範圍變數。</target> <note /> </trans-unit> <trans-unit id="Causes_the_current_class_or_interface_to_inherit_the_attributes_variables_properties_procedures_and_events_from_another_class_or_set_of_interfaces"> <source>Causes the current class or interface to inherit the attributes, variables, properties, procedures, and events from another class or set of interfaces.</source> <target state="translated">讓目前的類別或介面,從另一個類別或介面集合繼承屬性 (Attribute)、變數、屬性 (Property)、程序及事件。</target> <note /> </trans-unit> <trans-unit id="Specifies_the_group_that_the_range_variable_is_to_traverse_in_a_query"> <source>Specifies the group that the range variable is to traverse in a query.</source> <target state="translated">指定查詢中範圍變數要周遊的群組。</target> <note /> </trans-unit> <trans-unit id="Divides_two_numbers_and_returns_an_integer_result"> <source>Divides two numbers and returns an integer result.</source> <target state="translated">將兩個數值相除,傳回整數結果。</target> <note /> </trans-unit> <trans-unit id="Declares_the_name_of_an_interface_and_the_definitions_of_the_members_of_the_interface"> <source>Declares the name of an interface and the definitions of the members of the interface.</source> <target state="translated">宣告介面的名稱與介面成員的定義。</target> <note /> </trans-unit> <trans-unit id="Determines_whether_an_expression_is_false_If_instances_of_any_class_or_structure_will_be_used_in_an_OrElse_clause_you_must_define_IsFalse_on_that_class_or_structure"> <source>Determines whether an expression is false. If instances of any class or structure will be used in an OrElse clause, you must define IsFalse on that class or structure.</source> <target state="translated">判斷運算式是否為 False。若在 OrElse 子句中會出現任何類別或結構,您必須在該類別或結構上定義 IsFalse。</target> <note /> </trans-unit> <trans-unit id="Compares_two_object_reference_variables_and_returns_True_if_the_objects_are_equal_result_object1_Is_object2"> <source>Compares two object reference variables and returns True if the objects are equal. &lt;result&gt; = &lt;object1&gt; Is &lt;object2&gt;</source> <target state="translated">比較兩個物件參考變數,若物件相等,即傳回 True。 &lt;result&gt; = &lt;object1&gt; Is &lt;object2&gt;</target> <note /> </trans-unit> <trans-unit id="Compares_two_object_reference_variables_and_returns_True_if_the_objects_are_not_equal_result_object1_IsNot_object2"> <source>Compares two object reference variables and returns True if the objects are not equal. &lt;result&gt; = &lt;object1&gt; IsNot &lt;object2&gt;</source> <target state="translated">比較兩個物件參考變數,若物件不相等,即傳回 True。 &lt;result&gt; = &lt;object1&gt; IsNot &lt;object2&gt;</target> <note /> </trans-unit> <trans-unit id="Determines_whether_an_expression_is_true_If_instances_of_any_class_or_structure_will_be_used_in_an_OrElse_clause_you_must_define_IsTrue_on_that_class_or_structure"> <source>Determines whether an expression is true. If instances of any class or structure will be used in an OrElse clause, you must define IsTrue on that class or structure.</source> <target state="translated">判斷運算式是否為 True。若在 OrElse 子句會出現任何類別或結構,則必須在該類別或結構上定義 IsTrue。</target> <note /> </trans-unit> <trans-unit id="Indicates_an_iterator_method_that_can_use_the_Yield_statement"> <source>Indicates an iterator method that can use the Yield statement.</source> <target state="translated">指出可以使用 Yield 陳述式的 Iterator 方法。</target> <note /> </trans-unit> <trans-unit id="Defines_an_iterator_lambda_expression_that_can_use_the_Yield_statement_Iterator_Function_parameterList_As_IEnumerable_Of_T"> <source>Defines an iterator lambda expression that can use the Yield statement. Iterator Function(&lt;parameterList&gt;) As IEnumerable(Of &lt;T&gt;)</source> <target state="translated">定義可以使用 Yield 陳述式的 Iterator Lambda 運算式。 Iterator Function(&lt;parameterList&gt;) As IEnumerable(Of &lt;T&gt;)</target> <note /> </trans-unit> <trans-unit id="Performs_an_arithmetic_left_shift_on_a_bit_pattern"> <source>Performs an arithmetic left shift on a bit pattern.</source> <target state="translated">在位元模式上執行算術左位移。</target> <note /> </trans-unit> <trans-unit id="Compares_two_expressions_and_returns_True_if_the_first_is_less_than_the_second_Otherwise_returns_False"> <source>Compares two expressions and returns True if the first is less than the second. Otherwise, returns False.</source> <target state="translated">比較兩個運算式,若第一個運算式小於第二個運算式,即傳回 True; 否則傳回 False。</target> <note /> </trans-unit> <trans-unit id="Compares_two_expressions_and_returns_True_if_the_first_is_less_than_or_equal_to_the_second_Otherwise_returns_False"> <source>Compares two expressions and returns True if the first is less than or equal to the second. Otherwise, returns False.</source> <target state="translated">比較兩個運算式,若第一個運算式小於或等於第二個運算式,即傳回 True; 否則傳回 False。</target> <note /> </trans-unit> <trans-unit id="Introduces_a_clause_that_identifies_the_external_file_DLL_or_code_resource_containing_an_external_procedure"> <source>Introduces a clause that identifies the external file (DLL or code resource) containing an external procedure.</source> <target state="translated">引進能找出包含外部程序之外部檔案 (DLL 或程式碼資源) 的子句。</target> <note /> </trans-unit> <trans-unit id="Compares_a_string_against_a_pattern_Wildcards_available_include_to_match_1_character_and_to_match_0_or_more_characters_result_string_Like_pattern"> <source>Compares a string against a pattern. Wildcards available include ? to match 1 character and * to match 0 or more characters. &lt;result&gt; = &lt;string&gt; Like &lt;pattern&gt;</source> <target state="translated">將字串與模式相比。可用的萬用字元包括 ? (與 1 個字元相符) 以及 * (與 0 或多個字元相符)。 &lt;result&gt; = &lt;string&gt; Like &lt;pattern&gt;</target> <note /> </trans-unit> <trans-unit id="Returns_the_difference_between_two_numeric_expressions_or_the_negative_value_of_a_numeric_expression"> <source>Returns the difference between two numeric expressions, or the negative value of a numeric expression.</source> <target state="translated">傳回兩個數值運算式的差,或一個數值運算式的負值。</target> <note /> </trans-unit> <trans-unit id="Divides_two_numbers_and_returns_only_the_remainder_number1_Mod_number2"> <source>Divides two numbers and returns only the remainder. &lt;number1&gt; Mod &lt;number2&gt;</source> <target state="translated">將兩個數字相除,然後只傳回餘數。 &lt;數字 1&gt; Mod &lt;數字 2&gt;</target> <note /> </trans-unit> <trans-unit id="Specifies_that_an_attribute_at_the_beginning_of_a_source_file_applies_to_the_entire_module_Otherwise_the_attribute_will_apply_only_to_an_individual_programming_element_such_as_a_class_or_property"> <source>Specifies that an attribute at the beginning of a source file applies to the entire module. Otherwise the attribute will apply only to an individual programming element, such as a class or property.</source> <target state="translated">指定在原始程式檔開頭的屬性,會套用到整個模組。否則,屬性將只會套用到個別的程式設計元素,例如類別或屬性。</target> <note /> </trans-unit> <trans-unit id="Multiplies_two_numbers_and_returns_the_product"> <source>Multiplies two numbers and returns the product.</source> <target state="translated">將兩個數值相乘,然後傳回乘積。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_a_class_can_be_used_only_as_a_base_class_and_that_you_cannot_create_an_object_directly_from_it"> <source>Specifies that a class can be used only as a base class, and that you cannot create an object directly from it.</source> <target state="translated">指定類別只可用做為基底類別,且您無法直接從它建立物件。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_a_property_or_procedure_is_not_implemented_in_the_class_and_must_be_overridden_in_a_derived_class_before_it_can_be_used"> <source>Specifies that a property or procedure is not implemented in the class and must be overridden in a derived class before it can be used.</source> <target state="translated">指定未在類別中實作的屬性或程序,在使用之前必須於衍生的類別中加以覆寫。</target> <note /> </trans-unit> <trans-unit id="Declares_the_name_of_a_namespace_and_causes_the_source_code_following_the_declaration_to_be_compiled_within_that_namespace"> <source>Declares the name of a namespace, and causes the source code following the declaration to be compiled within that namespace.</source> <target state="translated">宣告命名空間的名稱,並讓接在宣告後的原始程式碼,會於該命名空間中編譯。</target> <note /> </trans-unit> <trans-unit id="Indicates_that_a_conversion_operator_CType_converts_a_class_or_structure_to_a_type_that_might_not_be_able_to_hold_some_of_the_possible_values_of_the_original_class_or_structure"> <source>Indicates that a conversion operator (CType) converts a class or structure to a type that might not be able to hold some of the possible values of the original class or structure.</source> <target state="translated">表示轉換運算子 (CType) 會將類別或結構轉換成可能無法容納原始類別或結構之某些可能值的類型。</target> <note /> </trans-unit> <trans-unit id="Compares_two_expressions_and_returns_True_if_they_are_not_equal_Otherwise_returns_False"> <source>Compares two expressions and returns True if they are not equal. Otherwise, returns False.</source> <target state="translated">比較兩個運算式,若兩者不相等,即傳回 True; 否則傳回 False。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_a_class_cannot_be_used_as_a_base_class"> <source>Specifies that a class cannot be used as a base class.</source> <target state="translated">指定類別不能用做為基底類別。</target> <note /> </trans-unit> <trans-unit id="Performs_logical_negation_on_a_Boolean_expression_or_bitwise_negation_on_a_numeric_expression_result_Not_expression"> <source>Performs logical negation on a Boolean expression, or bitwise negation on a numeric expression. &lt;result&gt; = Not &lt;expression&gt;</source> <target state="translated">在布林運算式上執行邏輯否定運算,或是在數值運算式上執行位元否定運算。 &lt;result&gt; = Not &lt;expression&gt;</target> <note /> </trans-unit> <trans-unit id="Specifies_that_a_property_or_procedure_cannot_be_overridden_in_a_derived_class"> <source>Specifies that a property or procedure cannot be overridden in a derived class.</source> <target state="translated">指定在衍生類別中不可覆寫屬性或程序。</target> <note /> </trans-unit> <trans-unit id="Identifies_a_type_parameter_on_a_generic_class_structure_interface_delegate_or_procedure"> <source>Identifies a type parameter on a generic class, structure, interface, delegate, or procedure.</source> <target state="translated">識別泛型類別、結構、介面、委派或程序的類型參數。</target> <note /> </trans-unit> <trans-unit id="Declares_the_operator_symbol_operands_and_code_that_define_an_operator_procedure_on_a_class_or_structure"> <source>Declares the operator symbol, operands, and code that define an operator procedure on a class or structure.</source> <target state="translated">宣告運算子符號、運算元與程式碼,以定義類別或結構的運算子程序。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_a_procedure_argument_can_be_omitted_when_the_procedure_is_called"> <source>Specifies that a procedure argument can be omitted when the procedure is called.</source> <target state="translated">指定呼叫程序時,可以省略程序引數。</target> <note /> </trans-unit> <trans-unit id="Introduces_a_statement_that_specifies_a_compiler_option_that_applies_to_the_entire_source_file"> <source>Introduces a statement that specifies a compiler option that applies to the entire source file.</source> <target state="translated">引進指定套用到整個原始程式檔之編譯器選項的陳述式。</target> <note /> </trans-unit> <trans-unit id="Performs_short_circuit_inclusive_logical_disjunction_on_two_expressions_Returns_True_if_either_operand_evaluates_to_True_If_the_first_expression_evaluates_to_True_the_second_expression_is_not_evaluated_result_expression1_OrElse_expression2"> <source>Performs short-circuit inclusive logical disjunction on two expressions. Returns True if either operand evaluates to True. If the first expression evaluates to True, the second expression is not evaluated. &lt;result&gt; = &lt;expression1&gt; OrElse &lt;expression2&gt;</source> <target state="translated">在兩個運算式上執行最少運算的內含邏輯分離。若任一運算元評估為 True,即傳回 True。若第一個運算式評估為 True,則不會評估第二個運算式。 &lt;result&gt; = &lt;expression1&gt; OrElse &lt;expression2&gt;</target> <note /> </trans-unit> <trans-unit id="Performs_an_inclusive_logical_disjunction_on_two_Boolean_expressions_or_a_bitwise_disjunction_on_two_numeric_expressions_For_Boolean_expressions_returns_True_if_at_least_one_operand_evaluates_to_True_Both_expressions_are_always_evaluated_result_expression1_Or_expression2"> <source>Performs an inclusive logical disjunction on two Boolean expressions, or a bitwise disjunction on two numeric expressions. For Boolean expressions, returns True if at least one operand evaluates to True. Both expressions are always evaluated. &lt;result&gt; = &lt;expression1&gt; Or &lt;expression2&gt;</source> <target state="translated">在兩個布林運算式上執行內含邏輯分離,或在兩個數值運算式上執行位元分離。對於布林運算式而言,若至少有一個運算元評估為 True,即傳回 True。兩個運算式都會進行評估。 &lt;result&gt; = &lt;expression1&gt; Or &lt;expression2&gt;</target> <note /> </trans-unit> <trans-unit id="Specifies_that_a_property_or_procedure_re_declares_one_or_more_existing_properties_or_procedures_with_the_same_name"> <source>Specifies that a property or procedure re-declares one or more existing properties or procedures with the same name.</source> <target state="translated">指定屬性或程序會重新宣告一或多個同名的現有屬性或程序。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_a_property_or_procedure_can_be_overridden_by_an_identically_named_property_or_procedure_in_a_derived_class"> <source>Specifies that a property or procedure can be overridden by an identically named property or procedure in a derived class.</source> <target state="translated">指定屬性或程序可由衍生類別中的同名屬性或程序覆寫。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_a_property_or_procedure_overrides_an_identically_named_property_or_procedure_inherited_from_a_base_class"> <source>Specifies that a property or procedure overrides an identically named property or procedure inherited from a base class.</source> <target state="translated">指定屬性或程序會覆寫繼承自基底類別的同名屬性或程序。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_a_procedure_parameter_takes_an_optional_array_of_elements_of_the_specified_type"> <source>Specifies that a procedure parameter takes an optional array of elements of the specified type.</source> <target state="translated">指定程序參數可會接受指定類型的選擇性元素陣列。</target> <note /> </trans-unit> <trans-unit id="Indicates_that_a_method_class_or_structure_declaration_is_a_partial_definition_of_the_method_class_or_structure"> <source>Indicates that a method, class, or structure declaration is a partial definition of the method, class, or structure.</source> <target state="translated">表示方法、類別或結構宣告,為方法、類別或結構的部分定義。</target> <note /> </trans-unit> <trans-unit id="Returns_the_sum_of_two_numbers_or_the_positive_value_of_a_numeric_expression"> <source>Returns the sum of two numbers, or the positive value of a numeric expression.</source> <target state="translated">傳回兩個數值的和,或數值運算式的正值。</target> <note /> </trans-unit> <trans-unit id="Prevents_the_contents_of_an_array_from_being_cleared_when_the_dimensions_of_the_array_are_changed"> <source>Prevents the contents of an array from being cleared when the dimensions of the array are changed.</source> <target state="translated">避免在變更陣列維度時,清除陣列內容。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_one_or_more_declared_programming_elements_are_accessible_only_from_within_their_module_class_or_structure"> <source>Specifies that one or more declared programming elements are accessible only from within their module, class, or structure.</source> <target state="translated">指定一或多個宣告的程式設計元素,只能從其模組、類別或結構加以存取。</target> <note /> </trans-unit> <trans-unit id="Declares_the_name_of_a_property_and_the_property_procedures_used_to_store_and_retrieve_the_value_of_the_property"> <source>Declares the name of a property, and the property procedures used to store and retrieve the value of the property.</source> <target state="translated">宣告屬性的名稱,以及用以儲存及擷取屬性值的屬性程序。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_one_or_more_declared_members_of_a_class_are_accessible_from_anywhere_in_the_same_assembly_their_own_classes_and_derived_classes"> <source>Specifies that one or more declared members of a class are accessible from anywhere in the same assembly, their own classes, and derived classes.</source> <target state="translated">指定類別的一或多個宣告成員,可從相同的組件、其本身的類別以及衍生類別中的任何位置加以存取。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_one_or_more_declared_programming_elements_are_accessible_only_from_within_their_own_class_or_from_a_derived_class"> <source>Specifies that one or more declared programming elements are accessible only from within their own class or from a derived class.</source> <target state="translated">指定一或多個宣告的程式設計元素,只能從其本身的類別或從衍生的類別加以存取。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_one_or_more_declared_programming_elements_have_no_access_restrictions"> <source>Specifies that one or more declared programming elements have no access restrictions.</source> <target state="translated">指定一或多個宣告的程式設計元素,沒有存取限制。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_a_variable_or_property_can_be_read_but_not_written_to"> <source>Specifies that a variable or property can be read but not written to.</source> <target state="translated">指定可讀取但無法寫入的變數或屬性。</target> <note /> </trans-unit> <trans-unit id="Reallocates_storage_space_for_an_array_variable"> <source>Reallocates storage space for an array variable.</source> <target state="translated">重新配置陣列變數的儲存空間。</target> <note /> </trans-unit> <trans-unit id="Performs_an_arithmetic_right_shift_on_a_bit_pattern"> <source>Performs an arithmetic right shift on a bit pattern</source> <target state="translated">在位元模式上執行算術右位移</target> <note /> </trans-unit> <trans-unit id="Declares_a_Set_property_procedure_that_is_used_to_assign_a_value_to_a_property"> <source>Declares a Set property procedure that is used to assign a value to a property.</source> <target state="translated">宣告用以為屬性指派值的 Set 屬性程序。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_a_declared_programming_element_redeclares_and_hides_an_identically_named_element_in_a_base_class"> <source>Specifies that a declared programming element redeclares and hides an identically named element in a base class.</source> <target state="translated">指定宣告的程式設計項目會重新宣告並隱藏基底類別中的同名項目。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_one_or_more_declared_programming_elements_are_associated_with_all_instances_of_a_class_or_structure"> <source>Specifies that one or more declared programming elements are associated with all instances of a class or structure.</source> <target state="translated">指定一或多個宣告的程式設計元素,其會與類別或結構的所有執行個體相關聯。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_one_or_more_declared_local_variables_are_to_remain_in_existence_and_retain_their_latest_values_after_the_procedure_in_which_they_are_declared_terminates"> <source>Specifies that one or more declared local variables are to remain in existence and retain their latest values after the procedure in which they are declared terminates.</source> <target state="translated">指定一或多個宣告的區域變數在宣告該變數的程序結束後,仍會持續存在且保留最後的值。</target> <note /> </trans-unit> <trans-unit id="Declares_the_name_of_a_structure_and_introduces_the_definition_of_the_variables_properties_events_and_procedures_that_make_up_the_structure"> <source>Declares the name of a structure and introduces the definition of the variables, properties, events, and procedures that make up the structure.</source> <target state="translated">宣告結構的名稱,並引進組成結構之變數、屬性、事件與程序的定義。</target> <note /> </trans-unit> <trans-unit id="Declares_the_name_parameters_and_code_that_define_a_Sub_procedure_that_is_a_procedure_that_does_not_return_a_value_to_the_calling_code"> <source>Declares the name, parameters, and code that define a Sub procedure, that is, a procedure that does not return a value to the calling code.</source> <target state="translated">宣告定義 Sub 程序的名稱、參數與程式碼; 也就是說,這種程序不會對呼叫的程式碼傳回值。</target> <note /> </trans-unit> <trans-unit id="Separates_the_beginning_and_ending_values_of_a_loop_counter_or_array_bounds_or_that_of_a_value_match_range"> <source>Separates the beginning and ending values of a loop counter or array bounds or that of a value match range.</source> <target state="translated">分隔迴圈計數器或陣列界限的起始值與結束值,或值比對範圍的起始值與結束值。</target> <note /> </trans-unit> <trans-unit id="Determines_the_run_time_type_of_an_object_reference_variable_and_compares_it_to_a_data_type_Returns_True_or_False_depending_on_whether_the_two_types_are_compatible_result_TypeOf_objectExpression_Is_typeName"> <source>Determines the run-time type of an object reference variable and compares it to a data type. Returns True or False depending, on whether the two types are compatible. &lt;result&gt; = TypeOf &lt;objectExpression&gt; Is &lt;typeName&gt;</source> <target state="translated">判斷物件參考變數的執行階段類型,並與資料類型進行比較。依兩種類型是否相容,而傳回 True 或 False。 &lt;result&gt; = TypeOf &lt;objectExpression&gt; Is &lt;typeName&gt;</target> <note /> </trans-unit> <trans-unit id="Used_in_a_Declare_statement_Specifies_that_Visual_Basic_should_marshal_all_strings_to_Unicode_values_in_a_call_into_an_external_procedure_and_should_look_up_the_procedure_without_modifying_its_name"> <source>Used in a Declare statement. Specifies that Visual Basic should marshal all strings to Unicode values in a call into an external procedure, and should look up the procedure without modifying its name.</source> <target state="translated">用於 Declare 陳述式中。指定 Visual Basic 應在呼叫外部程序中,將所有字串封送處理成 Unicode 值,且應在不修改程序名稱的情況下,查詢該程序。</target> <note /> </trans-unit> <trans-unit id="Indicates_that_a_conversion_operator_CType_converts_a_class_or_structure_to_a_type_that_can_hold_all_possible_values_of_the_original_class_or_structure"> <source>Indicates that a conversion operator (CType) converts a class or structure to a type that can hold all possible values of the original class or structure.</source> <target state="translated">表示轉換運算子 (CType) 會將類別或結構,轉換成可容納原始類別或結構之所有可能值的類型。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_one_or_more_declared_member_variables_refer_to_an_instance_of_a_class_that_can_raise_events"> <source>Specifies that one or more declared member variables refer to an instance of a class that can raise events</source> <target state="translated">指定一或多個宣告的成員變數會參考可能引發事件的類別執行個體</target> <note /> </trans-unit> <trans-unit id="Specifies_that_a_property_can_be_written_to_but_not_read"> <source>Specifies that a property can be written to but not read.</source> <target state="translated">指定可寫入但無法讀取的屬性。</target> <note /> </trans-unit> <trans-unit id="Performs_a_logical_exclusion_on_two_Boolean_expressions_or_a_bitwise_exclusion_on_two_numeric_expressions_For_Boolean_expressions_returns_True_if_exactly_one_of_the_expressions_evaluates_to_True_Both_expressions_are_always_evaluated_result_expression1_Xor_expression2"> <source>Performs a logical exclusion on two Boolean expressions, or a bitwise exclusion on two numeric expressions. For Boolean expressions, returns True if exactly one of the expressions evaluates to True. Both expressions are always evaluated. &lt;result&gt; = &lt;expression1&gt; Xor &lt;expression2&gt;</source> <target state="translated">在兩個布林運算式上執行邏輯排除,或在兩個數值運算式上執行位元排除。對於布林運算式而言,若剛好有一個運算元評估為 True,即傳回 True。兩個運算式都會進行評估。 &lt;result&gt; = &lt;expression1&gt; Xor &lt;expression2&gt;</target> <note /> </trans-unit> <trans-unit id="Applies_an_aggregation_function_such_as_Sum_Average_or_Count_to_a_sequence"> <source>Applies an aggregation function, such as Sum, Average, or Count to a sequence.</source> <target state="translated">套用彙總函式 (如 Sum、Average 或 Count) 到序列。</target> <note /> </trans-unit> <trans-unit id="Specifies_the_sort_order_for_an_Order_By_clause_in_a_query_The_smallest_element_will_appear_first"> <source>Specifies the sort order for an Order By clause in a query. The smallest element will appear first.</source> <target state="translated">指定查詢中 Order By 子句的排序順序。最小的元素最先出現。</target> <note /> </trans-unit> <trans-unit id="Sets_the_string_comparison_method_specified_in_Option_Compare_to_a_strict_binary_sort_order"> <source>Sets the string comparison method specified in Option Compare to a strict binary sort order.</source> <target state="translated">將 Option Compare 中指定的字串比較方法,設定為嚴格的二進位排序順序。</target> <note /> </trans-unit> <trans-unit id="Specifies_the_element_keys_used_for_grouping_in_Group_By_or_sort_order_in_Order_By"> <source>Specifies the element keys used for grouping (in Group By) or sort order (in Order By).</source> <target state="translated">指定用於分組 (Group By 中) 或排序順序 (Order By 中) 的元素索引鍵。</target> <note /> </trans-unit> <trans-unit id="Transfers_execution_to_a_Function_Sub_or_dynamic_link_library_DLL_procedure_bracket_Call_bracket_procedureName_bracket_argumentList_bracket"> <source>Transfers execution to a Function, Sub, or dynamic-link library (DLL) procedure. [Call] &lt;procedureName&gt; [(&lt;argumentList&gt;)]</source> <target state="translated">將執行轉移到 Function、Sub 或動態連結程式庫 (DLL) 程序。 [Call] &lt;procedureName&gt; [(&lt;argumentList&gt;)]</target> <note /> </trans-unit> <trans-unit id="Introduces_the_statements_to_run_if_none_of_the_previous_cases_in_the_Select_Case_statement_returns_True"> <source>Introduces the statements to run if none of the previous cases in the Select Case statement returns True.</source> <target state="translated">引進在 Select Case 陳述式中先前的案例都未傳回 True 時,會執行的陳述式。</target> <note /> </trans-unit> <trans-unit id="Followed_by_a_comparison_operator_and_then_an_expression_Case_Is_introduces_the_statements_to_run_if_the_Select_Case_expression_combined_with_the_Case_Is_expression_evaluates_to_True"> <source>Followed by a comparison operator and then an expression, Case Is introduces the statements to run if the Select Case expression combined with the Case Is expression evaluates to True.</source> <target state="translated">其後接著比較運算子,再接著運算式,Case Is 會引進當 Select Case 運算式與 Case Is 運算式組合在一起若評估為 True 時,所要執行的陳述式。</target> <note /> </trans-unit> <trans-unit id="Introduces_a_value_or_set_of_values_against_which_the_value_of_an_expression_in_a_Select_Case_statement_is_to_be_tested_Case_expression_expression1_To_expression2_bracket_Is_bracket_comparisonOperator_expression"> <source>Introduces a value, or set of values, against which the value of an expression in a Select Case statement is to be tested. Case {&lt;expression&gt;|&lt;expression1&gt; To &lt;expression2&gt;|[Is] &lt;comparisonOperator&gt; &lt;expression&gt;}</source> <target state="translated">引進一個值或一組值,並利用該值或該組值來測試 Select Case 陳述式中運算式的值。 Case {&lt;expression&gt;|&lt;expression1&gt; To &lt;expression2&gt;|[Is] &lt;comparisonOperator&gt; &lt;expression&gt;}</target> <note /> </trans-unit> <trans-unit id="Introduces_a_statement_block_to_be_run_if_the_specified_exception_occurs_inside_a_Try_block"> <source>Introduces a statement block to be run if the specified exception occurs inside a Try block.</source> <target state="translated">引進在 Try 區塊內發生指定的例外狀況時,所要執行的陳述式區塊。</target> <note /> </trans-unit> <trans-unit id="Sets_the_default_comparison_method_to_use_when_comparing_string_data_When_set_to_Text_uses_a_text_sort_order_that_is_not_case_sensitive_When_set_to_Binary_uses_a_strict_binary_sort_order_Option_Compare_Binary_Text"> <source>Sets the default comparison method to use when comparing string data. When set to Text, uses a text sort order that is not case sensitive. When set to Binary, uses a strict binary sort order. Option Compare {Binary | Text}</source> <target state="translated">設定比較字串資料時所用的預設比較方法。若設定為 Text,請使用不區分大小寫的文字排序順序。若設定為 Binary,請使用嚴格的二進位排序順序。 Option Compare {Binary | Text}</target> <note /> </trans-unit> <trans-unit id="Defines_a_conditional_compiler_constant_Conditional_compiler_constants_are_always_private_to_the_file_in_which_they_appear_The_expressions_used_to_initialize_them_can_contain_only_conditional_compiler_constants_and_literals"> <source>Defines a conditional compiler constant. Conditional compiler constants are always private to the file in which they appear. The expressions used to initialize them can contain only conditional compiler constants and literals.</source> <target state="translated">定義條件式編譯器常數。條件式編譯器常數在其所在之檔案中,一定會是私用常數。用於初始設定這類常數的運算式,只能包含條件式編譯器常數與常值。</target> <note /> </trans-unit> <trans-unit id="Transfers_execution_immediately_to_the_next_iteration_of_the_Do_loop"> <source>Transfers execution immediately to the next iteration of the Do loop.</source> <target state="translated">將執行立即轉移到 Do 迴圈的下一個反覆運算。</target> <note /> </trans-unit> <trans-unit id="Transfers_execution_immediately_to_the_next_iteration_of_the_For_loop"> <source>Transfers execution immediately to the next iteration of the For loop.</source> <target state="translated">將執行立即轉移到 For 迴圈的下一個反覆運算。</target> <note /> </trans-unit> <trans-unit id="Transfers_execution_immediately_to_the_next_iteration_of_the_loop_Can_be_used_in_a_Do_loop_a_For_loop_or_a_While_loop"> <source>Transfers execution immediately to the next iteration of the loop. Can be used in a Do loop, a For loop, or a While loop.</source> <target state="translated">將執行立即轉移到迴圈的下一個反覆運算。可用在 Do 迴圈、For 迴圈或 While 迴圈中。</target> <note /> </trans-unit> <trans-unit id="Transfers_execution_immediately_to_the_next_iteration_of_the_While_loop"> <source>Transfers execution immediately to the next iteration of the While loop.</source> <target state="translated">將執行立即轉移到 While 迴圈的下一個反覆運算。</target> <note /> </trans-unit> <trans-unit id="Specifies_the_sort_order_for_an_Order_By_clause_in_a_query_The_largest_element_will_appear_first"> <source>Specifies the sort order for an Order By clause in a query. The largest element will appear first.</source> <target state="translated">指定查詢中 Order By 子句的排序順序。最大的元素最先出現。</target> <note /> </trans-unit> <trans-unit id="Restricts_the_values_of_a_query_result_to_eliminate_duplicate_values"> <source>Restricts the values of a query result to eliminate duplicate values.</source> <target state="translated">限制查詢結果的值,以去除重複的值。</target> <note /> </trans-unit> <trans-unit id="Repeats_a_block_of_statements_while_a_Boolean_condition_is_true_or_until_the_condition_becomes_true_Do_Loop_While_Until_condition"> <source>Repeats a block of statements while a Boolean condition is true, or until the condition becomes true. Do...Loop {While | Until} &lt;condition&gt;</source> <target state="translated">在布林條件為 True 的情況下,或是在條件變成 True 之前,持續重複陳述式區塊。 Do...Loop {While | Until} &lt;condition&gt;</target> <note /> </trans-unit> <trans-unit id="Repeats_a_block_of_statements_until_a_Boolean_condition_becomes_true_Do_Until_condition_Loop"> <source>Repeats a block of statements until a Boolean condition becomes true. Do Until &lt;condition&gt;...Loop</source> <target state="translated">持續重複陳述式區塊,直到布林條件變成 True 為止。 Do Until &lt;condition&gt;...Loop</target> <note /> </trans-unit> <trans-unit id="Repeats_a_block_of_statements_while_a_Boolean_condition_is_true_Do_While_condition_Loop"> <source>Repeats a block of statements while a Boolean condition is true. Do While &lt;condition&gt;...Loop</source> <target state="translated">在布林條件為 True 的情況下,持續重複陳述式區塊。 Do While &lt;condition&gt;...Loop</target> <note /> </trans-unit> <trans-unit id="Introduces_a_group_of_statements_in_an_SharpIf_statement_that_is_compiled_if_no_previous_condition_evaluates_to_True"> <source>Introduces a group of statements in an #If statement that is compiled if no previous condition evaluates to True.</source> <target state="translated">在 #If 陳述式中引進引進若之前沒有條件評估為 True 時,就會編譯的一組陳述式。</target> <note /> </trans-unit> <trans-unit id="Introduces_a_condition_in_an_SharpIf_statement_that_is_tested_if_the_previous_conditional_test_evaluates_to_False"> <source>Introduces a condition in an #If statement that is tested if the previous conditional test evaluates to False.</source> <target state="translated">在 #If 陳述式中引進若之前的條件測試評估為 False 時,就會測試的條件。</target> <note /> </trans-unit> <trans-unit id="Introduces_a_condition_in_an_If_statement_that_is_to_be_tested_if_the_previous_conditional_test_fails"> <source>Introduces a condition in an If statement that is to be tested if the previous conditional test fails.</source> <target state="translated">在 If 陳述式中引進若之前的條件測試失敗,就會測試的條件。</target> <note /> </trans-unit> <trans-unit id="Introduces_a_group_of_statements_in_an_If_statement_that_is_executed_if_no_previous_condition_evaluates_to_True"> <source>Introduces a group of statements in an If statement that is executed if no previous condition evaluates to True.</source> <target state="translated">在 If 陳述式中引進若之前沒有條件評估為 True 時,就會執行的一組陳述式。</target> <note /> </trans-unit> <trans-unit id="Terminates_the_definition_of_an_SharpIf_block"> <source>Terminates the definition of an #If block.</source> <target state="translated">結束 #If 區塊的定義。</target> <note /> </trans-unit> <trans-unit id="Stops_execution_immediately"> <source>Stops execution immediately.</source> <target state="translated">立即停止執行。</target> <note /> </trans-unit> <trans-unit id="Terminates_a_SharpRegion_block"> <source>Terminates a #Region block.</source> <target state="translated">結束 #Region 區塊。</target> <note /> </trans-unit> <trans-unit id="Specifies_the_relationship_between_element_keys_to_use_as_the_basis_of_a_join_operation"> <source>Specifies the relationship between element keys to use as the basis of a join operation.</source> <target state="translated">指定元素索引鍵之間的關聯性,以用做為聯結作業的基礎。</target> <note /> </trans-unit> <trans-unit id="Simulates_the_occurrence_of_an_error"> <source>Simulates the occurrence of an error.</source> <target state="translated">模擬錯誤的發生。</target> <note /> </trans-unit> <trans-unit id="Exits_a_Do_loop_and_transfers_execution_immediately_to_the_statement_following_the_Loop_statement"> <source>Exits a Do loop and transfers execution immediately to the statement following the Loop statement.</source> <target state="translated">結束 Do 迴圈,將執行立即轉移到接在 Loop 陳述式之後的陳述式。</target> <note /> </trans-unit> <trans-unit id="Exits_a_For_loop_and_transfers_execution_immediately_to_the_statement_following_the_Next_statement"> <source>Exits a For loop and transfers execution immediately to the statement following the Next statement.</source> <target state="translated">結束 For 迴圈,並將執行立即轉移到接在 Next 陳述式之後的陳述式。</target> <note /> </trans-unit> <trans-unit id="Exits_a_procedure_or_block_and_transfers_execution_immediately_to_the_statement_following_the_procedure_call_or_block_definition_Exit_Do_For_Function_Property_Select_Sub_Try_While"> <source>Exits a procedure or block and transfers execution immediately to the statement following the procedure call or block definition. Exit {Do | For | Function | Property | Select | Sub | Try | While}</source> <target state="translated">結束程序或區塊,並將執行立即轉移到接在程序呼叫或區塊定義之後的陳述式。 Exit {Do | For | Function | Property | Select | Sub | Try | While}</target> <note /> </trans-unit> <trans-unit id="Exits_a_Select_block_and_transfers_execution_immediately_to_the_statement_following_the_End_Select_statement"> <source>Exits a Select block and transfers execution immediately to the statement following the End Select statement.</source> <target state="translated">結束 Select 區塊,並將執行立即轉移到接在 End Select 陳述式之後的陳述式。</target> <note /> </trans-unit> <trans-unit id="Exits_a_Try_block_and_transfers_execution_immediately_to_the_statement_following_the_End_Try_statement"> <source>Exits a Try block and transfers execution immediately to the statement following the End Try statement.</source> <target state="translated">結束 Try 區塊,將執行立即轉移到接在 End Try 陳述式之後的陳述式。</target> <note /> </trans-unit> <trans-unit id="Exits_a_While_loop_and_transfers_execution_immediately_to_the_statement_following_the_End_While_statement"> <source>Exits a While loop and transfers execution immediately to the statement following the End While statement.</source> <target state="translated">結束 While 迴圈,將執行立即轉移到接在 End While 陳述式之後的陳述式。</target> <note /> </trans-unit> <trans-unit id="When_set_to_On_requires_explicit_declaration_of_all_variables_using_a_Dim_Private_Public_or_ReDim_statement_Option_Explicit_On_Off"> <source>When set to On, requires explicit declaration of all variables, using a Dim, Private, Public, or ReDim statement. Option Explicit {On | Off}</source> <target state="translated">若設定為 On,則必須使用 Dim、Private、Public 或 ReDim 陳述式,明確地宣告所有變數。 Option Explicit {On | Off}</target> <note /> </trans-unit> <trans-unit id="Represents_a_Boolean_value_that_fails_a_conditional_test"> <source>Represents a Boolean value that fails a conditional test.</source> <target state="translated">代表條件測試失敗的布林值。</target> <note /> </trans-unit> <trans-unit id="Introduces_a_statement_block_to_be_run_before_exiting_a_Try_structure"> <source>Introduces a statement block to be run before exiting a Try structure.</source> <target state="translated">引進結束 Try 結構之前,所要執行的陳述式區塊。</target> <note /> </trans-unit> <trans-unit id="Introduces_a_loop_that_is_repeated_for_each_element_in_a_collection"> <source>Introduces a loop that is repeated for each element in a collection.</source> <target state="translated">引進為集合中每個元素重複運算的迴圈。</target> <note /> </trans-unit> <trans-unit id="Introduces_a_loop_that_is_iterated_a_specified_number_of_times"> <source>Introduces a loop that is iterated a specified number of times.</source> <target state="translated">引進會重複指定次數的迴圈。</target> <note /> </trans-unit> <trans-unit id="Identifies_a_list_of_values_as_a_collection_initializer"> <source>Identifies a list of values as a collection initializer</source> <target state="translated">將值的清單指定為集合初始設定式</target> <note /> </trans-unit> <trans-unit id="Branches_unconditionally_to_a_specified_line_in_a_procedure"> <source>Branches unconditionally to a specified line in a procedure.</source> <target state="translated">無條件分支到程序中的指定行。</target> <note /> </trans-unit> <trans-unit id="Groups_elements_that_have_a_common_key"> <source>Groups elements that have a common key.</source> <target state="translated">將具有共同索引鍵的元素分在一組。</target> <note /> </trans-unit> <trans-unit id="Combines_the_elements_of_two_sequences_and_groups_the_results_The_join_operation_is_based_on_matching_keys"> <source>Combines the elements of two sequences and groups the results. The join operation is based on matching keys.</source> <target state="translated">結合兩個序列的元素,並將結果分組。聯結作業會以相符的索引鍵為依據。</target> <note /> </trans-unit> <trans-unit id="Use_Group_to_specify_that_a_group_named_0_should_be_created"> <source>Use 'Group' to specify that a group named '{0}' should be created.</source> <target state="translated">Group' 可用以指定應建立名為 '{0}' 的群組。</target> <note /> </trans-unit> <trans-unit id="Use_Group_to_specify_that_a_group_named_Group_should_be_created"> <source>Use 'Group' to specify that a group named 'Group' should be created.</source> <target state="translated">Group' 可用以指定應建立名為 'Group' 的群組。</target> <note /> </trans-unit> <trans-unit id="Conditionally_compiles_selected_blocks_of_code_depending_on_the_value_of_an_expression"> <source>Conditionally compiles selected blocks of code, depending on the value of an expression.</source> <target state="translated">根據運算式的值,有條件地編譯選取的程式碼區塊。</target> <note /> </trans-unit> <trans-unit id="Conditionally_executes_a_group_of_statements_depending_on_the_value_of_an_expression"> <source>Conditionally executes a group of statements, depending on the value of an expression.</source> <target state="translated">根據運算式的值,有條件地執行陳述式群組。</target> <note /> </trans-unit> <trans-unit id="When_set_to_On_allows_the_use_of_local_type_inference_in_declaring_variables_Option_Infer_On_Off"> <source>When set to On, allows the use of local type inference in declaring variables. Option Infer {On | Off}</source> <target state="translated">若設定為 On,則可以在宣告變數中使用區域類型推斷。 Option Infer {On | Off}</target> <note /> </trans-unit> <trans-unit id="Specifies_an_identifier_that_can_serve_as_a_reference_to_the_results_of_a_join_or_grouping_subexpression"> <source>Specifies an identifier that can serve as a reference to the results of a join or grouping subexpression.</source> <target state="translated">指定可做為聯結或分組子運算式結果參考的識別項。</target> <note /> </trans-unit> <trans-unit id="Combines_the_elements_of_two_sequences_The_join_operation_is_based_on_matching_keys"> <source>Combines the elements of two sequences. The join operation is based on matching keys.</source> <target state="translated">結合兩個序列的元素。聯結作業會以相符的索引鍵為依據。</target> <note /> </trans-unit> <trans-unit id="Identifies_a_key_field_in_an_anonymous_type_definition"> <source>Identifies a key field in an anonymous type definition.</source> <target state="translated">指出匿名類型定義中的索引鍵欄位。</target> <note /> </trans-unit> <trans-unit id="Computes_a_value_for_each_item_in_the_query_and_assigns_the_value_to_a_new_range_variable"> <source>Computes a value for each item in the query, and assigns the value to a new range variable.</source> <target state="translated">計算查詢中每個項目的值,並將值指派給新的範圍變數。</target> <note /> </trans-unit> <trans-unit id="Terminates_a_loop_that_is_introduced_with_a_Do_statement"> <source>Terminates a loop that is introduced with a Do statement.</source> <target state="translated">結束利用 Do 陳述式所引進的迴圈。</target> <note /> </trans-unit> <trans-unit id="Repeats_a_block_of_statements_until_a_Boolean_condition_becomes_true_Do_Loop_Until_condition"> <source>Repeats a block of statements until a Boolean condition becomes true. Do...Loop Until &lt;condition&gt;</source> <target state="translated">持續重複陳述式區塊,直到布林條件變成 True 為止。 Do...Loop Until &lt;condition&gt;</target> <note /> </trans-unit> <trans-unit id="Repeats_a_block_of_statements_while_a_Boolean_condition_is_true_Do_Loop_While_condition"> <source>Repeats a block of statements while a Boolean condition is true. Do...Loop While &lt;condition&gt;</source> <target state="translated">在布林條件為 True 的情況下,持續重複陳述式區塊。 Do...Loop While &lt;condition&gt;</target> <note /> </trans-unit> <trans-unit id="Provides_a_way_to_refer_to_the_current_instance_of_a_class_or_structure_that_is_the_instance_in_which_the_code_is_running"> <source>Provides a way to refer to the current instance of a class or structure, that is, the instance in which the code is running.</source> <target state="translated">提供一種方法,來參考類別或結構目前的執行個體,也就是執行此程式碼的執行個體。</target> <note /> </trans-unit> <trans-unit id="Provides_a_way_to_refer_to_the_base_class_of_the_current_class_instance_You_cannot_use_MyBase_to_call_MustOverride_base_methods"> <source>Provides a way to refer to the base class of the current class instance. You cannot use MyBase to call MustOverride base methods.</source> <target state="translated">提供一種方法,來參考目前類別執行個體的基底類別。您無法使用 MyBase 呼叫 MustOverride 基底方法。</target> <note /> </trans-unit> <trans-unit id="Provides_a_way_to_refer_to_the_class_instance_members_as_originally_implemented_ignoring_any_derived_class_overrides"> <source>Provides a way to refer to the class instance members as originally implemented, ignoring any derived class overrides.</source> <target state="translated">提供一種方法,在忽略任何衍生之類別覆寫的情況下,以原始實作方式參考類別執行個體成員。</target> <note /> </trans-unit> <trans-unit id="Creates_a_new_object_instance"> <source>Creates a new object instance.</source> <target state="translated">建立新的物件執行個體。</target> <note /> </trans-unit> <trans-unit id="Terminates_a_loop_that_iterates_through_the_values_of_a_loop_variable"> <source>Terminates a loop that iterates through the values of a loop variable.</source> <target state="translated">反覆執行迴圈變數所指定的次數後,結束迴圈。</target> <note /> </trans-unit> <trans-unit id="Represents_the_default_value_of_any_data_type"> <source>Represents the default value of any data type.</source> <target state="translated">代表任何資料類型的預設值。</target> <note /> </trans-unit> <trans-unit id="Turns_a_compiler_option_off"> <source>Turns a compiler option off.</source> <target state="translated">關閉編譯器選項。</target> <note /> </trans-unit> <trans-unit id="Enables_the_error_handling_routine_that_starts_at_the_line_specified_in_the_line_argument_The_specified_line_must_be_in_the_same_procedure_as_the_On_Error_statement_On_Error_GoTo_bracket_label_0_1_bracket"> <source>Enables the error-handling routine that starts at the line specified in the line argument. The specified line must be in the same procedure as the On Error statement. On Error GoTo [&lt;label&gt; | 0 | -1]</source> <target state="translated">啟用錯誤處理常式,於行引數中所指定的行開始。 指定的行與 On Error 陳述式必須在同一個程序中。 On Error GoTo [&lt;label&gt; | 0 | -1]</target> <note /> </trans-unit> <trans-unit id="When_a_run_time_error_occurs_execution_transfers_to_the_statement_following_the_statement_or_procedure_call_that_resulted_in_the_error"> <source>When a run-time error occurs, execution transfers to the statement following the statement or procedure call that resulted in the error.</source> <target state="translated">發生執行階段錯誤時,執行會轉移到接著造成錯誤之陳述式或程序呼叫後的陳述式。</target> <note /> </trans-unit> <trans-unit id="Turns_a_compiler_option_on"> <source>Turns a compiler option on.</source> <target state="translated">開啟編譯器選項。</target> <note /> </trans-unit> <trans-unit id="Specifies_the_element_keys_used_to_correlate_sequences_for_a_join_operation"> <source>Specifies the element keys used to correlate sequences for a join operation.</source> <target state="translated">指定用以將聯結作業的序列相互關聯的元素索引鍵。</target> <note /> </trans-unit> <trans-unit id="Specifies_the_sort_order_for_columns_in_a_query_Can_be_followed_by_either_the_Ascending_or_the_Descending_keyword_If_neither_is_specified_Ascending_is_used"> <source>Specifies the sort order for columns in a query. Can be followed by either the Ascending or the Descending keyword. If neither is specified, Ascending is used.</source> <target state="translated">指定查詢中資料行的排序順序。其後可接著 Ascending 或 Descending 關鍵字,若都未指定,則會使用 Ascending。</target> <note /> </trans-unit> <trans-unit id="Specifies_the_statements_to_run_when_the_event_is_raised_by_the_RaiseEvent_statement_RaiseEvent_delegateSignature_End_RaiseEvent"> <source>Specifies the statements to run when the event is raised by the RaiseEvent statement. RaiseEvent(&lt;delegateSignature&gt;)...End RaiseEvent</source> <target state="translated">指定當 RaiseEvent 陳述式引發事件時,所要執行的陳述式。 RaiseEvent(&lt;delegateSignature&gt;)...End RaiseEvent</target> <note /> </trans-unit> <trans-unit id="Triggers_an_event_declared_at_module_level_within_a_class_form_or_document_RaiseEvent_eventName_bracket_argumentList_bracket"> <source>Triggers an event declared at module level within a class, form, or document. RaiseEvent &lt;eventName&gt; [(&lt;argumentList&gt;)]</source> <target state="translated">觸發於類別、表單或文件內的模組層級,所宣告的事件。 RaiseEvent &lt;eventName&gt; [(&lt;argumentList&gt;)]</target> <note /> </trans-unit> <trans-unit id="Collapses_and_hides_sections_of_code_in_Visual_Basic_files"> <source>Collapses and hides sections of code in Visual Basic files.</source> <target state="translated">摺疊並隱藏 Visual Basic 檔案中的程式碼區段。</target> <note /> </trans-unit> <trans-unit id="Returns_execution_to_the_code_that_called_the_Function_Sub_Get_Set_or_Operator_procedure_Return_or_Return_expression"> <source>Returns execution to the code that called the Function, Sub, Get, Set, or Operator procedure. Return -or- Return &lt;expression&gt;</source> <target state="translated">將執行傳回呼叫 Function、Sub、Get、Set 或 Operator 程序的程式碼。 Return -或- Return &lt;expression&gt;</target> <note /> </trans-unit> <trans-unit id="Runs_one_of_several_groups_of_statements_depending_on_the_value_of_an_expression"> <source>Runs one of several groups of statements, depending on the value of an expression.</source> <target state="translated">根據運算式的值,執行幾組陳述式中的一組。</target> <note /> </trans-unit> <trans-unit id="Specifies_which_columns_to_include_in_the_result_of_a_query"> <source>Specifies which columns to include in the result of a query.</source> <target state="translated">指定查詢結果中要包含的資料行。</target> <note /> </trans-unit> <trans-unit id="Skips_elements_up_to_a_specified_position_in_the_collection"> <source>Skips elements up to a specified position in the collection.</source> <target state="translated">略過集合中最多到指定位置為止的元素。</target> <note /> </trans-unit> <trans-unit id="Specifies_how_much_to_increment_between_each_loop_iteration"> <source>Specifies how much to increment between each loop iteration.</source> <target state="translated">指定每個迴圈反覆運算之間的增量。</target> <note /> </trans-unit> <trans-unit id="Suspends_program_execution"> <source>Suspends program execution.</source> <target state="translated">暫停程式的執行。</target> <note /> </trans-unit> <trans-unit id="When_set_to_On_restricts_implicit_data_type_conversions_to_only_widening_conversions_Option_Strict_On_Off"> <source>When set to On, restricts implicit data type conversions to only widening conversions. Option Strict {On | Off}</source> <target state="translated">若設定為 On,則隱含資料類型轉換將會限制為只有擴展轉換。 Option Strict {On | Off}</target> <note /> </trans-unit> <trans-unit id="Ensures_that_multiple_threads_do_not_execute_the_statement_block_at_the_same_time_SyncLock_object_End_Synclock"> <source>Ensures that multiple threads do not execute the statement block at the same time. SyncLock &lt;object&gt;...End Synclock</source> <target state="translated">確定不會有多個執行緒同時執行此陳述式區塊。 SyncLock &lt;object&gt;...End Synclock</target> <note /> </trans-unit> <trans-unit id="Includes_elements_up_to_a_specified_position_in_the_collection"> <source>Includes elements up to a specified position in the collection.</source> <target state="translated">包含集合中最多到指定位置為止的元素。</target> <note /> </trans-unit> <trans-unit id="Sets_the_string_comparison_method_specified_in_Option_Compare_to_a_text_sort_order_that_is_not_case_sensitive"> <source>Sets the string comparison method specified in Option Compare to a text sort order that is not case sensitive.</source> <target state="translated">將 Option Compare 中指定的字串比較方法,設定為不區分大小寫的文字排序順序。</target> <note /> </trans-unit> <trans-unit id="Introduces_a_statement_block_to_be_compiled_or_executed_if_a_tested_condition_is_true"> <source>Introduces a statement block to be compiled or executed if a tested condition is true.</source> <target state="translated">引進在測試的條件為 True 時,所要編譯或執行的陳述式區塊。</target> <note /> </trans-unit> <trans-unit id="Throws_an_exception_within_a_procedure_so_that_you_can_handle_it_with_structured_or_unstructured_exception_handling_code"> <source>Throws an exception within a procedure so that you can handle it with structured or unstructured exception-handling code.</source> <target state="translated">在程序中擲回例外狀況,使您能夠以結構化或無結構的例外狀況處理程式碼,來處理該例外狀況。</target> <note /> </trans-unit> <trans-unit id="Represents_a_Boolean_value_that_passes_a_conditional_test"> <source>Represents a Boolean value that passes a conditional test.</source> <target state="translated">代表通過條件測試的布林值。</target> <note /> </trans-unit> <trans-unit id="Provides_a_way_to_handle_some_or_all_possible_errors_that_might_occur_in_a_given_block_of_code_while_still_running_the_code_Try_bracket_Catch_bracket_Catch_Finally_End_Try"> <source>Provides a way to handle some or all possible errors that might occur in a given block of code, while still running the code. Try...[Catch]...{Catch | Finally}...End Try</source> <target state="translated">提供一種方法,在仍然繼續執行程式碼的情況下,處理指定程式碼區塊中可能發生的一些或所有錯誤。 Try...[Catch]...{Catch | Finally}...End Try</target> <note /> </trans-unit> <trans-unit id="A_Using_block_does_three_things_colon_it_creates_and_initializes_variables_in_the_resource_list_it_runs_the_code_in_the_block_and_it_disposes_of_the_variables_before_exiting_Resources_used_in_the_Using_block_must_implement_System_IDisposable_Using_resource1_bracket_resource2_bracket_End_Using"> <source>A Using block does three things: it creates and initializes variables in the resource list, it runs the code in the block, and it disposes of the variables before exiting. Resources used in the Using block must implement System.IDisposable. Using &lt;resource1&gt;[, &lt;resource2&gt;]...End Using</source> <target state="translated">Using 區塊有以下三個作用: 建立及初始設定資源清單中的變數、執行區塊中的程式碼,以及在結束前處置變數。Using 區塊中使用的資源,必須實作 System.IDisposable。 Using &lt;resource1&gt;[, &lt;resource2&gt;]...End Using</target> <note /> </trans-unit> <trans-unit id="Adds_a_conditional_test_to_a_Catch_statement_Exceptions_are_caught_by_that_Catch_statement_only_when_the_conditional_test_that_follows_the_When_keyword_evaluates_to_True"> <source>Adds a conditional test to a Catch statement. Exceptions are caught by that Catch statement only when the conditional test that follows the When keyword evaluates to True.</source> <target state="translated">在 Catch 陳述式中加入條件測試。只有接在 When 關鍵字之後的條件測試,評估為 True 時,Catch 陳述式才會捕捉到例外狀況。</target> <note /> </trans-unit> <trans-unit id="Specifies_the_filtering_condition_for_a_range_variable_in_a_query"> <source>Specifies the filtering condition for a range variable in a query.</source> <target state="translated">指定查詢中範圍變數的篩選條件。</target> <note /> </trans-unit> <trans-unit id="Runs_a_series_of_statements_as_long_as_a_given_condition_is_true"> <source>Runs a series of statements as long as a given condition is true.</source> <target state="translated">在指定的條件為 True 的情況下,執行一系列的陳述式。</target> <note /> </trans-unit> <trans-unit id="Specifies_a_condition_for_Skip_and_Take_operations_Elements_will_be_bypassed_or_included_as_long_as_the_condition_is_true"> <source>Specifies a condition for Skip and Take operations. Elements will be bypassed or included as long as the condition is true.</source> <target state="translated">指定 Skip 和 Take 作業的條件。只要條件為 True,就會略過或包含這些項目。</target> <note /> </trans-unit> <trans-unit id="Specifies_the_declaration_of_property_initializations_in_an_object_initializer_New_typeName_With_bracket_property_expression_bracket_bracket_bracket"> <source>Specifies the declaration of property initializations in an object initializer. New &lt;typeName&gt; With {[.&lt;property&gt; = &lt;expression&gt;][,...]}</source> <target state="translated">指定物件初始設定式中屬性初始設定的宣告。 New &lt;typeName&gt; With {[.&lt;property&gt; = &lt;expression&gt;][,...]}</target> <note /> </trans-unit> <trans-unit id="Runs_a_series_of_statements_that_refer_to_a_single_object_or_structure_With_object_End_With"> <source>Runs a series of statements that refer to a single object or structure. With &lt;object&gt;...End With</source> <target state="translated">執行一系列參考單一物件或結構的陳述式。 With &lt;object&gt;...End With</target> <note /> </trans-unit> <trans-unit id="Produces_an_element_of_an_IEnumerable_or_IEnumerator"> <source>Produces an element of an IEnumerable or IEnumerator.</source> <target state="translated">產生 IEnumerable 或 IEnumerator 的元素。</target> <note /> </trans-unit> <trans-unit id="Defines_an_asynchronous_lambda_expression_that_can_use_the_Await_operator_Can_be_used_wherever_a_delegate_type_is_expected_Async_Sub_Function_parameterList_expression"> <source>Defines an asynchronous lambda expression that can use the Await operator. Can be used wherever a delegate type is expected. Async Sub/Function(&lt;parameterList&gt;) &lt;expression&gt;</source> <target state="translated">定義可以使用 Await 運算子的非同步 Lambda 運算式。可用於必須是委派類型時。 Async Sub/Function(&lt;parameterList&gt;) &lt;expression&gt;</target> <note /> </trans-unit> <trans-unit id="Defines_a_lambda_expression_that_calculates_and_returns_a_single_value_Can_be_used_wherever_a_delegate_type_is_expected_Function_parameterList_expression"> <source>Defines a lambda expression that calculates and returns a single value. Can be used wherever a delegate type is expected. Function(&lt;parameterList&gt;) &lt;expression&gt;</source> <target state="translated">定義計算並傳回單一值的 Lambda 運算式。可用於必須是委派類型時。 Function(&lt;parameterList&gt;) &lt;expression&gt;</target> <note /> </trans-unit> <trans-unit id="Defines_a_lambda_expression_that_can_execute_statements_and_does_not_return_a_value_Can_be_used_wherever_a_delegate_type_is_expected_Sub_parameterList_statement"> <source>Defines a lambda expression that can execute statements and does not return a value. Can be used wherever a delegate type is expected. Sub(&lt;parameterList&gt;) &lt;statement&gt;</source> <target state="translated">定義可執行陳述式但不傳回值的 Lambda 運算式。可用於必須是委派類型時。 Sub(&lt;parameterList&gt;) &lt;statement&gt;</target> <note /> </trans-unit> <trans-unit id="Disables_reporting_of_specified_warnings_in_the_portion_of_the_source_file_below_the_current_line"> <source>Disables reporting of specified warnings in the portion of the source file below the current line.</source> <target state="translated">停用目前這一行下方原始程式檔部分中,指定之警告的回報功能。</target> <note /> </trans-unit> <trans-unit id="Enables_reporting_of_specified_warnings_in_the_portion_of_the_source_file_below_the_current_line"> <source>Enables reporting of specified warnings in the portion of the source file below the current line.</source> <target state="translated">啟用目前這一行下方原始程式檔部分中,指定之警告的回報功能。</target> <note /> </trans-unit> <trans-unit id="Insert_Await"> <source>Insert 'Await'.</source> <target state="translated">插入 'Await'。</target> <note /> </trans-unit> <trans-unit id="Make_0_an_Async_Function"> <source>Make {0} an Async Function.</source> <target state="translated">讓 {0} 成為非同步函式。</target> <note /> </trans-unit> <trans-unit id="Convert_0_to_Iterator"> <source>Convert {0} to Iterator</source> <target state="translated">將 {0} 轉換為 Iterator</target> <note /> </trans-unit> <trans-unit id="Replace_Return_with_Yield"> <source>Replace 'Return' with 'Yield</source> <target state="translated">以 'Yield' 取代 'Return'</target> <note /> </trans-unit> <trans-unit id="Use_the_correct_control_variable"> <source>Use the correct control variable</source> <target state="translated">使用正確的控制變數</target> <note /> </trans-unit> <trans-unit id="NameOf_function"> <source>NameOf function</source> <target state="translated">NameOf 函式</target> <note /> </trans-unit> <trans-unit id="Generate_narrowing_conversion_in_0"> <source>Generate narrowing conversion in '{0}'</source> <target state="translated">在 '{0}' 中產生縮小轉換</target> <note /> </trans-unit> <trans-unit id="Generate_widening_conversion_in_0"> <source>Generate widening conversion in '{0}'</source> <target state="translated">在 '{0}' 中產生放大轉換</target> <note /> </trans-unit> <trans-unit id="Try_block"> <source>Try block</source> <target state="translated">Try 區塊</target> <note>{Locked="Try"} "Try" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Catch_clause"> <source>Catch clause</source> <target state="translated">Catch 子句</target> <note>{Locked="Catch"} "Catch" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Finally_clause"> <source>Finally clause</source> <target state="translated">Finally 子句</target> <note>{Locked="Finally"} "Finally" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Using_statement"> <source>Using statement</source> <target state="translated">Using 陳述式</target> <note>{Locked="Using"} "Using" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Using_block"> <source>Using block</source> <target state="translated">Using 區塊</target> <note>{Locked="Using"} "Using" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="With_statement"> <source>With statement</source> <target state="translated">With 陳述式</target> <note>{Locked="With"} "With" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="With_block"> <source>With block</source> <target state="translated">With 區塊</target> <note>{Locked="With"} "With" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="SyncLock_statement"> <source>SyncLock statement</source> <target state="translated">SyncLock 陳述式</target> <note>{Locked="SyncLock"} "SyncLock" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="SyncLock_block"> <source>SyncLock block</source> <target state="translated">SyncLock 區塊</target> <note>{Locked="SyncLock"} "SyncLock" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="For_Each_statement"> <source>For Each statement</source> <target state="translated">For Each 陳述式</target> <note>{Locked="For Each"} "For Each" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="For_Each_block"> <source>For Each block</source> <target state="translated">For Each 區塊</target> <note>{Locked="For Each"} "For Each" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="On_Error_statement"> <source>On Error statement</source> <target state="translated">On Error 陳述式</target> <note>{Locked="On Error"} "On Error" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Resume_statement"> <source>Resume statement</source> <target state="translated">Resume 陳述式</target> <note>{Locked="Resume"} "Resume" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Yield_statement"> <source>Yield statement</source> <target state="translated">Yield 陳述式</target> <note>{Locked="Yield"} "Yield" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Await_expression"> <source>Await expression</source> <target state="translated">Await 運算式</target> <note>{Locked="Await"} "Await" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Lambda"> <source>Lambda</source> <target state="translated">Lambda</target> <note /> </trans-unit> <trans-unit id="Where_clause"> <source>Where clause</source> <target state="translated">Where 子句</target> <note>{Locked="Where"} "Where" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Select_clause"> <source>Select clause</source> <target state="translated">Select 子句</target> <note>{Locked="Select"} "Select" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="From_clause"> <source>From clause</source> <target state="translated">From 子句</target> <note>{Locked="From"} "From" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Aggregate_clause"> <source>Aggregate clause</source> <target state="translated">Aggregate 子句</target> <note>{Locked="Aggregate"} "Aggregate" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Let_clause"> <source>Let clause</source> <target state="translated">Let 子句</target> <note>{Locked="Let"} "Let" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Join_clause"> <source>Join clause</source> <target state="translated">Join 子句</target> <note>{Locked="Join"} "Join" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Group_Join_clause"> <source>Group Join clause</source> <target state="translated">Group Join 子句</target> <note>{Locked="Group Join"} "Group Join" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Group_By_clause"> <source>Group By clause</source> <target state="translated">Group By 子句</target> <note>{Locked="Group By"} "Group By" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Function_aggregation"> <source>Function aggregation</source> <target state="translated">函式彙總</target> <note /> </trans-unit> <trans-unit id="Take_While_clause"> <source>Take While clause</source> <target state="translated">Take While 子句</target> <note>{Locked="Take While"} "Take While" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Skip_While_clause"> <source>Skip While clause</source> <target state="translated">Skip While 子句</target> <note>{Locked="Skip While"} "Skip While" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Ordering_clause"> <source>Ordering clause</source> <target state="translated">Ordering 子句</target> <note>{Locked="Ordering"} "Ordering" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Join_condition"> <source>Join condition</source> <target state="translated">Join 條件</target> <note>{Locked="Join"} "Join" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="WithEvents_field"> <source>WithEvents field</source> <target state="translated">WithEvents 欄位</target> <note>{Locked="WithEvents"} "WithEvents" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="as_clause"> <source>as clause</source> <target state="translated">as 子句</target> <note>{Locked="as"} "as" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="type_parameters"> <source>type parameters</source> <target state="translated">類型參數</target> <note /> </trans-unit> <trans-unit id="parameters"> <source>parameters</source> <target state="translated">參數</target> <note /> </trans-unit> <trans-unit id="attributes"> <source>attributes</source> <target state="translated">屬性</target> <note /> </trans-unit> <trans-unit id="Too_many_arguments_to_0"> <source>Too many arguments to '{0}'.</source> <target state="translated">'{0}' 的引數太多。</target> <note /> </trans-unit> <trans-unit id="Type_0_is_not_defined"> <source>Type '{0}' is not defined.</source> <target state="translated">類型 '{0}' 未定義。</target> <note /> </trans-unit> <trans-unit id="Add_Overloads"> <source>Add 'Overloads'</source> <target state="translated">新增 'Overloads'</target> <note>{Locked="Overloads"} "Overloads" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Add_a_metadata_reference_to_specified_assembly_and_all_its_dependencies_e_g_Sharpr_myLib_dll"> <source>Add a metadata reference to specified assembly and all its dependencies, e.g. #r "myLib.dll".</source> <target state="translated">將中繼資料參考加入指定的組件及其所有相依性中,例如 #r "myLib.dll"。</target> <note /> </trans-unit> <trans-unit id="Properties"> <source>Properties</source> <target state="translated">屬性</target> <note /> </trans-unit> <trans-unit id="namespace_name"> <source>&lt;namespace name&gt;</source> <target state="translated">&lt;命名空間名稱&gt;</target> <note /> </trans-unit> <trans-unit id="Type_a_name_here_to_declare_a_namespace"> <source>Type a name here to declare a namespace.</source> <target state="translated">在此輸入名稱以宣告命名空間。</target> <note /> </trans-unit> <trans-unit id="Type_a_name_here_to_declare_a_partial_class"> <source>Type a name here to declare a partial class.</source> <target state="translated">在這裡鍵入名稱以宣告部分類別。</target> <note /> </trans-unit> <trans-unit id="class_name"> <source>&lt;class name&gt;</source> <target state="translated">&lt;類別名稱&gt;</target> <note /> </trans-unit> <trans-unit id="interface_name"> <source>&lt;interface name&gt;</source> <target state="translated">&lt;介面名稱&gt;</target> <note /> </trans-unit> <trans-unit id="module_name"> <source>&lt;module name&gt;</source> <target state="translated">&lt;模組名稱&gt;</target> <note /> </trans-unit> <trans-unit id="structure_name"> <source>&lt;structure name&gt;</source> <target state="translated">&lt;結構名稱&gt;</target> <note /> </trans-unit> <trans-unit id="Type_a_name_here_to_declare_a_partial_interface"> <source>Type a name here to declare a partial interface.</source> <target state="translated">在這裡鍵入名稱以宣告部分類型。</target> <note /> </trans-unit> <trans-unit id="Type_a_name_here_to_declare_a_partial_module"> <source>Type a name here to declare a partial module.</source> <target state="translated">在這裡鍵入名稱以宣告部分類型。</target> <note /> </trans-unit> <trans-unit id="Type_a_name_here_to_declare_a_partial_structure"> <source>Type a name here to declare a partial structure.</source> <target state="translated">在這裡鍵入名稱以宣告部分類型。</target> <note /> </trans-unit> <trans-unit id="Event_add_handler_name"> <source>{0}.add</source> <target state="translated">{0}.add</target> <note>The name of an event add handler where "{0}" is the event name.</note> </trans-unit> <trans-unit id="Event_remove_handler_name"> <source>{0}.remove</source> <target state="translated">{0}.remove</target> <note>The name of an event remove handler where "{0}" is the event name.</note> </trans-unit> <trans-unit id="Property_getter_name"> <source>{0}.get</source> <target state="translated">{0}.get</target> <note>The name of a property getter like "public int MyProperty { get; }" where "{0}" is the property name</note> </trans-unit> <trans-unit id="Property_setter_name"> <source>{0}.set</source> <target state="translated">{0}.set</target> <note>The name of a property setter like "public int MyProperty { set; }" where "{0}" is the property name</note> </trans-unit> <trans-unit id="Make_Async_Function"> <source>Make Async Function</source> <target state="translated">讓非同步函式</target> <note /> </trans-unit> <trans-unit id="Make_Async_Sub"> <source>Make Async Sub</source> <target state="translated">轉換為非同步 Sub</target> <note /> </trans-unit> <trans-unit id="Convert_to_Select_Case"> <source>Convert to 'Select Case'</source> <target state="translated">轉換為 'Select Case'</target> <note /> </trans-unit> <trans-unit id="Convert_to_For_Each"> <source>Convert to 'For Each'</source> <target state="translated">轉換為 'For Each'</target> <note /> </trans-unit> <trans-unit id="Convert_to_For"> <source>Convert to 'For'</source> <target state="translated">轉換為 'For'</target> <note /> </trans-unit> <trans-unit id="Invert_If"> <source>Invert If</source> <target state="translated">反轉 IF</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="zh-Hant" original="../VBFeaturesResources.resx"> <body> <trans-unit id="Add_Await"> <source>Add Await</source> <target state="translated">新增 Await</target> <note /> </trans-unit> <trans-unit id="Add_Await_and_ConfigureAwaitFalse"> <source>Add Await and 'ConfigureAwait(false)'</source> <target state="translated">新增 Await 及 'ConfigureAwait(false)'</target> <note /> </trans-unit> <trans-unit id="Add_Obsolete"> <source>Add &lt;Obsolete&gt;</source> <target state="translated">新增 &lt;已淘汰&gt;</target> <note /> </trans-unit> <trans-unit id="Add_missing_Imports"> <source>Add missing Imports</source> <target state="translated">新增缺少的 Import</target> <note>{Locked="Import"}</note> </trans-unit> <trans-unit id="Add_Shadows"> <source>Add 'Shadows'</source> <target state="translated">新增 'Shadows'</target> <note>{Locked="Shadows"} "Shadows" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Apply_Imports_directive_placement_preferences"> <source>Apply Imports directive placement preferences</source> <target state="translated">套用 Import 指示詞放置喜好設定</target> <note>{Locked="Import"} "Import" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Apply_Me_qualification_preferences"> <source>Apply Me qualification preferences</source> <target state="translated">套用 Me 資格喜好設定</target> <note>{Locked="Me"} "Me" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Change_to_DirectCast"> <source>Change to 'DirectCast'</source> <target state="translated">變更為 'DirectCast'</target> <note /> </trans-unit> <trans-unit id="Change_to_TryCast"> <source>Change to 'TryCast'</source> <target state="translated">變更為 'TryCast'</target> <note /> </trans-unit> <trans-unit id="Insert_0"> <source>Insert '{0}'.</source> <target state="translated">插入 '{0}'。</target> <note /> </trans-unit> <trans-unit id="Delete_the_0_statement1"> <source>Delete the '{0}' statement.</source> <target state="translated">刪除 '{0}' 陳述式。</target> <note /> </trans-unit> <trans-unit id="Create_event_0_in_1"> <source>Create event {0} in {1}</source> <target state="translated">在 {1} 中建立事件 {0}</target> <note /> </trans-unit> <trans-unit id="Insert_the_missing_End_Property_statement"> <source>Insert the missing 'End Property' statement.</source> <target state="translated">插入遺漏的 'End Property' 陳述式。</target> <note /> </trans-unit> <trans-unit id="Insert_the_missing_0"> <source>Insert the missing '{0}'.</source> <target state="translated">插入遺漏的 '{0}'。</target> <note /> </trans-unit> <trans-unit id="Inline_temporary_variable"> <source>Inline temporary variable</source> <target state="translated">內嵌暫存變數</target> <note /> </trans-unit> <trans-unit id="Conflict_s_detected"> <source>Conflict(s) detected.</source> <target state="translated">偵測到衝突。</target> <note /> </trans-unit> <trans-unit id="Introduce_Using_statement"> <source>Introduce 'Using' statement</source> <target state="translated">引入 'Using' 陳述式</target> <note>{Locked="Using"} "Using" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Make_0_inheritable"> <source>Make '{0}' inheritable</source> <target state="translated">將 '{0}' 設為可繼承</target> <note /> </trans-unit> <trans-unit id="Make_private_field_ReadOnly_when_possible"> <source>Make private field ReadOnly when possible</source> <target state="translated">盡可能地將私人欄位設為 ReadOnly</target> <note>{Locked="ReadOnly"} "ReadOnly" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Move_the_0_statement_to_line_1"> <source>Move the '{0}' statement to line {1}.</source> <target state="translated">將 '{0}' 陳述式移至行 {1}。</target> <note /> </trans-unit> <trans-unit id="Delete_the_0_statement2"> <source>Delete the '{0}' statement.</source> <target state="translated">刪除 '{0}' 陳述式。</target> <note /> </trans-unit> <trans-unit id="Multiple_Types"> <source>&lt;Multiple Types&gt;</source> <target state="translated">&lt;多項類型&gt;</target> <note /> </trans-unit> <trans-unit id="Organize_Imports"> <source>Organize Imports</source> <target state="translated">整理 Import</target> <note>{Locked="Import"}</note> </trans-unit> <trans-unit id="Remove_shared_keyword_from_module_member"> <source>Remove 'Shared' keyword from Module member</source> <target state="translated">從模組成員移除 'Shared' 關鍵字</target> <note>{Locked="Shared"} "Shared" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Shared_constructor"> <source>Shared constructor</source> <target state="translated">共用建構函式</target> <note /> </trans-unit> <trans-unit id="Type_a_name_here_to_declare_a_new_field"> <source>Type a name here to declare a new field.</source> <target state="translated">於此輸入名稱以宣告新的欄位。</target> <note /> </trans-unit> <trans-unit id="Note_colon_Space_completion_is_disabled_to_avoid_potential_interference_To_insert_a_name_from_the_list_use_tab"> <source>Note: Space completion is disabled to avoid potential interference. To insert a name from the list, use tab.</source> <target state="translated">注意: 空格完成的功能已停用,以免造成可能的干擾。若要插入清單中的名稱,請使用 Tab 鍵。</target> <note /> </trans-unit> <trans-unit id="_0_Events"> <source>({0} Events)</source> <target state="translated">({0} 個事件)</target> <note /> </trans-unit> <trans-unit id="new_field"> <source>&lt;new field&gt;</source> <target state="translated">&lt;新欄位&gt;</target> <note /> </trans-unit> <trans-unit id="Type_a_name_here_to_declare_a_parameter_If_no_preceding_keyword_is_used_ByVal_will_be_assumed_and_the_argument_will_be_passed_by_value"> <source>Type a name here to declare a parameter. If no preceding keyword is used; 'ByVal' will be assumed and the argument will be passed by value.</source> <target state="translated">於此輸入名稱以宣告參數。若之前未出現任何關鍵字,將假設使用 'ByVal',且引數將依值傳遞。</target> <note /> </trans-unit> <trans-unit id="parameter_name"> <source>&lt;parameter name&gt;</source> <target state="translated">&lt;參數名稱&gt;</target> <note /> </trans-unit> <trans-unit id="Type_a_new_name_for_the_column_followed_by_Otherwise_the_original_column_name_with_be_used"> <source>Type a new name for the column, followed by '='. Otherwise, the original column name with be used.</source> <target state="translated">輸入資料行的新名稱,其後接著 '='。否則將會使用原始的資料行名稱。</target> <note /> </trans-unit> <trans-unit id="Note_colon_Use_tab_for_automatic_completion_space_completion_is_disabled_to_avoid_interfering_with_a_new_name"> <source>Note: Use tab for automatic completion; space completion is disabled to avoid interfering with a new name.</source> <target state="translated">注意: 若要自動完成可使用 Tab 鍵; 而空格完成功能已停用,以免干擾新名稱。</target> <note /> </trans-unit> <trans-unit id="result_alias"> <source>&lt;result alias&gt;</source> <target state="translated">&lt;結果別名&gt;</target> <note /> </trans-unit> <trans-unit id="Type_a_new_variable_name"> <source>Type a new variable name</source> <target state="translated">輸入新的變數名稱</target> <note /> </trans-unit> <trans-unit id="Note_colon_Space_and_completion_are_disabled_to_avoid_potential_interference_To_insert_a_name_from_the_list_use_tab"> <source>Note: Space and '=' completion are disabled to avoid potential interference. To insert a name from the list, use tab.</source> <target state="translated">注意: 空格和 '=' 完成的功能已停用,以免造成可能的干擾。若要插入清單中的名稱,請使用 Tab 鍵。</target> <note /> </trans-unit> <trans-unit id="new_resource"> <source>&lt;new resource&gt;</source> <target state="translated">&lt;新資源&gt;</target> <note /> </trans-unit> <trans-unit id="AddHandler_statement"> <source>AddHandler statement</source> <target state="translated">AddHandler 陳述式</target> <note /> </trans-unit> <trans-unit id="RemoveHandler_statement"> <source>RemoveHandler statement</source> <target state="translated">RemoveHandler 陳述式</target> <note /> </trans-unit> <trans-unit id="_0_function"> <source>{0} function</source> <target state="translated">{0} 函式</target> <note /> </trans-unit> <trans-unit id="CType_function"> <source>CType function</source> <target state="translated">CType 函式</target> <note /> </trans-unit> <trans-unit id="DirectCast_function"> <source>DirectCast function</source> <target state="translated">DirectCast 函式</target> <note /> </trans-unit> <trans-unit id="TryCast_function"> <source>TryCast function</source> <target state="translated">TryCast 函式</target> <note /> </trans-unit> <trans-unit id="GetType_function"> <source>GetType function</source> <target state="translated">GetType 函式</target> <note /> </trans-unit> <trans-unit id="GetXmlNamespace_function"> <source>GetXmlNamespace function</source> <target state="translated">GetXmlNamespace 函式</target> <note /> </trans-unit> <trans-unit id="Mid_statement"> <source>Mid statement</source> <target state="translated">Mid 陳述式</target> <note /> </trans-unit> <trans-unit id="Fix_Incorrect_Function_Return_Type"> <source>Fix Incorrect Function Return Type</source> <target state="translated">修正不正確的函式傳回類型</target> <note /> </trans-unit> <trans-unit id="Simplify_name_0"> <source>Simplify name '{0}'</source> <target state="translated">簡化名稱 '{0}'</target> <note /> </trans-unit> <trans-unit id="Simplify_member_access_0"> <source>Simplify member access '{0}'</source> <target state="translated">簡化成員存取 '{0}'</target> <note /> </trans-unit> <trans-unit id="Remove_Me_qualification"> <source>Remove 'Me' qualification</source> <target state="translated">移除 'Me' 限定性條件</target> <note>{Locked="Me"} "Me" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Name_can_be_simplified"> <source>Name can be simplified</source> <target state="translated">可以簡化名稱</target> <note /> </trans-unit> <trans-unit id="can_t_determine_valid_range_of_statements_to_extract_out"> <source>can't determine valid range of statements to extract out</source> <target state="translated">無法決定要擷取的有效陳述式範圍</target> <note /> </trans-unit> <trans-unit id="Not_all_code_paths_return"> <source>Not all code paths return</source> <target state="translated">未傳回所有程式碼路徑</target> <note /> </trans-unit> <trans-unit id="contains_invalid_selection"> <source>contains invalid selection</source> <target state="translated">包含無效的選取範圍</target> <note /> </trans-unit> <trans-unit id="the_selection_contains_syntactic_errors"> <source>the selection contains syntactic errors</source> <target state="translated">選取範圍包含語法錯誤</target> <note /> </trans-unit> <trans-unit id="Selection_can_t_be_crossed_over_preprocessors"> <source>Selection can't be crossed over preprocessors</source> <target state="translated">選取範圍不可跨多部前置處理器</target> <note /> </trans-unit> <trans-unit id="Selection_can_t_contain_throw_without_enclosing_catch_block"> <source>Selection can't contain throw without enclosing catch block</source> <target state="translated">選取範圍不可包含未納入 catch 區塊的 Throw</target> <note /> </trans-unit> <trans-unit id="Selection_can_t_be_parts_of_constant_initializer_expression"> <source>Selection can't be parts of constant initializer expression</source> <target state="translated">選取範圍不可為常數初始設定式運算式的任何部分</target> <note /> </trans-unit> <trans-unit id="Argument_used_for_ByRef_parameter_can_t_be_extracted_out"> <source>Argument used for ByRef parameter can't be extracted out</source> <target state="translated">無法擷取用於 ByRef 參數的引數</target> <note /> </trans-unit> <trans-unit id="all_static_local_usages_defined_in_the_selection_must_be_included_in_the_selection"> <source>all static local usages defined in the selection must be included in the selection</source> <target state="translated">選取範圍中必須包含選取範圍中所定義的所有靜態區域使用方式</target> <note /> </trans-unit> <trans-unit id="Implicit_member_access_can_t_be_included_in_the_selection_without_containing_statement"> <source>Implicit member access can't be included in the selection without containing statement</source> <target state="translated">沒有包含陳述式的選取範圍中,不可包含隱含成員存取</target> <note /> </trans-unit> <trans-unit id="Selection_must_be_part_of_executable_statements"> <source>Selection must be part of executable statements</source> <target state="translated">選取範圍必須是可執行之陳述式的一部分</target> <note /> </trans-unit> <trans-unit id="next_statement_control_variable_doesn_t_have_matching_declaration_statement"> <source>next statement control variable doesn't have matching declaration statement</source> <target state="translated">下一個陳述式控制變數沒有相符的宣告陳述式</target> <note /> </trans-unit> <trans-unit id="Selection_doesn_t_contain_any_valid_node"> <source>Selection doesn't contain any valid node</source> <target state="translated">選取範圍不包含任何有效的節點</target> <note /> </trans-unit> <trans-unit id="no_valid_statement_range_to_extract_out"> <source>no valid statement range to extract out</source> <target state="translated">沒有可擷取內容的有效陳述式範圍</target> <note /> </trans-unit> <trans-unit id="Invalid_selection"> <source>Invalid selection</source> <target state="translated">選取範圍無效</target> <note /> </trans-unit> <trans-unit id="Deprecated"> <source>Deprecated</source> <target state="translated">取代</target> <note /> </trans-unit> <trans-unit id="Extension"> <source>Extension</source> <target state="translated">擴充功能</target> <note /> </trans-unit> <trans-unit id="Awaitable"> <source>Awaitable</source> <target state="translated">可等候</target> <note /> </trans-unit> <trans-unit id="Awaitable_Extension"> <source>Awaitable, Extension</source> <target state="translated">可等候的擴充功能</target> <note /> </trans-unit> <trans-unit id="new_variable"> <source>&lt;new variable&gt;</source> <target state="translated">&lt;新變數&gt;</target> <note /> </trans-unit> <trans-unit id="Creates_a_delegate_procedure_instance_that_references_the_specified_procedure_AddressOf_procedureName"> <source>Creates a delegate procedure instance that references the specified procedure. AddressOf &lt;procedureName&gt;</source> <target state="translated">建立會參考指定程序的委派程序執行個體。 AddressOf &lt;procedureName&gt;</target> <note /> </trans-unit> <trans-unit id="Indicates_that_an_external_procedure_has_another_name_in_its_DLL"> <source>Indicates that an external procedure has another name in its DLL.</source> <target state="translated">表示外部程序在其 DLL 中有另一個名稱。</target> <note /> </trans-unit> <trans-unit id="Performs_a_short_circuit_logical_conjunction_on_two_expressions_Returns_True_if_both_operands_evaluate_to_True_If_the_first_expression_evaluates_to_False_the_second_is_not_evaluated_result_expression1_AndAlso_expression2"> <source>Performs a short-circuit logical conjunction on two expressions. Returns True if both operands evaluate to True. If the first expression evaluates to False, the second is not evaluated. &lt;result&gt; = &lt;expression1&gt; AndAlso &lt;expression2&gt;</source> <target state="translated">在兩個運算式上執行最少運算邏輯結合。若兩個運算元都評估為 True,即傳回 True。若第一個運算式評估為 False,則不會評估第二個運算式。 &lt;result&gt; = &lt;expression1&gt; AndAlso &lt;expression2&gt;</target> <note /> </trans-unit> <trans-unit id="Performs_a_logical_conjunction_on_two_Boolean_expressions_or_a_bitwise_conjunction_on_two_numeric_expressions_For_Boolean_expressions_returns_True_if_both_operands_evaluate_to_True_Both_expressions_are_always_evaluated_result_expression1_And_expression2"> <source>Performs a logical conjunction on two Boolean expressions, or a bitwise conjunction on two numeric expressions. For Boolean expressions, returns True if both operands evaluate to True. Both expressions are always evaluated. &lt;result&gt; = &lt;expression1&gt; And &lt;expression2&gt;</source> <target state="translated">在兩布林運算式上執行邏輯結合,或在兩個數值運算式上執行位元結合。對於布林運算式而言,若兩個運算元都評估為 True,即傳回 True。兩個運算式都會進行評估。 &lt;result&gt; = &lt;expression1&gt; And &lt;expression2&gt;</target> <note /> </trans-unit> <trans-unit id="Used_in_a_Declare_statement_The_Ansi_modifier_specifies_that_Visual_Basic_should_marshal_all_strings_to_ANSI_values_and_should_look_up_the_procedure_without_modifying_its_name_during_the_search_If_no_character_set_is_specified_ANSI_is_the_default"> <source>Used in a Declare statement. The Ansi modifier specifies that Visual Basic should marshal all strings to ANSI values, and should look up the procedure without modifying its name during the search. If no character set is specified, ANSI is the default.</source> <target state="translated">用在 Declare 陳述式中。Ansi 修飾元會指定 Visual Basic 應將所有字串封送處理成 ANSI 值,且在搜尋期間,應查詢程序但不要修改其名稱。若未指定字元集,預設值就是 ANSI。</target> <note /> </trans-unit> <trans-unit id="Specifies_a_data_type_in_a_declaration_statement"> <source>Specifies a data type in a declaration statement.</source> <target state="translated">在宣告陳述式中指定資料類型。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_an_attribute_at_the_beginning_of_a_source_file_applies_to_the_entire_assembly_Otherwise_the_attribute_will_apply_only_to_an_individual_programming_element_such_as_a_class_or_property"> <source>Specifies that an attribute at the beginning of a source file applies to the entire assembly. Otherwise the attribute will apply only to an individual programming element, such as a class or property.</source> <target state="translated">指定在原始程式檔開頭的屬性,會套用到整個組件。否則,屬性將只會套用到個別的程式設計元素,例如類別或屬性。</target> <note /> </trans-unit> <trans-unit id="Indicates_an_asynchronous_method_that_can_use_the_Await_operator"> <source>Indicates an asynchronous method that can use the Await operator.</source> <target state="translated">指出可以使用 Await 運算子的非同步方法。</target> <note /> </trans-unit> <trans-unit id="Used_in_a_Declare_statement_The_Auto_modifier_specifies_that_Visual_Basic_should_marshal_strings_according_to_NET_Framework_rules_and_should_determine_the_base_character_set_of_the_run_time_platform_and_possibly_modify_the_external_procedure_name_if_the_initial_search_fails"> <source>Used in a Declare statement. The Auto modifier specifies that Visual Basic should marshal strings according to .NET Framework rules, and should determine the base character set of the run-time platform and possibly modify the external procedure name if the initial search fails.</source> <target state="translated">用在 Declare 陳述式中。Auto 修飾元可指定 Visual Basic 應該根據 .NET Framework 規則封送處理字串,且應判斷執行階段平台的基礎字元集,若初始搜尋失敗,還可能修改外部程序名稱。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_an_argument_is_passed_in_such_a_way_that_the_called_procedure_can_change_the_underlying_value_of_the_argument_in_the_calling_code"> <source>Specifies that an argument is passed in such a way that the called procedure can change the underlying value of the argument in the calling code.</source> <target state="translated">將引數的傳遞方式,指定為可讓呼叫的程序能變更呼叫程式碼中引數的基礎值。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_an_argument_is_passed_in_such_a_way_that_the_called_procedure_or_property_cannot_change_the_underlying_value_of_the_argument_in_the_calling_code"> <source>Specifies that an argument is passed in such a way that the called procedure or property cannot change the underlying value of the argument in the calling code.</source> <target state="translated">將引數的傳遞方式,指定為可讓呼叫的程序或屬性無法變更呼叫程式碼中引數的基礎值。</target> <note /> </trans-unit> <trans-unit id="Declares_the_name_of_a_class_and_introduces_the_definitions_of_the_variables_properties_and_methods_that_make_up_the_class"> <source>Declares the name of a class and introduces the definitions of the variables, properties, and methods that make up the class.</source> <target state="translated">宣告類別的名稱,並引進組成類別之變數、屬性與方法的定義。</target> <note /> </trans-unit> <trans-unit id="Generates_a_string_concatenation_of_two_expressions"> <source>Generates a string concatenation of two expressions.</source> <target state="translated">產生兩個運算式的字串串連。</target> <note /> </trans-unit> <trans-unit id="Declares_and_defines_one_or_more_constants"> <source>Declares and defines one or more constants.</source> <target state="translated">宣告並定義一或多個常數。</target> <note /> </trans-unit> <trans-unit id="Use_In_for_a_type_that_will_only_be_used_for_ByVal_arguments_to_functions"> <source>Use 'In' for a type that will only be used for ByVal arguments to functions.</source> <target state="translated">針對只用於函式中 ByVal 引數的類型,使用 'In'。</target> <note /> </trans-unit> <trans-unit id="Use_Out_for_a_type_that_will_only_be_used_as_a_return_from_functions"> <source>Use 'Out' for a type that will only be used as a return from functions.</source> <target state="translated">針對只用做為函式傳回值的類型,使用 'Out'。</target> <note /> </trans-unit> <trans-unit id="Returns_the_result_of_explicitly_converting_an_expression_to_a_specified_data_type_object_structure_class_or_interface_CType_Object_As_Expression_Object_As_Type_As_Type"> <source>Returns the result of explicitly converting an expression to a specified data type, object, structure, class, or interface. CType(Object As Expression, Object As Type) As Type</source> <target state="translated">傳回運算式明確轉換成指定之資料類型、物件、結構、類別或介面的結果。 CType(Object As Expression, Object As Type) As Type</target> <note /> </trans-unit> <trans-unit id="Specifies_that_an_event_has_additional_specialized_code_for_adding_handlers_removing_handlers_and_raising_events"> <source>Specifies that an event has additional, specialized code for adding handlers, removing handlers, and raising events.</source> <target state="translated">指定事件有額外的特定程式碼,可加入處理常式、移除處理常式,以及引發事件。</target> <note /> </trans-unit> <trans-unit id="Declares_a_reference_to_a_procedure_implemented_in_an_external_file"> <source>Declares a reference to a procedure implemented in an external file.</source> <target state="translated">宣告實作在外部檔案中之程序的參考。</target> <note /> </trans-unit> <trans-unit id="Identifies_a_property_as_the_default_property_of_its_class_structure_or_interface"> <source>Identifies a property as the default property of its class, structure, or interface.</source> <target state="translated">找出為其類別、結構或介面之預設屬性的屬性。</target> <note /> </trans-unit> <trans-unit id="Used_to_declare_a_delegate_A_delegate_is_a_reference_type_that_refers_to_a_shared_method_of_a_type_or_to_an_instance_method_of_an_object_Any_procedure_that_is_convertible_or_that_has_matching_parameter_types_and_return_type_may_be_used_to_create_an_instance_of_this_delegate_class"> <source>Used to declare a delegate. A delegate is a reference type that refers to a shared method of a type or to an instance method of an object. Any procedure that is convertible, or that has matching parameter types and return type may be used to create an instance of this delegate class.</source> <target state="translated">用於宣告委派。委派是一種參考類型,其會參考類型的共用方法,或物件的執行個體方法。任何可轉換的程序,或是參數類型與傳回類型相符的程序,都可用以建立此委派類別的執行個體。</target> <note /> </trans-unit> <trans-unit id="Declares_and_allocates_storage_space_for_one_or_more_variables_Dim_var_bracket_As_bracket_New_bracket_dataType_bracket_boundList_bracket_bracket_bracket_initializer_bracket_bracket_var2_bracket"> <source>Declares and allocates storage space for one or more variables. Dim {&lt;var&gt; [As [New] dataType [(boundList)]][= initializer]}[, var2]</source> <target state="translated">宣告一或多個變數,並為其配置儲存空間。 Dim {&lt;var&gt; [As [New] dataType [(boundList)]][= initializer]}[, var2]</target> <note /> </trans-unit> <trans-unit id="Divides_two_numbers_and_returns_a_floating_point_result"> <source>Divides two numbers and returns a floating-point result.</source> <target state="translated">將兩個數值相除,傳回浮點結果。</target> <note /> </trans-unit> <trans-unit id="Terminates_a_0_block"> <source>Terminates a {0} block.</source> <target state="translated">結束 {0} 區塊。</target> <note /> </trans-unit> <trans-unit id="Terminates_an_0_block"> <source>Terminates an {0} block.</source> <target state="translated">結束 {0} 區塊。</target> <note /> </trans-unit> <trans-unit id="Terminates_the_definition_of_a_0_statement"> <source>Terminates the definition of a {0} statement.</source> <target state="translated">結束 {0} 陳述式的定義。</target> <note /> </trans-unit> <trans-unit id="Terminates_the_definition_of_an_0_statement"> <source>Terminates the definition of an {0} statement.</source> <target state="translated">結束 {0} 陳述式的定義。</target> <note /> </trans-unit> <trans-unit id="Declares_an_enumeration_and_defines_the_values_of_its_members"> <source>Declares an enumeration and defines the values of its members.</source> <target state="translated">宣告列舉,並定義其成員的值。</target> <note /> </trans-unit> <trans-unit id="Compares_two_expressions_and_returns_True_if_they_are_equal_Otherwise_returns_False"> <source>Compares two expressions and returns True if they are equal. Otherwise, returns False.</source> <target state="translated">比較兩個運算式,若兩者相等,即傳回 True; 否則傳回 False。</target> <note /> </trans-unit> <trans-unit id="Used_to_release_array_variables_and_deallocate_the_memory_used_for_their_elements"> <source>Used to release array variables and deallocate the memory used for their elements.</source> <target state="translated">用以釋放陣列變數,並取消配置其元素所使用的記憶體。</target> <note /> </trans-unit> <trans-unit id="Declares_a_user_defined_event"> <source>Declares a user-defined event.</source> <target state="translated">宣告使用者定義的事件。</target> <note /> </trans-unit> <trans-unit id="Exits_a_Sub_procedure_and_transfers_execution_immediately_to_the_statement_following_the_call_to_the_Sub_procedure"> <source>Exits a Sub procedure and transfers execution immediately to the statement following the call to the Sub procedure.</source> <target state="translated">結束 Sub 程序,並將執行立即轉移到接在 Sub 程序呼叫之後的陳述式。</target> <note /> </trans-unit> <trans-unit id="Raises_a_number_to_the_power_of_another_number"> <source>Raises a number to the power of another number.</source> <target state="translated">將數字的次方指定為另一個數字。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_the_external_procedure_being_referenced_in_the_Declare_statement_is_a_Function"> <source>Specifies that the external procedure being referenced in the Declare statement is a Function.</source> <target state="translated">指定 Declare 陳述式中所參考的外部程序是 Function。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_the_external_procedure_being_referenced_in_the_Declare_statement_is_a_Sub"> <source>Specifies that the external procedure being referenced in the Declare statement is a Sub.</source> <target state="translated">指定 Declare 陳述式中所參考的外部程序是 Sub。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_one_or_more_declared_programming_elements_are_accessible_only_from_within_the_assembly_that_contains_their_declaration"> <source>Specifies that one or more declared programming elements are accessible only from within the assembly that contains their declaration.</source> <target state="translated">指定一或多個宣告的程式設計元素,只能從包含其宣告的組件加以存取。</target> <note /> </trans-unit> <trans-unit id="Specifies_a_collection_and_a_range_variable_to_use_in_a_query"> <source>Specifies a collection and a range variable to use in a query.</source> <target state="translated">指定查詢中所使用的集合與範圍變數。</target> <note /> </trans-unit> <trans-unit id="Declares_the_name_parameters_and_code_that_define_a_Function_procedure_that_is_a_procedure_that_returns_a_value_to_the_calling_code"> <source>Declares the name, parameters, and code that define a Function procedure, that is, a procedure that returns a value to the calling code.</source> <target state="translated">宣告定義 Function 程序的名稱、參數與程式碼; 也就是説,這種程序會對呼叫的程式碼傳回值。</target> <note /> </trans-unit> <trans-unit id="Constrains_a_generic_type_parameter_to_require_that_any_type_argument_passed_to_it_be_a_reference_type"> <source>Constrains a generic type parameter to require that any type argument passed to it be a reference type.</source> <target state="translated">將泛型類型參數限制為傳遞給它的所有類型引數,都必須要是參考類型。</target> <note /> </trans-unit> <trans-unit id="Specifies_a_constructor_constraint_on_a_generic_type_parameter"> <source>Specifies a constructor constraint on a generic type parameter.</source> <target state="translated">指定泛型類型參數的建構函式條件約束。</target> <note /> </trans-unit> <trans-unit id="Constrains_a_generic_type_parameter_to_require_that_any_type_argument_passed_to_it_be_a_value_type"> <source>Constrains a generic type parameter to require that any type argument passed to it be a value type.</source> <target state="translated">將泛型類型參數限制為傳遞給它的所有類型引數,都必須要是實值類型。</target> <note /> </trans-unit> <trans-unit id="Declares_a_Get_property_procedure_that_is_used_to_return_the_current_value_of_a_property"> <source>Declares a Get property procedure that is used to return the current value of a property.</source> <target state="translated">宣告用以傳回屬性目前值的 Get 屬性程序。</target> <note /> </trans-unit> <trans-unit id="Compares_two_expressions_and_returns_True_if_the_first_is_greater_than_the_second_Otherwise_returns_False"> <source>Compares two expressions and returns True if the first is greater than the second. Otherwise, returns False.</source> <target state="translated">比較兩個運算式,若第一個運算式大於第二個運算式,即傳回 True; 否則傳回 False。</target> <note /> </trans-unit> <trans-unit id="Compares_two_expressions_and_returns_True_if_the_first_is_greater_than_or_equal_to_the_second_Otherwise_returns_False"> <source>Compares two expressions and returns True if the first is greater than or equal to the second. Otherwise, returns False.</source> <target state="translated">比較兩個運算式,若第一個運算式大於或等於第二個運算式,即傳回 True; 否則傳回 False。</target> <note /> </trans-unit> <trans-unit id="Declares_that_a_procedure_handles_a_specified_event"> <source>Declares that a procedure handles a specified event.</source> <target state="translated">宣告程序會處理指定的事件。</target> <note /> </trans-unit> <trans-unit id="Indicates_that_a_class_or_structure_member_is_providing_the_implementation_for_a_member_defined_in_an_interface"> <source>Indicates that a class or structure member is providing the implementation for a member defined in an interface.</source> <target state="translated">表示類別或結構成員將提供介面中定義之成員的實作。</target> <note /> </trans-unit> <trans-unit id="Specifies_one_or_more_interfaces_or_interface_members_that_must_be_implemented_in_the_class_or_structure_definition_in_which_the_Implements_statement_appears"> <source>Specifies one or more interfaces, or interface members, that must be implemented in the class or structure definition in which the Implements statement appears.</source> <target state="translated">指定必須在出現 Implements 陳述式的類別或結構定義中實作的一或多個介面或介面成員。</target> <note /> </trans-unit> <trans-unit id="Imports_all_or_specified_elements_of_a_namespace_into_a_file"> <source>Imports all or specified elements of a namespace into a file.</source> <target state="translated">將命名空間的所有元素或指定元素,匯入至檔案。</target> <note /> </trans-unit> <trans-unit id="Specifies_the_group_that_the_loop_variable_in_a_For_Each_statement_is_to_traverse"> <source>Specifies the group that the loop variable in a For Each statement is to traverse.</source> <target state="translated">指定 For Each 陳述式中迴圈變數要周遊的群組。</target> <note /> </trans-unit> <trans-unit id="Specifies_the_group_that_the_loop_variable_is_to_traverse_in_a_For_Each_statement_or_specifies_the_range_variable_in_a_query"> <source>Specifies the group that the loop variable is to traverse in a For Each statement, or specifies the range variable in a query.</source> <target state="translated">指定 For Each 陳述式中迴圈變數要周遊的群組,或指定查詢中的範圍變數。</target> <note /> </trans-unit> <trans-unit id="Causes_the_current_class_or_interface_to_inherit_the_attributes_variables_properties_procedures_and_events_from_another_class_or_set_of_interfaces"> <source>Causes the current class or interface to inherit the attributes, variables, properties, procedures, and events from another class or set of interfaces.</source> <target state="translated">讓目前的類別或介面,從另一個類別或介面集合繼承屬性 (Attribute)、變數、屬性 (Property)、程序及事件。</target> <note /> </trans-unit> <trans-unit id="Specifies_the_group_that_the_range_variable_is_to_traverse_in_a_query"> <source>Specifies the group that the range variable is to traverse in a query.</source> <target state="translated">指定查詢中範圍變數要周遊的群組。</target> <note /> </trans-unit> <trans-unit id="Divides_two_numbers_and_returns_an_integer_result"> <source>Divides two numbers and returns an integer result.</source> <target state="translated">將兩個數值相除,傳回整數結果。</target> <note /> </trans-unit> <trans-unit id="Declares_the_name_of_an_interface_and_the_definitions_of_the_members_of_the_interface"> <source>Declares the name of an interface and the definitions of the members of the interface.</source> <target state="translated">宣告介面的名稱與介面成員的定義。</target> <note /> </trans-unit> <trans-unit id="Determines_whether_an_expression_is_false_If_instances_of_any_class_or_structure_will_be_used_in_an_OrElse_clause_you_must_define_IsFalse_on_that_class_or_structure"> <source>Determines whether an expression is false. If instances of any class or structure will be used in an OrElse clause, you must define IsFalse on that class or structure.</source> <target state="translated">判斷運算式是否為 False。若在 OrElse 子句中會出現任何類別或結構,您必須在該類別或結構上定義 IsFalse。</target> <note /> </trans-unit> <trans-unit id="Compares_two_object_reference_variables_and_returns_True_if_the_objects_are_equal_result_object1_Is_object2"> <source>Compares two object reference variables and returns True if the objects are equal. &lt;result&gt; = &lt;object1&gt; Is &lt;object2&gt;</source> <target state="translated">比較兩個物件參考變數,若物件相等,即傳回 True。 &lt;result&gt; = &lt;object1&gt; Is &lt;object2&gt;</target> <note /> </trans-unit> <trans-unit id="Compares_two_object_reference_variables_and_returns_True_if_the_objects_are_not_equal_result_object1_IsNot_object2"> <source>Compares two object reference variables and returns True if the objects are not equal. &lt;result&gt; = &lt;object1&gt; IsNot &lt;object2&gt;</source> <target state="translated">比較兩個物件參考變數,若物件不相等,即傳回 True。 &lt;result&gt; = &lt;object1&gt; IsNot &lt;object2&gt;</target> <note /> </trans-unit> <trans-unit id="Determines_whether_an_expression_is_true_If_instances_of_any_class_or_structure_will_be_used_in_an_OrElse_clause_you_must_define_IsTrue_on_that_class_or_structure"> <source>Determines whether an expression is true. If instances of any class or structure will be used in an OrElse clause, you must define IsTrue on that class or structure.</source> <target state="translated">判斷運算式是否為 True。若在 OrElse 子句會出現任何類別或結構,則必須在該類別或結構上定義 IsTrue。</target> <note /> </trans-unit> <trans-unit id="Indicates_an_iterator_method_that_can_use_the_Yield_statement"> <source>Indicates an iterator method that can use the Yield statement.</source> <target state="translated">指出可以使用 Yield 陳述式的 Iterator 方法。</target> <note /> </trans-unit> <trans-unit id="Defines_an_iterator_lambda_expression_that_can_use_the_Yield_statement_Iterator_Function_parameterList_As_IEnumerable_Of_T"> <source>Defines an iterator lambda expression that can use the Yield statement. Iterator Function(&lt;parameterList&gt;) As IEnumerable(Of &lt;T&gt;)</source> <target state="translated">定義可以使用 Yield 陳述式的 Iterator Lambda 運算式。 Iterator Function(&lt;parameterList&gt;) As IEnumerable(Of &lt;T&gt;)</target> <note /> </trans-unit> <trans-unit id="Performs_an_arithmetic_left_shift_on_a_bit_pattern"> <source>Performs an arithmetic left shift on a bit pattern.</source> <target state="translated">在位元模式上執行算術左位移。</target> <note /> </trans-unit> <trans-unit id="Compares_two_expressions_and_returns_True_if_the_first_is_less_than_the_second_Otherwise_returns_False"> <source>Compares two expressions and returns True if the first is less than the second. Otherwise, returns False.</source> <target state="translated">比較兩個運算式,若第一個運算式小於第二個運算式,即傳回 True; 否則傳回 False。</target> <note /> </trans-unit> <trans-unit id="Compares_two_expressions_and_returns_True_if_the_first_is_less_than_or_equal_to_the_second_Otherwise_returns_False"> <source>Compares two expressions and returns True if the first is less than or equal to the second. Otherwise, returns False.</source> <target state="translated">比較兩個運算式,若第一個運算式小於或等於第二個運算式,即傳回 True; 否則傳回 False。</target> <note /> </trans-unit> <trans-unit id="Introduces_a_clause_that_identifies_the_external_file_DLL_or_code_resource_containing_an_external_procedure"> <source>Introduces a clause that identifies the external file (DLL or code resource) containing an external procedure.</source> <target state="translated">引進能找出包含外部程序之外部檔案 (DLL 或程式碼資源) 的子句。</target> <note /> </trans-unit> <trans-unit id="Compares_a_string_against_a_pattern_Wildcards_available_include_to_match_1_character_and_to_match_0_or_more_characters_result_string_Like_pattern"> <source>Compares a string against a pattern. Wildcards available include ? to match 1 character and * to match 0 or more characters. &lt;result&gt; = &lt;string&gt; Like &lt;pattern&gt;</source> <target state="translated">將字串與模式相比。可用的萬用字元包括 ? (與 1 個字元相符) 以及 * (與 0 或多個字元相符)。 &lt;result&gt; = &lt;string&gt; Like &lt;pattern&gt;</target> <note /> </trans-unit> <trans-unit id="Returns_the_difference_between_two_numeric_expressions_or_the_negative_value_of_a_numeric_expression"> <source>Returns the difference between two numeric expressions, or the negative value of a numeric expression.</source> <target state="translated">傳回兩個數值運算式的差,或一個數值運算式的負值。</target> <note /> </trans-unit> <trans-unit id="Divides_two_numbers_and_returns_only_the_remainder_number1_Mod_number2"> <source>Divides two numbers and returns only the remainder. &lt;number1&gt; Mod &lt;number2&gt;</source> <target state="translated">將兩個數字相除,然後只傳回餘數。 &lt;數字 1&gt; Mod &lt;數字 2&gt;</target> <note /> </trans-unit> <trans-unit id="Specifies_that_an_attribute_at_the_beginning_of_a_source_file_applies_to_the_entire_module_Otherwise_the_attribute_will_apply_only_to_an_individual_programming_element_such_as_a_class_or_property"> <source>Specifies that an attribute at the beginning of a source file applies to the entire module. Otherwise the attribute will apply only to an individual programming element, such as a class or property.</source> <target state="translated">指定在原始程式檔開頭的屬性,會套用到整個模組。否則,屬性將只會套用到個別的程式設計元素,例如類別或屬性。</target> <note /> </trans-unit> <trans-unit id="Multiplies_two_numbers_and_returns_the_product"> <source>Multiplies two numbers and returns the product.</source> <target state="translated">將兩個數值相乘,然後傳回乘積。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_a_class_can_be_used_only_as_a_base_class_and_that_you_cannot_create_an_object_directly_from_it"> <source>Specifies that a class can be used only as a base class, and that you cannot create an object directly from it.</source> <target state="translated">指定類別只可用做為基底類別,且您無法直接從它建立物件。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_a_property_or_procedure_is_not_implemented_in_the_class_and_must_be_overridden_in_a_derived_class_before_it_can_be_used"> <source>Specifies that a property or procedure is not implemented in the class and must be overridden in a derived class before it can be used.</source> <target state="translated">指定未在類別中實作的屬性或程序,在使用之前必須於衍生的類別中加以覆寫。</target> <note /> </trans-unit> <trans-unit id="Declares_the_name_of_a_namespace_and_causes_the_source_code_following_the_declaration_to_be_compiled_within_that_namespace"> <source>Declares the name of a namespace, and causes the source code following the declaration to be compiled within that namespace.</source> <target state="translated">宣告命名空間的名稱,並讓接在宣告後的原始程式碼,會於該命名空間中編譯。</target> <note /> </trans-unit> <trans-unit id="Indicates_that_a_conversion_operator_CType_converts_a_class_or_structure_to_a_type_that_might_not_be_able_to_hold_some_of_the_possible_values_of_the_original_class_or_structure"> <source>Indicates that a conversion operator (CType) converts a class or structure to a type that might not be able to hold some of the possible values of the original class or structure.</source> <target state="translated">表示轉換運算子 (CType) 會將類別或結構轉換成可能無法容納原始類別或結構之某些可能值的類型。</target> <note /> </trans-unit> <trans-unit id="Compares_two_expressions_and_returns_True_if_they_are_not_equal_Otherwise_returns_False"> <source>Compares two expressions and returns True if they are not equal. Otherwise, returns False.</source> <target state="translated">比較兩個運算式,若兩者不相等,即傳回 True; 否則傳回 False。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_a_class_cannot_be_used_as_a_base_class"> <source>Specifies that a class cannot be used as a base class.</source> <target state="translated">指定類別不能用做為基底類別。</target> <note /> </trans-unit> <trans-unit id="Performs_logical_negation_on_a_Boolean_expression_or_bitwise_negation_on_a_numeric_expression_result_Not_expression"> <source>Performs logical negation on a Boolean expression, or bitwise negation on a numeric expression. &lt;result&gt; = Not &lt;expression&gt;</source> <target state="translated">在布林運算式上執行邏輯否定運算,或是在數值運算式上執行位元否定運算。 &lt;result&gt; = Not &lt;expression&gt;</target> <note /> </trans-unit> <trans-unit id="Specifies_that_a_property_or_procedure_cannot_be_overridden_in_a_derived_class"> <source>Specifies that a property or procedure cannot be overridden in a derived class.</source> <target state="translated">指定在衍生類別中不可覆寫屬性或程序。</target> <note /> </trans-unit> <trans-unit id="Identifies_a_type_parameter_on_a_generic_class_structure_interface_delegate_or_procedure"> <source>Identifies a type parameter on a generic class, structure, interface, delegate, or procedure.</source> <target state="translated">識別泛型類別、結構、介面、委派或程序的類型參數。</target> <note /> </trans-unit> <trans-unit id="Declares_the_operator_symbol_operands_and_code_that_define_an_operator_procedure_on_a_class_or_structure"> <source>Declares the operator symbol, operands, and code that define an operator procedure on a class or structure.</source> <target state="translated">宣告運算子符號、運算元與程式碼,以定義類別或結構的運算子程序。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_a_procedure_argument_can_be_omitted_when_the_procedure_is_called"> <source>Specifies that a procedure argument can be omitted when the procedure is called.</source> <target state="translated">指定呼叫程序時,可以省略程序引數。</target> <note /> </trans-unit> <trans-unit id="Introduces_a_statement_that_specifies_a_compiler_option_that_applies_to_the_entire_source_file"> <source>Introduces a statement that specifies a compiler option that applies to the entire source file.</source> <target state="translated">引進指定套用到整個原始程式檔之編譯器選項的陳述式。</target> <note /> </trans-unit> <trans-unit id="Performs_short_circuit_inclusive_logical_disjunction_on_two_expressions_Returns_True_if_either_operand_evaluates_to_True_If_the_first_expression_evaluates_to_True_the_second_expression_is_not_evaluated_result_expression1_OrElse_expression2"> <source>Performs short-circuit inclusive logical disjunction on two expressions. Returns True if either operand evaluates to True. If the first expression evaluates to True, the second expression is not evaluated. &lt;result&gt; = &lt;expression1&gt; OrElse &lt;expression2&gt;</source> <target state="translated">在兩個運算式上執行最少運算的內含邏輯分離。若任一運算元評估為 True,即傳回 True。若第一個運算式評估為 True,則不會評估第二個運算式。 &lt;result&gt; = &lt;expression1&gt; OrElse &lt;expression2&gt;</target> <note /> </trans-unit> <trans-unit id="Performs_an_inclusive_logical_disjunction_on_two_Boolean_expressions_or_a_bitwise_disjunction_on_two_numeric_expressions_For_Boolean_expressions_returns_True_if_at_least_one_operand_evaluates_to_True_Both_expressions_are_always_evaluated_result_expression1_Or_expression2"> <source>Performs an inclusive logical disjunction on two Boolean expressions, or a bitwise disjunction on two numeric expressions. For Boolean expressions, returns True if at least one operand evaluates to True. Both expressions are always evaluated. &lt;result&gt; = &lt;expression1&gt; Or &lt;expression2&gt;</source> <target state="translated">在兩個布林運算式上執行內含邏輯分離,或在兩個數值運算式上執行位元分離。對於布林運算式而言,若至少有一個運算元評估為 True,即傳回 True。兩個運算式都會進行評估。 &lt;result&gt; = &lt;expression1&gt; Or &lt;expression2&gt;</target> <note /> </trans-unit> <trans-unit id="Specifies_that_a_property_or_procedure_re_declares_one_or_more_existing_properties_or_procedures_with_the_same_name"> <source>Specifies that a property or procedure re-declares one or more existing properties or procedures with the same name.</source> <target state="translated">指定屬性或程序會重新宣告一或多個同名的現有屬性或程序。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_a_property_or_procedure_can_be_overridden_by_an_identically_named_property_or_procedure_in_a_derived_class"> <source>Specifies that a property or procedure can be overridden by an identically named property or procedure in a derived class.</source> <target state="translated">指定屬性或程序可由衍生類別中的同名屬性或程序覆寫。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_a_property_or_procedure_overrides_an_identically_named_property_or_procedure_inherited_from_a_base_class"> <source>Specifies that a property or procedure overrides an identically named property or procedure inherited from a base class.</source> <target state="translated">指定屬性或程序會覆寫繼承自基底類別的同名屬性或程序。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_a_procedure_parameter_takes_an_optional_array_of_elements_of_the_specified_type"> <source>Specifies that a procedure parameter takes an optional array of elements of the specified type.</source> <target state="translated">指定程序參數可會接受指定類型的選擇性元素陣列。</target> <note /> </trans-unit> <trans-unit id="Indicates_that_a_method_class_or_structure_declaration_is_a_partial_definition_of_the_method_class_or_structure"> <source>Indicates that a method, class, or structure declaration is a partial definition of the method, class, or structure.</source> <target state="translated">表示方法、類別或結構宣告,為方法、類別或結構的部分定義。</target> <note /> </trans-unit> <trans-unit id="Returns_the_sum_of_two_numbers_or_the_positive_value_of_a_numeric_expression"> <source>Returns the sum of two numbers, or the positive value of a numeric expression.</source> <target state="translated">傳回兩個數值的和,或數值運算式的正值。</target> <note /> </trans-unit> <trans-unit id="Prevents_the_contents_of_an_array_from_being_cleared_when_the_dimensions_of_the_array_are_changed"> <source>Prevents the contents of an array from being cleared when the dimensions of the array are changed.</source> <target state="translated">避免在變更陣列維度時,清除陣列內容。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_one_or_more_declared_programming_elements_are_accessible_only_from_within_their_module_class_or_structure"> <source>Specifies that one or more declared programming elements are accessible only from within their module, class, or structure.</source> <target state="translated">指定一或多個宣告的程式設計元素,只能從其模組、類別或結構加以存取。</target> <note /> </trans-unit> <trans-unit id="Declares_the_name_of_a_property_and_the_property_procedures_used_to_store_and_retrieve_the_value_of_the_property"> <source>Declares the name of a property, and the property procedures used to store and retrieve the value of the property.</source> <target state="translated">宣告屬性的名稱,以及用以儲存及擷取屬性值的屬性程序。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_one_or_more_declared_members_of_a_class_are_accessible_from_anywhere_in_the_same_assembly_their_own_classes_and_derived_classes"> <source>Specifies that one or more declared members of a class are accessible from anywhere in the same assembly, their own classes, and derived classes.</source> <target state="translated">指定類別的一或多個宣告成員,可從相同的組件、其本身的類別以及衍生類別中的任何位置加以存取。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_one_or_more_declared_programming_elements_are_accessible_only_from_within_their_own_class_or_from_a_derived_class"> <source>Specifies that one or more declared programming elements are accessible only from within their own class or from a derived class.</source> <target state="translated">指定一或多個宣告的程式設計元素,只能從其本身的類別或從衍生的類別加以存取。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_one_or_more_declared_programming_elements_have_no_access_restrictions"> <source>Specifies that one or more declared programming elements have no access restrictions.</source> <target state="translated">指定一或多個宣告的程式設計元素,沒有存取限制。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_a_variable_or_property_can_be_read_but_not_written_to"> <source>Specifies that a variable or property can be read but not written to.</source> <target state="translated">指定可讀取但無法寫入的變數或屬性。</target> <note /> </trans-unit> <trans-unit id="Reallocates_storage_space_for_an_array_variable"> <source>Reallocates storage space for an array variable.</source> <target state="translated">重新配置陣列變數的儲存空間。</target> <note /> </trans-unit> <trans-unit id="Performs_an_arithmetic_right_shift_on_a_bit_pattern"> <source>Performs an arithmetic right shift on a bit pattern</source> <target state="translated">在位元模式上執行算術右位移</target> <note /> </trans-unit> <trans-unit id="Declares_a_Set_property_procedure_that_is_used_to_assign_a_value_to_a_property"> <source>Declares a Set property procedure that is used to assign a value to a property.</source> <target state="translated">宣告用以為屬性指派值的 Set 屬性程序。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_a_declared_programming_element_redeclares_and_hides_an_identically_named_element_in_a_base_class"> <source>Specifies that a declared programming element redeclares and hides an identically named element in a base class.</source> <target state="translated">指定宣告的程式設計項目會重新宣告並隱藏基底類別中的同名項目。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_one_or_more_declared_programming_elements_are_associated_with_all_instances_of_a_class_or_structure"> <source>Specifies that one or more declared programming elements are associated with all instances of a class or structure.</source> <target state="translated">指定一或多個宣告的程式設計元素,其會與類別或結構的所有執行個體相關聯。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_one_or_more_declared_local_variables_are_to_remain_in_existence_and_retain_their_latest_values_after_the_procedure_in_which_they_are_declared_terminates"> <source>Specifies that one or more declared local variables are to remain in existence and retain their latest values after the procedure in which they are declared terminates.</source> <target state="translated">指定一或多個宣告的區域變數在宣告該變數的程序結束後,仍會持續存在且保留最後的值。</target> <note /> </trans-unit> <trans-unit id="Declares_the_name_of_a_structure_and_introduces_the_definition_of_the_variables_properties_events_and_procedures_that_make_up_the_structure"> <source>Declares the name of a structure and introduces the definition of the variables, properties, events, and procedures that make up the structure.</source> <target state="translated">宣告結構的名稱,並引進組成結構之變數、屬性、事件與程序的定義。</target> <note /> </trans-unit> <trans-unit id="Declares_the_name_parameters_and_code_that_define_a_Sub_procedure_that_is_a_procedure_that_does_not_return_a_value_to_the_calling_code"> <source>Declares the name, parameters, and code that define a Sub procedure, that is, a procedure that does not return a value to the calling code.</source> <target state="translated">宣告定義 Sub 程序的名稱、參數與程式碼; 也就是說,這種程序不會對呼叫的程式碼傳回值。</target> <note /> </trans-unit> <trans-unit id="Separates_the_beginning_and_ending_values_of_a_loop_counter_or_array_bounds_or_that_of_a_value_match_range"> <source>Separates the beginning and ending values of a loop counter or array bounds or that of a value match range.</source> <target state="translated">分隔迴圈計數器或陣列界限的起始值與結束值,或值比對範圍的起始值與結束值。</target> <note /> </trans-unit> <trans-unit id="Determines_the_run_time_type_of_an_object_reference_variable_and_compares_it_to_a_data_type_Returns_True_or_False_depending_on_whether_the_two_types_are_compatible_result_TypeOf_objectExpression_Is_typeName"> <source>Determines the run-time type of an object reference variable and compares it to a data type. Returns True or False depending, on whether the two types are compatible. &lt;result&gt; = TypeOf &lt;objectExpression&gt; Is &lt;typeName&gt;</source> <target state="translated">判斷物件參考變數的執行階段類型,並與資料類型進行比較。依兩種類型是否相容,而傳回 True 或 False。 &lt;result&gt; = TypeOf &lt;objectExpression&gt; Is &lt;typeName&gt;</target> <note /> </trans-unit> <trans-unit id="Used_in_a_Declare_statement_Specifies_that_Visual_Basic_should_marshal_all_strings_to_Unicode_values_in_a_call_into_an_external_procedure_and_should_look_up_the_procedure_without_modifying_its_name"> <source>Used in a Declare statement. Specifies that Visual Basic should marshal all strings to Unicode values in a call into an external procedure, and should look up the procedure without modifying its name.</source> <target state="translated">用於 Declare 陳述式中。指定 Visual Basic 應在呼叫外部程序中,將所有字串封送處理成 Unicode 值,且應在不修改程序名稱的情況下,查詢該程序。</target> <note /> </trans-unit> <trans-unit id="Indicates_that_a_conversion_operator_CType_converts_a_class_or_structure_to_a_type_that_can_hold_all_possible_values_of_the_original_class_or_structure"> <source>Indicates that a conversion operator (CType) converts a class or structure to a type that can hold all possible values of the original class or structure.</source> <target state="translated">表示轉換運算子 (CType) 會將類別或結構,轉換成可容納原始類別或結構之所有可能值的類型。</target> <note /> </trans-unit> <trans-unit id="Specifies_that_one_or_more_declared_member_variables_refer_to_an_instance_of_a_class_that_can_raise_events"> <source>Specifies that one or more declared member variables refer to an instance of a class that can raise events</source> <target state="translated">指定一或多個宣告的成員變數會參考可能引發事件的類別執行個體</target> <note /> </trans-unit> <trans-unit id="Specifies_that_a_property_can_be_written_to_but_not_read"> <source>Specifies that a property can be written to but not read.</source> <target state="translated">指定可寫入但無法讀取的屬性。</target> <note /> </trans-unit> <trans-unit id="Performs_a_logical_exclusion_on_two_Boolean_expressions_or_a_bitwise_exclusion_on_two_numeric_expressions_For_Boolean_expressions_returns_True_if_exactly_one_of_the_expressions_evaluates_to_True_Both_expressions_are_always_evaluated_result_expression1_Xor_expression2"> <source>Performs a logical exclusion on two Boolean expressions, or a bitwise exclusion on two numeric expressions. For Boolean expressions, returns True if exactly one of the expressions evaluates to True. Both expressions are always evaluated. &lt;result&gt; = &lt;expression1&gt; Xor &lt;expression2&gt;</source> <target state="translated">在兩個布林運算式上執行邏輯排除,或在兩個數值運算式上執行位元排除。對於布林運算式而言,若剛好有一個運算元評估為 True,即傳回 True。兩個運算式都會進行評估。 &lt;result&gt; = &lt;expression1&gt; Xor &lt;expression2&gt;</target> <note /> </trans-unit> <trans-unit id="Applies_an_aggregation_function_such_as_Sum_Average_or_Count_to_a_sequence"> <source>Applies an aggregation function, such as Sum, Average, or Count to a sequence.</source> <target state="translated">套用彙總函式 (如 Sum、Average 或 Count) 到序列。</target> <note /> </trans-unit> <trans-unit id="Specifies_the_sort_order_for_an_Order_By_clause_in_a_query_The_smallest_element_will_appear_first"> <source>Specifies the sort order for an Order By clause in a query. The smallest element will appear first.</source> <target state="translated">指定查詢中 Order By 子句的排序順序。最小的元素最先出現。</target> <note /> </trans-unit> <trans-unit id="Sets_the_string_comparison_method_specified_in_Option_Compare_to_a_strict_binary_sort_order"> <source>Sets the string comparison method specified in Option Compare to a strict binary sort order.</source> <target state="translated">將 Option Compare 中指定的字串比較方法,設定為嚴格的二進位排序順序。</target> <note /> </trans-unit> <trans-unit id="Specifies_the_element_keys_used_for_grouping_in_Group_By_or_sort_order_in_Order_By"> <source>Specifies the element keys used for grouping (in Group By) or sort order (in Order By).</source> <target state="translated">指定用於分組 (Group By 中) 或排序順序 (Order By 中) 的元素索引鍵。</target> <note /> </trans-unit> <trans-unit id="Transfers_execution_to_a_Function_Sub_or_dynamic_link_library_DLL_procedure_bracket_Call_bracket_procedureName_bracket_argumentList_bracket"> <source>Transfers execution to a Function, Sub, or dynamic-link library (DLL) procedure. [Call] &lt;procedureName&gt; [(&lt;argumentList&gt;)]</source> <target state="translated">將執行轉移到 Function、Sub 或動態連結程式庫 (DLL) 程序。 [Call] &lt;procedureName&gt; [(&lt;argumentList&gt;)]</target> <note /> </trans-unit> <trans-unit id="Introduces_the_statements_to_run_if_none_of_the_previous_cases_in_the_Select_Case_statement_returns_True"> <source>Introduces the statements to run if none of the previous cases in the Select Case statement returns True.</source> <target state="translated">引進在 Select Case 陳述式中先前的案例都未傳回 True 時,會執行的陳述式。</target> <note /> </trans-unit> <trans-unit id="Followed_by_a_comparison_operator_and_then_an_expression_Case_Is_introduces_the_statements_to_run_if_the_Select_Case_expression_combined_with_the_Case_Is_expression_evaluates_to_True"> <source>Followed by a comparison operator and then an expression, Case Is introduces the statements to run if the Select Case expression combined with the Case Is expression evaluates to True.</source> <target state="translated">其後接著比較運算子,再接著運算式,Case Is 會引進當 Select Case 運算式與 Case Is 運算式組合在一起若評估為 True 時,所要執行的陳述式。</target> <note /> </trans-unit> <trans-unit id="Introduces_a_value_or_set_of_values_against_which_the_value_of_an_expression_in_a_Select_Case_statement_is_to_be_tested_Case_expression_expression1_To_expression2_bracket_Is_bracket_comparisonOperator_expression"> <source>Introduces a value, or set of values, against which the value of an expression in a Select Case statement is to be tested. Case {&lt;expression&gt;|&lt;expression1&gt; To &lt;expression2&gt;|[Is] &lt;comparisonOperator&gt; &lt;expression&gt;}</source> <target state="translated">引進一個值或一組值,並利用該值或該組值來測試 Select Case 陳述式中運算式的值。 Case {&lt;expression&gt;|&lt;expression1&gt; To &lt;expression2&gt;|[Is] &lt;comparisonOperator&gt; &lt;expression&gt;}</target> <note /> </trans-unit> <trans-unit id="Introduces_a_statement_block_to_be_run_if_the_specified_exception_occurs_inside_a_Try_block"> <source>Introduces a statement block to be run if the specified exception occurs inside a Try block.</source> <target state="translated">引進在 Try 區塊內發生指定的例外狀況時,所要執行的陳述式區塊。</target> <note /> </trans-unit> <trans-unit id="Sets_the_default_comparison_method_to_use_when_comparing_string_data_When_set_to_Text_uses_a_text_sort_order_that_is_not_case_sensitive_When_set_to_Binary_uses_a_strict_binary_sort_order_Option_Compare_Binary_Text"> <source>Sets the default comparison method to use when comparing string data. When set to Text, uses a text sort order that is not case sensitive. When set to Binary, uses a strict binary sort order. Option Compare {Binary | Text}</source> <target state="translated">設定比較字串資料時所用的預設比較方法。若設定為 Text,請使用不區分大小寫的文字排序順序。若設定為 Binary,請使用嚴格的二進位排序順序。 Option Compare {Binary | Text}</target> <note /> </trans-unit> <trans-unit id="Defines_a_conditional_compiler_constant_Conditional_compiler_constants_are_always_private_to_the_file_in_which_they_appear_The_expressions_used_to_initialize_them_can_contain_only_conditional_compiler_constants_and_literals"> <source>Defines a conditional compiler constant. Conditional compiler constants are always private to the file in which they appear. The expressions used to initialize them can contain only conditional compiler constants and literals.</source> <target state="translated">定義條件式編譯器常數。條件式編譯器常數在其所在之檔案中,一定會是私用常數。用於初始設定這類常數的運算式,只能包含條件式編譯器常數與常值。</target> <note /> </trans-unit> <trans-unit id="Transfers_execution_immediately_to_the_next_iteration_of_the_Do_loop"> <source>Transfers execution immediately to the next iteration of the Do loop.</source> <target state="translated">將執行立即轉移到 Do 迴圈的下一個反覆運算。</target> <note /> </trans-unit> <trans-unit id="Transfers_execution_immediately_to_the_next_iteration_of_the_For_loop"> <source>Transfers execution immediately to the next iteration of the For loop.</source> <target state="translated">將執行立即轉移到 For 迴圈的下一個反覆運算。</target> <note /> </trans-unit> <trans-unit id="Transfers_execution_immediately_to_the_next_iteration_of_the_loop_Can_be_used_in_a_Do_loop_a_For_loop_or_a_While_loop"> <source>Transfers execution immediately to the next iteration of the loop. Can be used in a Do loop, a For loop, or a While loop.</source> <target state="translated">將執行立即轉移到迴圈的下一個反覆運算。可用在 Do 迴圈、For 迴圈或 While 迴圈中。</target> <note /> </trans-unit> <trans-unit id="Transfers_execution_immediately_to_the_next_iteration_of_the_While_loop"> <source>Transfers execution immediately to the next iteration of the While loop.</source> <target state="translated">將執行立即轉移到 While 迴圈的下一個反覆運算。</target> <note /> </trans-unit> <trans-unit id="Specifies_the_sort_order_for_an_Order_By_clause_in_a_query_The_largest_element_will_appear_first"> <source>Specifies the sort order for an Order By clause in a query. The largest element will appear first.</source> <target state="translated">指定查詢中 Order By 子句的排序順序。最大的元素最先出現。</target> <note /> </trans-unit> <trans-unit id="Restricts_the_values_of_a_query_result_to_eliminate_duplicate_values"> <source>Restricts the values of a query result to eliminate duplicate values.</source> <target state="translated">限制查詢結果的值,以去除重複的值。</target> <note /> </trans-unit> <trans-unit id="Repeats_a_block_of_statements_while_a_Boolean_condition_is_true_or_until_the_condition_becomes_true_Do_Loop_While_Until_condition"> <source>Repeats a block of statements while a Boolean condition is true, or until the condition becomes true. Do...Loop {While | Until} &lt;condition&gt;</source> <target state="translated">在布林條件為 True 的情況下,或是在條件變成 True 之前,持續重複陳述式區塊。 Do...Loop {While | Until} &lt;condition&gt;</target> <note /> </trans-unit> <trans-unit id="Repeats_a_block_of_statements_until_a_Boolean_condition_becomes_true_Do_Until_condition_Loop"> <source>Repeats a block of statements until a Boolean condition becomes true. Do Until &lt;condition&gt;...Loop</source> <target state="translated">持續重複陳述式區塊,直到布林條件變成 True 為止。 Do Until &lt;condition&gt;...Loop</target> <note /> </trans-unit> <trans-unit id="Repeats_a_block_of_statements_while_a_Boolean_condition_is_true_Do_While_condition_Loop"> <source>Repeats a block of statements while a Boolean condition is true. Do While &lt;condition&gt;...Loop</source> <target state="translated">在布林條件為 True 的情況下,持續重複陳述式區塊。 Do While &lt;condition&gt;...Loop</target> <note /> </trans-unit> <trans-unit id="Introduces_a_group_of_statements_in_an_SharpIf_statement_that_is_compiled_if_no_previous_condition_evaluates_to_True"> <source>Introduces a group of statements in an #If statement that is compiled if no previous condition evaluates to True.</source> <target state="translated">在 #If 陳述式中引進引進若之前沒有條件評估為 True 時,就會編譯的一組陳述式。</target> <note /> </trans-unit> <trans-unit id="Introduces_a_condition_in_an_SharpIf_statement_that_is_tested_if_the_previous_conditional_test_evaluates_to_False"> <source>Introduces a condition in an #If statement that is tested if the previous conditional test evaluates to False.</source> <target state="translated">在 #If 陳述式中引進若之前的條件測試評估為 False 時,就會測試的條件。</target> <note /> </trans-unit> <trans-unit id="Introduces_a_condition_in_an_If_statement_that_is_to_be_tested_if_the_previous_conditional_test_fails"> <source>Introduces a condition in an If statement that is to be tested if the previous conditional test fails.</source> <target state="translated">在 If 陳述式中引進若之前的條件測試失敗,就會測試的條件。</target> <note /> </trans-unit> <trans-unit id="Introduces_a_group_of_statements_in_an_If_statement_that_is_executed_if_no_previous_condition_evaluates_to_True"> <source>Introduces a group of statements in an If statement that is executed if no previous condition evaluates to True.</source> <target state="translated">在 If 陳述式中引進若之前沒有條件評估為 True 時,就會執行的一組陳述式。</target> <note /> </trans-unit> <trans-unit id="Terminates_the_definition_of_an_SharpIf_block"> <source>Terminates the definition of an #If block.</source> <target state="translated">結束 #If 區塊的定義。</target> <note /> </trans-unit> <trans-unit id="Stops_execution_immediately"> <source>Stops execution immediately.</source> <target state="translated">立即停止執行。</target> <note /> </trans-unit> <trans-unit id="Terminates_a_SharpRegion_block"> <source>Terminates a #Region block.</source> <target state="translated">結束 #Region 區塊。</target> <note /> </trans-unit> <trans-unit id="Specifies_the_relationship_between_element_keys_to_use_as_the_basis_of_a_join_operation"> <source>Specifies the relationship between element keys to use as the basis of a join operation.</source> <target state="translated">指定元素索引鍵之間的關聯性,以用做為聯結作業的基礎。</target> <note /> </trans-unit> <trans-unit id="Simulates_the_occurrence_of_an_error"> <source>Simulates the occurrence of an error.</source> <target state="translated">模擬錯誤的發生。</target> <note /> </trans-unit> <trans-unit id="Exits_a_Do_loop_and_transfers_execution_immediately_to_the_statement_following_the_Loop_statement"> <source>Exits a Do loop and transfers execution immediately to the statement following the Loop statement.</source> <target state="translated">結束 Do 迴圈,將執行立即轉移到接在 Loop 陳述式之後的陳述式。</target> <note /> </trans-unit> <trans-unit id="Exits_a_For_loop_and_transfers_execution_immediately_to_the_statement_following_the_Next_statement"> <source>Exits a For loop and transfers execution immediately to the statement following the Next statement.</source> <target state="translated">結束 For 迴圈,並將執行立即轉移到接在 Next 陳述式之後的陳述式。</target> <note /> </trans-unit> <trans-unit id="Exits_a_procedure_or_block_and_transfers_execution_immediately_to_the_statement_following_the_procedure_call_or_block_definition_Exit_Do_For_Function_Property_Select_Sub_Try_While"> <source>Exits a procedure or block and transfers execution immediately to the statement following the procedure call or block definition. Exit {Do | For | Function | Property | Select | Sub | Try | While}</source> <target state="translated">結束程序或區塊,並將執行立即轉移到接在程序呼叫或區塊定義之後的陳述式。 Exit {Do | For | Function | Property | Select | Sub | Try | While}</target> <note /> </trans-unit> <trans-unit id="Exits_a_Select_block_and_transfers_execution_immediately_to_the_statement_following_the_End_Select_statement"> <source>Exits a Select block and transfers execution immediately to the statement following the End Select statement.</source> <target state="translated">結束 Select 區塊,並將執行立即轉移到接在 End Select 陳述式之後的陳述式。</target> <note /> </trans-unit> <trans-unit id="Exits_a_Try_block_and_transfers_execution_immediately_to_the_statement_following_the_End_Try_statement"> <source>Exits a Try block and transfers execution immediately to the statement following the End Try statement.</source> <target state="translated">結束 Try 區塊,將執行立即轉移到接在 End Try 陳述式之後的陳述式。</target> <note /> </trans-unit> <trans-unit id="Exits_a_While_loop_and_transfers_execution_immediately_to_the_statement_following_the_End_While_statement"> <source>Exits a While loop and transfers execution immediately to the statement following the End While statement.</source> <target state="translated">結束 While 迴圈,將執行立即轉移到接在 End While 陳述式之後的陳述式。</target> <note /> </trans-unit> <trans-unit id="When_set_to_On_requires_explicit_declaration_of_all_variables_using_a_Dim_Private_Public_or_ReDim_statement_Option_Explicit_On_Off"> <source>When set to On, requires explicit declaration of all variables, using a Dim, Private, Public, or ReDim statement. Option Explicit {On | Off}</source> <target state="translated">若設定為 On,則必須使用 Dim、Private、Public 或 ReDim 陳述式,明確地宣告所有變數。 Option Explicit {On | Off}</target> <note /> </trans-unit> <trans-unit id="Represents_a_Boolean_value_that_fails_a_conditional_test"> <source>Represents a Boolean value that fails a conditional test.</source> <target state="translated">代表條件測試失敗的布林值。</target> <note /> </trans-unit> <trans-unit id="Introduces_a_statement_block_to_be_run_before_exiting_a_Try_structure"> <source>Introduces a statement block to be run before exiting a Try structure.</source> <target state="translated">引進結束 Try 結構之前,所要執行的陳述式區塊。</target> <note /> </trans-unit> <trans-unit id="Introduces_a_loop_that_is_repeated_for_each_element_in_a_collection"> <source>Introduces a loop that is repeated for each element in a collection.</source> <target state="translated">引進為集合中每個元素重複運算的迴圈。</target> <note /> </trans-unit> <trans-unit id="Introduces_a_loop_that_is_iterated_a_specified_number_of_times"> <source>Introduces a loop that is iterated a specified number of times.</source> <target state="translated">引進會重複指定次數的迴圈。</target> <note /> </trans-unit> <trans-unit id="Identifies_a_list_of_values_as_a_collection_initializer"> <source>Identifies a list of values as a collection initializer</source> <target state="translated">將值的清單指定為集合初始設定式</target> <note /> </trans-unit> <trans-unit id="Branches_unconditionally_to_a_specified_line_in_a_procedure"> <source>Branches unconditionally to a specified line in a procedure.</source> <target state="translated">無條件分支到程序中的指定行。</target> <note /> </trans-unit> <trans-unit id="Groups_elements_that_have_a_common_key"> <source>Groups elements that have a common key.</source> <target state="translated">將具有共同索引鍵的元素分在一組。</target> <note /> </trans-unit> <trans-unit id="Combines_the_elements_of_two_sequences_and_groups_the_results_The_join_operation_is_based_on_matching_keys"> <source>Combines the elements of two sequences and groups the results. The join operation is based on matching keys.</source> <target state="translated">結合兩個序列的元素,並將結果分組。聯結作業會以相符的索引鍵為依據。</target> <note /> </trans-unit> <trans-unit id="Use_Group_to_specify_that_a_group_named_0_should_be_created"> <source>Use 'Group' to specify that a group named '{0}' should be created.</source> <target state="translated">Group' 可用以指定應建立名為 '{0}' 的群組。</target> <note /> </trans-unit> <trans-unit id="Use_Group_to_specify_that_a_group_named_Group_should_be_created"> <source>Use 'Group' to specify that a group named 'Group' should be created.</source> <target state="translated">Group' 可用以指定應建立名為 'Group' 的群組。</target> <note /> </trans-unit> <trans-unit id="Conditionally_compiles_selected_blocks_of_code_depending_on_the_value_of_an_expression"> <source>Conditionally compiles selected blocks of code, depending on the value of an expression.</source> <target state="translated">根據運算式的值,有條件地編譯選取的程式碼區塊。</target> <note /> </trans-unit> <trans-unit id="Conditionally_executes_a_group_of_statements_depending_on_the_value_of_an_expression"> <source>Conditionally executes a group of statements, depending on the value of an expression.</source> <target state="translated">根據運算式的值,有條件地執行陳述式群組。</target> <note /> </trans-unit> <trans-unit id="When_set_to_On_allows_the_use_of_local_type_inference_in_declaring_variables_Option_Infer_On_Off"> <source>When set to On, allows the use of local type inference in declaring variables. Option Infer {On | Off}</source> <target state="translated">若設定為 On,則可以在宣告變數中使用區域類型推斷。 Option Infer {On | Off}</target> <note /> </trans-unit> <trans-unit id="Specifies_an_identifier_that_can_serve_as_a_reference_to_the_results_of_a_join_or_grouping_subexpression"> <source>Specifies an identifier that can serve as a reference to the results of a join or grouping subexpression.</source> <target state="translated">指定可做為聯結或分組子運算式結果參考的識別項。</target> <note /> </trans-unit> <trans-unit id="Combines_the_elements_of_two_sequences_The_join_operation_is_based_on_matching_keys"> <source>Combines the elements of two sequences. The join operation is based on matching keys.</source> <target state="translated">結合兩個序列的元素。聯結作業會以相符的索引鍵為依據。</target> <note /> </trans-unit> <trans-unit id="Identifies_a_key_field_in_an_anonymous_type_definition"> <source>Identifies a key field in an anonymous type definition.</source> <target state="translated">指出匿名類型定義中的索引鍵欄位。</target> <note /> </trans-unit> <trans-unit id="Computes_a_value_for_each_item_in_the_query_and_assigns_the_value_to_a_new_range_variable"> <source>Computes a value for each item in the query, and assigns the value to a new range variable.</source> <target state="translated">計算查詢中每個項目的值,並將值指派給新的範圍變數。</target> <note /> </trans-unit> <trans-unit id="Terminates_a_loop_that_is_introduced_with_a_Do_statement"> <source>Terminates a loop that is introduced with a Do statement.</source> <target state="translated">結束利用 Do 陳述式所引進的迴圈。</target> <note /> </trans-unit> <trans-unit id="Repeats_a_block_of_statements_until_a_Boolean_condition_becomes_true_Do_Loop_Until_condition"> <source>Repeats a block of statements until a Boolean condition becomes true. Do...Loop Until &lt;condition&gt;</source> <target state="translated">持續重複陳述式區塊,直到布林條件變成 True 為止。 Do...Loop Until &lt;condition&gt;</target> <note /> </trans-unit> <trans-unit id="Repeats_a_block_of_statements_while_a_Boolean_condition_is_true_Do_Loop_While_condition"> <source>Repeats a block of statements while a Boolean condition is true. Do...Loop While &lt;condition&gt;</source> <target state="translated">在布林條件為 True 的情況下,持續重複陳述式區塊。 Do...Loop While &lt;condition&gt;</target> <note /> </trans-unit> <trans-unit id="Provides_a_way_to_refer_to_the_current_instance_of_a_class_or_structure_that_is_the_instance_in_which_the_code_is_running"> <source>Provides a way to refer to the current instance of a class or structure, that is, the instance in which the code is running.</source> <target state="translated">提供一種方法,來參考類別或結構目前的執行個體,也就是執行此程式碼的執行個體。</target> <note /> </trans-unit> <trans-unit id="Provides_a_way_to_refer_to_the_base_class_of_the_current_class_instance_You_cannot_use_MyBase_to_call_MustOverride_base_methods"> <source>Provides a way to refer to the base class of the current class instance. You cannot use MyBase to call MustOverride base methods.</source> <target state="translated">提供一種方法,來參考目前類別執行個體的基底類別。您無法使用 MyBase 呼叫 MustOverride 基底方法。</target> <note /> </trans-unit> <trans-unit id="Provides_a_way_to_refer_to_the_class_instance_members_as_originally_implemented_ignoring_any_derived_class_overrides"> <source>Provides a way to refer to the class instance members as originally implemented, ignoring any derived class overrides.</source> <target state="translated">提供一種方法,在忽略任何衍生之類別覆寫的情況下,以原始實作方式參考類別執行個體成員。</target> <note /> </trans-unit> <trans-unit id="Creates_a_new_object_instance"> <source>Creates a new object instance.</source> <target state="translated">建立新的物件執行個體。</target> <note /> </trans-unit> <trans-unit id="Terminates_a_loop_that_iterates_through_the_values_of_a_loop_variable"> <source>Terminates a loop that iterates through the values of a loop variable.</source> <target state="translated">反覆執行迴圈變數所指定的次數後,結束迴圈。</target> <note /> </trans-unit> <trans-unit id="Represents_the_default_value_of_any_data_type"> <source>Represents the default value of any data type.</source> <target state="translated">代表任何資料類型的預設值。</target> <note /> </trans-unit> <trans-unit id="Turns_a_compiler_option_off"> <source>Turns a compiler option off.</source> <target state="translated">關閉編譯器選項。</target> <note /> </trans-unit> <trans-unit id="Enables_the_error_handling_routine_that_starts_at_the_line_specified_in_the_line_argument_The_specified_line_must_be_in_the_same_procedure_as_the_On_Error_statement_On_Error_GoTo_bracket_label_0_1_bracket"> <source>Enables the error-handling routine that starts at the line specified in the line argument. The specified line must be in the same procedure as the On Error statement. On Error GoTo [&lt;label&gt; | 0 | -1]</source> <target state="translated">啟用錯誤處理常式,於行引數中所指定的行開始。 指定的行與 On Error 陳述式必須在同一個程序中。 On Error GoTo [&lt;label&gt; | 0 | -1]</target> <note /> </trans-unit> <trans-unit id="When_a_run_time_error_occurs_execution_transfers_to_the_statement_following_the_statement_or_procedure_call_that_resulted_in_the_error"> <source>When a run-time error occurs, execution transfers to the statement following the statement or procedure call that resulted in the error.</source> <target state="translated">發生執行階段錯誤時,執行會轉移到接著造成錯誤之陳述式或程序呼叫後的陳述式。</target> <note /> </trans-unit> <trans-unit id="Turns_a_compiler_option_on"> <source>Turns a compiler option on.</source> <target state="translated">開啟編譯器選項。</target> <note /> </trans-unit> <trans-unit id="Specifies_the_element_keys_used_to_correlate_sequences_for_a_join_operation"> <source>Specifies the element keys used to correlate sequences for a join operation.</source> <target state="translated">指定用以將聯結作業的序列相互關聯的元素索引鍵。</target> <note /> </trans-unit> <trans-unit id="Specifies_the_sort_order_for_columns_in_a_query_Can_be_followed_by_either_the_Ascending_or_the_Descending_keyword_If_neither_is_specified_Ascending_is_used"> <source>Specifies the sort order for columns in a query. Can be followed by either the Ascending or the Descending keyword. If neither is specified, Ascending is used.</source> <target state="translated">指定查詢中資料行的排序順序。其後可接著 Ascending 或 Descending 關鍵字,若都未指定,則會使用 Ascending。</target> <note /> </trans-unit> <trans-unit id="Specifies_the_statements_to_run_when_the_event_is_raised_by_the_RaiseEvent_statement_RaiseEvent_delegateSignature_End_RaiseEvent"> <source>Specifies the statements to run when the event is raised by the RaiseEvent statement. RaiseEvent(&lt;delegateSignature&gt;)...End RaiseEvent</source> <target state="translated">指定當 RaiseEvent 陳述式引發事件時,所要執行的陳述式。 RaiseEvent(&lt;delegateSignature&gt;)...End RaiseEvent</target> <note /> </trans-unit> <trans-unit id="Triggers_an_event_declared_at_module_level_within_a_class_form_or_document_RaiseEvent_eventName_bracket_argumentList_bracket"> <source>Triggers an event declared at module level within a class, form, or document. RaiseEvent &lt;eventName&gt; [(&lt;argumentList&gt;)]</source> <target state="translated">觸發於類別、表單或文件內的模組層級,所宣告的事件。 RaiseEvent &lt;eventName&gt; [(&lt;argumentList&gt;)]</target> <note /> </trans-unit> <trans-unit id="Collapses_and_hides_sections_of_code_in_Visual_Basic_files"> <source>Collapses and hides sections of code in Visual Basic files.</source> <target state="translated">摺疊並隱藏 Visual Basic 檔案中的程式碼區段。</target> <note /> </trans-unit> <trans-unit id="Returns_execution_to_the_code_that_called_the_Function_Sub_Get_Set_or_Operator_procedure_Return_or_Return_expression"> <source>Returns execution to the code that called the Function, Sub, Get, Set, or Operator procedure. Return -or- Return &lt;expression&gt;</source> <target state="translated">將執行傳回呼叫 Function、Sub、Get、Set 或 Operator 程序的程式碼。 Return -或- Return &lt;expression&gt;</target> <note /> </trans-unit> <trans-unit id="Runs_one_of_several_groups_of_statements_depending_on_the_value_of_an_expression"> <source>Runs one of several groups of statements, depending on the value of an expression.</source> <target state="translated">根據運算式的值,執行幾組陳述式中的一組。</target> <note /> </trans-unit> <trans-unit id="Specifies_which_columns_to_include_in_the_result_of_a_query"> <source>Specifies which columns to include in the result of a query.</source> <target state="translated">指定查詢結果中要包含的資料行。</target> <note /> </trans-unit> <trans-unit id="Skips_elements_up_to_a_specified_position_in_the_collection"> <source>Skips elements up to a specified position in the collection.</source> <target state="translated">略過集合中最多到指定位置為止的元素。</target> <note /> </trans-unit> <trans-unit id="Specifies_how_much_to_increment_between_each_loop_iteration"> <source>Specifies how much to increment between each loop iteration.</source> <target state="translated">指定每個迴圈反覆運算之間的增量。</target> <note /> </trans-unit> <trans-unit id="Suspends_program_execution"> <source>Suspends program execution.</source> <target state="translated">暫停程式的執行。</target> <note /> </trans-unit> <trans-unit id="When_set_to_On_restricts_implicit_data_type_conversions_to_only_widening_conversions_Option_Strict_On_Off"> <source>When set to On, restricts implicit data type conversions to only widening conversions. Option Strict {On | Off}</source> <target state="translated">若設定為 On,則隱含資料類型轉換將會限制為只有擴展轉換。 Option Strict {On | Off}</target> <note /> </trans-unit> <trans-unit id="Ensures_that_multiple_threads_do_not_execute_the_statement_block_at_the_same_time_SyncLock_object_End_Synclock"> <source>Ensures that multiple threads do not execute the statement block at the same time. SyncLock &lt;object&gt;...End Synclock</source> <target state="translated">確定不會有多個執行緒同時執行此陳述式區塊。 SyncLock &lt;object&gt;...End Synclock</target> <note /> </trans-unit> <trans-unit id="Includes_elements_up_to_a_specified_position_in_the_collection"> <source>Includes elements up to a specified position in the collection.</source> <target state="translated">包含集合中最多到指定位置為止的元素。</target> <note /> </trans-unit> <trans-unit id="Sets_the_string_comparison_method_specified_in_Option_Compare_to_a_text_sort_order_that_is_not_case_sensitive"> <source>Sets the string comparison method specified in Option Compare to a text sort order that is not case sensitive.</source> <target state="translated">將 Option Compare 中指定的字串比較方法,設定為不區分大小寫的文字排序順序。</target> <note /> </trans-unit> <trans-unit id="Introduces_a_statement_block_to_be_compiled_or_executed_if_a_tested_condition_is_true"> <source>Introduces a statement block to be compiled or executed if a tested condition is true.</source> <target state="translated">引進在測試的條件為 True 時,所要編譯或執行的陳述式區塊。</target> <note /> </trans-unit> <trans-unit id="Throws_an_exception_within_a_procedure_so_that_you_can_handle_it_with_structured_or_unstructured_exception_handling_code"> <source>Throws an exception within a procedure so that you can handle it with structured or unstructured exception-handling code.</source> <target state="translated">在程序中擲回例外狀況,使您能夠以結構化或無結構的例外狀況處理程式碼,來處理該例外狀況。</target> <note /> </trans-unit> <trans-unit id="Represents_a_Boolean_value_that_passes_a_conditional_test"> <source>Represents a Boolean value that passes a conditional test.</source> <target state="translated">代表通過條件測試的布林值。</target> <note /> </trans-unit> <trans-unit id="Provides_a_way_to_handle_some_or_all_possible_errors_that_might_occur_in_a_given_block_of_code_while_still_running_the_code_Try_bracket_Catch_bracket_Catch_Finally_End_Try"> <source>Provides a way to handle some or all possible errors that might occur in a given block of code, while still running the code. Try...[Catch]...{Catch | Finally}...End Try</source> <target state="translated">提供一種方法,在仍然繼續執行程式碼的情況下,處理指定程式碼區塊中可能發生的一些或所有錯誤。 Try...[Catch]...{Catch | Finally}...End Try</target> <note /> </trans-unit> <trans-unit id="A_Using_block_does_three_things_colon_it_creates_and_initializes_variables_in_the_resource_list_it_runs_the_code_in_the_block_and_it_disposes_of_the_variables_before_exiting_Resources_used_in_the_Using_block_must_implement_System_IDisposable_Using_resource1_bracket_resource2_bracket_End_Using"> <source>A Using block does three things: it creates and initializes variables in the resource list, it runs the code in the block, and it disposes of the variables before exiting. Resources used in the Using block must implement System.IDisposable. Using &lt;resource1&gt;[, &lt;resource2&gt;]...End Using</source> <target state="translated">Using 區塊有以下三個作用: 建立及初始設定資源清單中的變數、執行區塊中的程式碼,以及在結束前處置變數。Using 區塊中使用的資源,必須實作 System.IDisposable。 Using &lt;resource1&gt;[, &lt;resource2&gt;]...End Using</target> <note /> </trans-unit> <trans-unit id="Adds_a_conditional_test_to_a_Catch_statement_Exceptions_are_caught_by_that_Catch_statement_only_when_the_conditional_test_that_follows_the_When_keyword_evaluates_to_True"> <source>Adds a conditional test to a Catch statement. Exceptions are caught by that Catch statement only when the conditional test that follows the When keyword evaluates to True.</source> <target state="translated">在 Catch 陳述式中加入條件測試。只有接在 When 關鍵字之後的條件測試,評估為 True 時,Catch 陳述式才會捕捉到例外狀況。</target> <note /> </trans-unit> <trans-unit id="Specifies_the_filtering_condition_for_a_range_variable_in_a_query"> <source>Specifies the filtering condition for a range variable in a query.</source> <target state="translated">指定查詢中範圍變數的篩選條件。</target> <note /> </trans-unit> <trans-unit id="Runs_a_series_of_statements_as_long_as_a_given_condition_is_true"> <source>Runs a series of statements as long as a given condition is true.</source> <target state="translated">在指定的條件為 True 的情況下,執行一系列的陳述式。</target> <note /> </trans-unit> <trans-unit id="Specifies_a_condition_for_Skip_and_Take_operations_Elements_will_be_bypassed_or_included_as_long_as_the_condition_is_true"> <source>Specifies a condition for Skip and Take operations. Elements will be bypassed or included as long as the condition is true.</source> <target state="translated">指定 Skip 和 Take 作業的條件。只要條件為 True,就會略過或包含這些項目。</target> <note /> </trans-unit> <trans-unit id="Specifies_the_declaration_of_property_initializations_in_an_object_initializer_New_typeName_With_bracket_property_expression_bracket_bracket_bracket"> <source>Specifies the declaration of property initializations in an object initializer. New &lt;typeName&gt; With {[.&lt;property&gt; = &lt;expression&gt;][,...]}</source> <target state="translated">指定物件初始設定式中屬性初始設定的宣告。 New &lt;typeName&gt; With {[.&lt;property&gt; = &lt;expression&gt;][,...]}</target> <note /> </trans-unit> <trans-unit id="Runs_a_series_of_statements_that_refer_to_a_single_object_or_structure_With_object_End_With"> <source>Runs a series of statements that refer to a single object or structure. With &lt;object&gt;...End With</source> <target state="translated">執行一系列參考單一物件或結構的陳述式。 With &lt;object&gt;...End With</target> <note /> </trans-unit> <trans-unit id="Produces_an_element_of_an_IEnumerable_or_IEnumerator"> <source>Produces an element of an IEnumerable or IEnumerator.</source> <target state="translated">產生 IEnumerable 或 IEnumerator 的元素。</target> <note /> </trans-unit> <trans-unit id="Defines_an_asynchronous_lambda_expression_that_can_use_the_Await_operator_Can_be_used_wherever_a_delegate_type_is_expected_Async_Sub_Function_parameterList_expression"> <source>Defines an asynchronous lambda expression that can use the Await operator. Can be used wherever a delegate type is expected. Async Sub/Function(&lt;parameterList&gt;) &lt;expression&gt;</source> <target state="translated">定義可以使用 Await 運算子的非同步 Lambda 運算式。可用於必須是委派類型時。 Async Sub/Function(&lt;parameterList&gt;) &lt;expression&gt;</target> <note /> </trans-unit> <trans-unit id="Defines_a_lambda_expression_that_calculates_and_returns_a_single_value_Can_be_used_wherever_a_delegate_type_is_expected_Function_parameterList_expression"> <source>Defines a lambda expression that calculates and returns a single value. Can be used wherever a delegate type is expected. Function(&lt;parameterList&gt;) &lt;expression&gt;</source> <target state="translated">定義計算並傳回單一值的 Lambda 運算式。可用於必須是委派類型時。 Function(&lt;parameterList&gt;) &lt;expression&gt;</target> <note /> </trans-unit> <trans-unit id="Defines_a_lambda_expression_that_can_execute_statements_and_does_not_return_a_value_Can_be_used_wherever_a_delegate_type_is_expected_Sub_parameterList_statement"> <source>Defines a lambda expression that can execute statements and does not return a value. Can be used wherever a delegate type is expected. Sub(&lt;parameterList&gt;) &lt;statement&gt;</source> <target state="translated">定義可執行陳述式但不傳回值的 Lambda 運算式。可用於必須是委派類型時。 Sub(&lt;parameterList&gt;) &lt;statement&gt;</target> <note /> </trans-unit> <trans-unit id="Disables_reporting_of_specified_warnings_in_the_portion_of_the_source_file_below_the_current_line"> <source>Disables reporting of specified warnings in the portion of the source file below the current line.</source> <target state="translated">停用目前這一行下方原始程式檔部分中,指定之警告的回報功能。</target> <note /> </trans-unit> <trans-unit id="Enables_reporting_of_specified_warnings_in_the_portion_of_the_source_file_below_the_current_line"> <source>Enables reporting of specified warnings in the portion of the source file below the current line.</source> <target state="translated">啟用目前這一行下方原始程式檔部分中,指定之警告的回報功能。</target> <note /> </trans-unit> <trans-unit id="Insert_Await"> <source>Insert 'Await'.</source> <target state="translated">插入 'Await'。</target> <note /> </trans-unit> <trans-unit id="Make_0_an_Async_Function"> <source>Make {0} an Async Function.</source> <target state="translated">讓 {0} 成為非同步函式。</target> <note /> </trans-unit> <trans-unit id="Convert_0_to_Iterator"> <source>Convert {0} to Iterator</source> <target state="translated">將 {0} 轉換為 Iterator</target> <note /> </trans-unit> <trans-unit id="Replace_Return_with_Yield"> <source>Replace 'Return' with 'Yield</source> <target state="translated">以 'Yield' 取代 'Return'</target> <note /> </trans-unit> <trans-unit id="Use_the_correct_control_variable"> <source>Use the correct control variable</source> <target state="translated">使用正確的控制變數</target> <note /> </trans-unit> <trans-unit id="NameOf_function"> <source>NameOf function</source> <target state="translated">NameOf 函式</target> <note /> </trans-unit> <trans-unit id="Generate_narrowing_conversion_in_0"> <source>Generate narrowing conversion in '{0}'</source> <target state="translated">在 '{0}' 中產生縮小轉換</target> <note /> </trans-unit> <trans-unit id="Generate_widening_conversion_in_0"> <source>Generate widening conversion in '{0}'</source> <target state="translated">在 '{0}' 中產生放大轉換</target> <note /> </trans-unit> <trans-unit id="Try_block"> <source>Try block</source> <target state="translated">Try 區塊</target> <note>{Locked="Try"} "Try" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Catch_clause"> <source>Catch clause</source> <target state="translated">Catch 子句</target> <note>{Locked="Catch"} "Catch" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Finally_clause"> <source>Finally clause</source> <target state="translated">Finally 子句</target> <note>{Locked="Finally"} "Finally" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Using_statement"> <source>Using statement</source> <target state="translated">Using 陳述式</target> <note>{Locked="Using"} "Using" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Using_block"> <source>Using block</source> <target state="translated">Using 區塊</target> <note>{Locked="Using"} "Using" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="With_statement"> <source>With statement</source> <target state="translated">With 陳述式</target> <note>{Locked="With"} "With" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="With_block"> <source>With block</source> <target state="translated">With 區塊</target> <note>{Locked="With"} "With" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="SyncLock_statement"> <source>SyncLock statement</source> <target state="translated">SyncLock 陳述式</target> <note>{Locked="SyncLock"} "SyncLock" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="SyncLock_block"> <source>SyncLock block</source> <target state="translated">SyncLock 區塊</target> <note>{Locked="SyncLock"} "SyncLock" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="For_Each_statement"> <source>For Each statement</source> <target state="translated">For Each 陳述式</target> <note>{Locked="For Each"} "For Each" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="For_Each_block"> <source>For Each block</source> <target state="translated">For Each 區塊</target> <note>{Locked="For Each"} "For Each" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="On_Error_statement"> <source>On Error statement</source> <target state="translated">On Error 陳述式</target> <note>{Locked="On Error"} "On Error" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Resume_statement"> <source>Resume statement</source> <target state="translated">Resume 陳述式</target> <note>{Locked="Resume"} "Resume" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Yield_statement"> <source>Yield statement</source> <target state="translated">Yield 陳述式</target> <note>{Locked="Yield"} "Yield" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Await_expression"> <source>Await expression</source> <target state="translated">Await 運算式</target> <note>{Locked="Await"} "Await" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Lambda"> <source>Lambda</source> <target state="translated">Lambda</target> <note /> </trans-unit> <trans-unit id="Where_clause"> <source>Where clause</source> <target state="translated">Where 子句</target> <note>{Locked="Where"} "Where" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Select_clause"> <source>Select clause</source> <target state="translated">Select 子句</target> <note>{Locked="Select"} "Select" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="From_clause"> <source>From clause</source> <target state="translated">From 子句</target> <note>{Locked="From"} "From" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Aggregate_clause"> <source>Aggregate clause</source> <target state="translated">Aggregate 子句</target> <note>{Locked="Aggregate"} "Aggregate" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Let_clause"> <source>Let clause</source> <target state="translated">Let 子句</target> <note>{Locked="Let"} "Let" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Join_clause"> <source>Join clause</source> <target state="translated">Join 子句</target> <note>{Locked="Join"} "Join" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Group_Join_clause"> <source>Group Join clause</source> <target state="translated">Group Join 子句</target> <note>{Locked="Group Join"} "Group Join" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Group_By_clause"> <source>Group By clause</source> <target state="translated">Group By 子句</target> <note>{Locked="Group By"} "Group By" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Function_aggregation"> <source>Function aggregation</source> <target state="translated">函式彙總</target> <note /> </trans-unit> <trans-unit id="Take_While_clause"> <source>Take While clause</source> <target state="translated">Take While 子句</target> <note>{Locked="Take While"} "Take While" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Skip_While_clause"> <source>Skip While clause</source> <target state="translated">Skip While 子句</target> <note>{Locked="Skip While"} "Skip While" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Ordering_clause"> <source>Ordering clause</source> <target state="translated">Ordering 子句</target> <note>{Locked="Ordering"} "Ordering" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Join_condition"> <source>Join condition</source> <target state="translated">Join 條件</target> <note>{Locked="Join"} "Join" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="WithEvents_field"> <source>WithEvents field</source> <target state="translated">WithEvents 欄位</target> <note>{Locked="WithEvents"} "WithEvents" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="as_clause"> <source>as clause</source> <target state="translated">as 子句</target> <note>{Locked="as"} "as" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="type_parameters"> <source>type parameters</source> <target state="translated">類型參數</target> <note /> </trans-unit> <trans-unit id="parameters"> <source>parameters</source> <target state="translated">參數</target> <note /> </trans-unit> <trans-unit id="attributes"> <source>attributes</source> <target state="translated">屬性</target> <note /> </trans-unit> <trans-unit id="Too_many_arguments_to_0"> <source>Too many arguments to '{0}'.</source> <target state="translated">'{0}' 的引數太多。</target> <note /> </trans-unit> <trans-unit id="Type_0_is_not_defined"> <source>Type '{0}' is not defined.</source> <target state="translated">類型 '{0}' 未定義。</target> <note /> </trans-unit> <trans-unit id="Add_Overloads"> <source>Add 'Overloads'</source> <target state="translated">新增 'Overloads'</target> <note>{Locked="Overloads"} "Overloads" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Add_a_metadata_reference_to_specified_assembly_and_all_its_dependencies_e_g_Sharpr_myLib_dll"> <source>Add a metadata reference to specified assembly and all its dependencies, e.g. #r "myLib.dll".</source> <target state="translated">將中繼資料參考加入指定的組件及其所有相依性中,例如 #r "myLib.dll"。</target> <note /> </trans-unit> <trans-unit id="Properties"> <source>Properties</source> <target state="translated">屬性</target> <note /> </trans-unit> <trans-unit id="namespace_name"> <source>&lt;namespace name&gt;</source> <target state="translated">&lt;命名空間名稱&gt;</target> <note /> </trans-unit> <trans-unit id="Type_a_name_here_to_declare_a_namespace"> <source>Type a name here to declare a namespace.</source> <target state="translated">在此輸入名稱以宣告命名空間。</target> <note /> </trans-unit> <trans-unit id="Type_a_name_here_to_declare_a_partial_class"> <source>Type a name here to declare a partial class.</source> <target state="translated">在這裡鍵入名稱以宣告部分類別。</target> <note /> </trans-unit> <trans-unit id="class_name"> <source>&lt;class name&gt;</source> <target state="translated">&lt;類別名稱&gt;</target> <note /> </trans-unit> <trans-unit id="interface_name"> <source>&lt;interface name&gt;</source> <target state="translated">&lt;介面名稱&gt;</target> <note /> </trans-unit> <trans-unit id="module_name"> <source>&lt;module name&gt;</source> <target state="translated">&lt;模組名稱&gt;</target> <note /> </trans-unit> <trans-unit id="structure_name"> <source>&lt;structure name&gt;</source> <target state="translated">&lt;結構名稱&gt;</target> <note /> </trans-unit> <trans-unit id="Type_a_name_here_to_declare_a_partial_interface"> <source>Type a name here to declare a partial interface.</source> <target state="translated">在這裡鍵入名稱以宣告部分類型。</target> <note /> </trans-unit> <trans-unit id="Type_a_name_here_to_declare_a_partial_module"> <source>Type a name here to declare a partial module.</source> <target state="translated">在這裡鍵入名稱以宣告部分類型。</target> <note /> </trans-unit> <trans-unit id="Type_a_name_here_to_declare_a_partial_structure"> <source>Type a name here to declare a partial structure.</source> <target state="translated">在這裡鍵入名稱以宣告部分類型。</target> <note /> </trans-unit> <trans-unit id="Event_add_handler_name"> <source>{0}.add</source> <target state="translated">{0}.add</target> <note>The name of an event add handler where "{0}" is the event name.</note> </trans-unit> <trans-unit id="Event_remove_handler_name"> <source>{0}.remove</source> <target state="translated">{0}.remove</target> <note>The name of an event remove handler where "{0}" is the event name.</note> </trans-unit> <trans-unit id="Property_getter_name"> <source>{0}.get</source> <target state="translated">{0}.get</target> <note>The name of a property getter like "public int MyProperty { get; }" where "{0}" is the property name</note> </trans-unit> <trans-unit id="Property_setter_name"> <source>{0}.set</source> <target state="translated">{0}.set</target> <note>The name of a property setter like "public int MyProperty { set; }" where "{0}" is the property name</note> </trans-unit> <trans-unit id="Make_Async_Function"> <source>Make Async Function</source> <target state="translated">讓非同步函式</target> <note /> </trans-unit> <trans-unit id="Make_Async_Sub"> <source>Make Async Sub</source> <target state="translated">轉換為非同步 Sub</target> <note /> </trans-unit> <trans-unit id="Convert_to_Select_Case"> <source>Convert to 'Select Case'</source> <target state="translated">轉換為 'Select Case'</target> <note /> </trans-unit> <trans-unit id="Convert_to_For_Each"> <source>Convert to 'For Each'</source> <target state="translated">轉換為 'For Each'</target> <note /> </trans-unit> <trans-unit id="Convert_to_For"> <source>Convert to 'For'</source> <target state="translated">轉換為 'For'</target> <note /> </trans-unit> <trans-unit id="Invert_If"> <source>Invert If</source> <target state="translated">反轉 IF</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Features/Core/Portable/MetadataAsSource/AbstractMetadataAsSourceService.WrappedMethodSymbol.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.Reflection.Metadata; using Microsoft.CodeAnalysis.DocumentationComments; namespace Microsoft.CodeAnalysis.MetadataAsSource { internal partial class AbstractMetadataAsSourceService { private class WrappedMethodSymbol : AbstractWrappedSymbol, IMethodSymbol { private readonly IMethodSymbol _symbol; public WrappedMethodSymbol(IMethodSymbol methodSymbol, bool canImplementImplicitly, IDocumentationCommentFormattingService docCommentFormattingService) : base(methodSymbol, canImplementImplicitly, docCommentFormattingService) { _symbol = methodSymbol; } public int Arity => _symbol.Arity; public ISymbol AssociatedSymbol => _symbol.AssociatedSymbol; public INamedTypeSymbol AssociatedAnonymousDelegate => _symbol.AssociatedAnonymousDelegate; public IMethodSymbol ConstructedFrom => _symbol.ConstructedFrom; public bool IsReadOnly => _symbol.IsReadOnly; public bool IsInitOnly => _symbol.IsInitOnly; public System.Reflection.MethodImplAttributes MethodImplementationFlags => _symbol.MethodImplementationFlags; public ImmutableArray<IMethodSymbol> ExplicitInterfaceImplementations { get { return CanImplementImplicitly ? ImmutableArray.Create<IMethodSymbol>() : _symbol.ExplicitInterfaceImplementations; } } public bool HidesBaseMethodsByName => _symbol.HidesBaseMethodsByName; public bool IsExtensionMethod => _symbol.IsExtensionMethod; public bool IsGenericMethod => _symbol.IsGenericMethod; public bool IsAsync => _symbol.IsAsync; public MethodKind MethodKind => _symbol.MethodKind; public new IMethodSymbol OriginalDefinition { get { return this; } } public IMethodSymbol OverriddenMethod => _symbol.OverriddenMethod; public ImmutableArray<IParameterSymbol> Parameters => _symbol.Parameters; public IMethodSymbol PartialDefinitionPart => _symbol.PartialDefinitionPart; public IMethodSymbol PartialImplementationPart => _symbol.PartialImplementationPart; public bool IsPartialDefinition => _symbol.IsPartialDefinition; public ITypeSymbol ReceiverType => _symbol.ReceiverType; public NullableAnnotation ReceiverNullableAnnotation => _symbol.ReceiverNullableAnnotation; public IMethodSymbol ReducedFrom => // This implementation feels incorrect! _symbol.ReducedFrom; public ITypeSymbol GetTypeInferredDuringReduction(ITypeParameterSymbol reducedFromTypeParameter) { // This implementation feels incorrect, but it follows the pattern that other extension method related APIs are using! return _symbol.GetTypeInferredDuringReduction(reducedFromTypeParameter); } public bool ReturnsVoid => _symbol.ReturnsVoid; public bool ReturnsByRef => _symbol.ReturnsByRef; public bool ReturnsByRefReadonly => _symbol.ReturnsByRefReadonly; public RefKind RefKind => _symbol.RefKind; public ITypeSymbol ReturnType => _symbol.ReturnType; public NullableAnnotation ReturnNullableAnnotation => _symbol.ReturnNullableAnnotation; public ImmutableArray<AttributeData> GetReturnTypeAttributes() => _symbol.GetReturnTypeAttributes(); public ImmutableArray<CustomModifier> RefCustomModifiers => _symbol.RefCustomModifiers; public ImmutableArray<CustomModifier> ReturnTypeCustomModifiers => _symbol.ReturnTypeCustomModifiers; public ImmutableArray<ITypeSymbol> TypeArguments => _symbol.TypeArguments; public ImmutableArray<NullableAnnotation> TypeArgumentNullableAnnotations => _symbol.TypeArgumentNullableAnnotations; public ImmutableArray<ITypeParameterSymbol> TypeParameters => _symbol.TypeParameters; public IMethodSymbol Construct(params ITypeSymbol[] typeArguments) => _symbol.Construct(typeArguments); public IMethodSymbol Construct(ImmutableArray<ITypeSymbol> typeArguments, ImmutableArray<NullableAnnotation> typeArgumentNullableAnnotations) => _symbol.Construct(typeArguments, typeArgumentNullableAnnotations); public DllImportData GetDllImportData() => _symbol.GetDllImportData(); public IMethodSymbol ReduceExtensionMethod(ITypeSymbol receiverType) { // This implementation feels incorrect! return _symbol.ReduceExtensionMethod(receiverType); } public bool IsVararg => _symbol.IsVararg; public bool IsCheckedBuiltin => _symbol.IsCheckedBuiltin; public bool IsConditional => _symbol.IsConditional; public SignatureCallingConvention CallingConvention => _symbol.CallingConvention; public ImmutableArray<INamedTypeSymbol> UnmanagedCallingConventionTypes => _symbol.UnmanagedCallingConventionTypes; } } }
// Licensed to the .NET Foundation under one or more 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.Reflection.Metadata; using Microsoft.CodeAnalysis.DocumentationComments; namespace Microsoft.CodeAnalysis.MetadataAsSource { internal partial class AbstractMetadataAsSourceService { private class WrappedMethodSymbol : AbstractWrappedSymbol, IMethodSymbol { private readonly IMethodSymbol _symbol; public WrappedMethodSymbol(IMethodSymbol methodSymbol, bool canImplementImplicitly, IDocumentationCommentFormattingService docCommentFormattingService) : base(methodSymbol, canImplementImplicitly, docCommentFormattingService) { _symbol = methodSymbol; } public int Arity => _symbol.Arity; public ISymbol AssociatedSymbol => _symbol.AssociatedSymbol; public INamedTypeSymbol AssociatedAnonymousDelegate => _symbol.AssociatedAnonymousDelegate; public IMethodSymbol ConstructedFrom => _symbol.ConstructedFrom; public bool IsReadOnly => _symbol.IsReadOnly; public bool IsInitOnly => _symbol.IsInitOnly; public System.Reflection.MethodImplAttributes MethodImplementationFlags => _symbol.MethodImplementationFlags; public ImmutableArray<IMethodSymbol> ExplicitInterfaceImplementations { get { return CanImplementImplicitly ? ImmutableArray.Create<IMethodSymbol>() : _symbol.ExplicitInterfaceImplementations; } } public bool HidesBaseMethodsByName => _symbol.HidesBaseMethodsByName; public bool IsExtensionMethod => _symbol.IsExtensionMethod; public bool IsGenericMethod => _symbol.IsGenericMethod; public bool IsAsync => _symbol.IsAsync; public MethodKind MethodKind => _symbol.MethodKind; public new IMethodSymbol OriginalDefinition { get { return this; } } public IMethodSymbol OverriddenMethod => _symbol.OverriddenMethod; public ImmutableArray<IParameterSymbol> Parameters => _symbol.Parameters; public IMethodSymbol PartialDefinitionPart => _symbol.PartialDefinitionPart; public IMethodSymbol PartialImplementationPart => _symbol.PartialImplementationPart; public bool IsPartialDefinition => _symbol.IsPartialDefinition; public ITypeSymbol ReceiverType => _symbol.ReceiverType; public NullableAnnotation ReceiverNullableAnnotation => _symbol.ReceiverNullableAnnotation; public IMethodSymbol ReducedFrom => // This implementation feels incorrect! _symbol.ReducedFrom; public ITypeSymbol GetTypeInferredDuringReduction(ITypeParameterSymbol reducedFromTypeParameter) { // This implementation feels incorrect, but it follows the pattern that other extension method related APIs are using! return _symbol.GetTypeInferredDuringReduction(reducedFromTypeParameter); } public bool ReturnsVoid => _symbol.ReturnsVoid; public bool ReturnsByRef => _symbol.ReturnsByRef; public bool ReturnsByRefReadonly => _symbol.ReturnsByRefReadonly; public RefKind RefKind => _symbol.RefKind; public ITypeSymbol ReturnType => _symbol.ReturnType; public NullableAnnotation ReturnNullableAnnotation => _symbol.ReturnNullableAnnotation; public ImmutableArray<AttributeData> GetReturnTypeAttributes() => _symbol.GetReturnTypeAttributes(); public ImmutableArray<CustomModifier> RefCustomModifiers => _symbol.RefCustomModifiers; public ImmutableArray<CustomModifier> ReturnTypeCustomModifiers => _symbol.ReturnTypeCustomModifiers; public ImmutableArray<ITypeSymbol> TypeArguments => _symbol.TypeArguments; public ImmutableArray<NullableAnnotation> TypeArgumentNullableAnnotations => _symbol.TypeArgumentNullableAnnotations; public ImmutableArray<ITypeParameterSymbol> TypeParameters => _symbol.TypeParameters; public IMethodSymbol Construct(params ITypeSymbol[] typeArguments) => _symbol.Construct(typeArguments); public IMethodSymbol Construct(ImmutableArray<ITypeSymbol> typeArguments, ImmutableArray<NullableAnnotation> typeArgumentNullableAnnotations) => _symbol.Construct(typeArguments, typeArgumentNullableAnnotations); public DllImportData GetDllImportData() => _symbol.GetDllImportData(); public IMethodSymbol ReduceExtensionMethod(ITypeSymbol receiverType) { // This implementation feels incorrect! return _symbol.ReduceExtensionMethod(receiverType); } public bool IsVararg => _symbol.IsVararg; public bool IsCheckedBuiltin => _symbol.IsCheckedBuiltin; public bool IsConditional => _symbol.IsConditional; public SignatureCallingConvention CallingConvention => _symbol.CallingConvention; public ImmutableArray<INamedTypeSymbol> UnmanagedCallingConventionTypes => _symbol.UnmanagedCallingConventionTypes; } } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/EditorFeatures/VisualBasicTest/LineCommit/CommitTestData.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 System.Xml.Linq Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit Imports Microsoft.CodeAnalysis.Indentation Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.Text.Shared.Extensions Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Imports Microsoft.VisualStudio.Text.Operations Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.LineCommit Friend Class CommitTestData Implements IDisposable Public ReadOnly Buffer As ITextBuffer Public ReadOnly CommandHandler As CommitCommandHandler Public ReadOnly EditorOperations As IEditorOperations Public ReadOnly Workspace As TestWorkspace Public ReadOnly View As ITextView Public ReadOnly UndoHistory As ITextUndoHistory Private ReadOnly _formatter As FormatterMock Private ReadOnly _inlineRenameService As InlineRenameServiceMock Public Shared Function Create(test As XElement) As CommitTestData Dim workspace = TestWorkspace.Create(test, composition:=EditorTestCompositions.EditorFeaturesWpf) Return New CommitTestData(workspace) End Function Public Sub New(workspace As TestWorkspace) Me.Workspace = workspace View = workspace.Documents.Single().GetTextView() EditorOperations = workspace.GetService(Of IEditorOperationsFactoryService).GetEditorOperations(View) Dim position = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value View.Caret.MoveTo(New SnapshotPoint(View.TextSnapshot, position)) Buffer = workspace.Documents.Single().GetTextBuffer() ' HACK: We may have already created a CommitBufferManager for the buffer, so remove it If Buffer.Properties.ContainsProperty(GetType(CommitBufferManager)) Then Dim oldManager = Buffer.Properties.GetProperty(Of CommitBufferManager)(GetType(CommitBufferManager)) oldManager.RemoveReferencingView() Buffer.Properties.RemoveProperty(GetType(CommitBufferManager)) End If Dim textUndoHistoryRegistry = workspace.GetService(Of ITextUndoHistoryRegistry)() UndoHistory = textUndoHistoryRegistry.GetHistory(View.TextBuffer) _formatter = New FormatterMock(workspace) _inlineRenameService = New InlineRenameServiceMock() Dim commitManagerFactory As New CommitBufferManagerFactory(_formatter, _inlineRenameService, workspace.GetService(Of IThreadingContext)) ' Make sure the manager exists for the buffer Dim commitManager = commitManagerFactory.CreateForBuffer(Buffer) commitManager.AddReferencingView() CommandHandler = New CommitCommandHandler( commitManagerFactory, workspace.GetService(Of IEditorOperationsFactoryService), workspace.GetService(Of ISmartIndentationService), textUndoHistoryRegistry) End Sub Friend Sub AssertHadCommit(expectCommit As Boolean) Assert.Equal(expectCommit, _formatter.GotCommit) End Sub Friend Sub AssertUsedSemantics(expected As Boolean) Assert.Equal(expected, _formatter.UsedSemantics) End Sub Friend Sub StartInlineRenameSession() _inlineRenameService.HasSession = True End Sub Public Sub Dispose() Implements IDisposable.Dispose Workspace.Dispose() End Sub Private Class InlineRenameServiceMock Implements IInlineRenameService Public Property HasSession As Boolean Public ReadOnly Property ActiveSession As IInlineRenameSession Implements IInlineRenameService.ActiveSession Get Return If(HasSession, New MockInlineRenameSession(), Nothing) End Get End Property Public Function StartInlineSession(snapshot As Document, triggerSpan As TextSpan, Optional cancellationToken As CancellationToken = Nothing) As InlineRenameSessionInfo Implements IInlineRenameService.StartInlineSession Throw New NotImplementedException() End Function Private Class MockInlineRenameSession Implements IInlineRenameSession Public Sub Cancel() Implements IInlineRenameSession.Cancel Throw New NotImplementedException() End Sub Public Sub Commit(Optional previewChanges As Boolean = False) Implements IInlineRenameSession.Commit Throw New NotImplementedException() End Sub End Class End Class Private Class FormatterMock Implements ICommitFormatter Private ReadOnly _testWorkspace As TestWorkspace Public Property GotCommit As Boolean Public Property UsedSemantics As Boolean Public Sub New(testWorkspace As TestWorkspace) _testWorkspace = testWorkspace End Sub Public Sub CommitRegion(spanToFormat As SnapshotSpan, isExplicitFormat As Boolean, useSemantics As Boolean, dirtyRegion As SnapshotSpan, baseSnapshot As ITextSnapshot, baseTree As SyntaxTree, cancellationToken As CancellationToken) Implements ICommitFormatter.CommitRegion GotCommit = True UsedSemantics = useSemantics ' Assert the span if we have an assertion If _testWorkspace.Documents.Any(Function(d) d.SelectedSpans.Any()) Then Dim expectedSpan = _testWorkspace.Documents.Single(Function(d) d.SelectedSpans.Any()).SelectedSpans.Single() Dim trackingSpan = _testWorkspace.Documents.Single().InitialTextSnapshot.CreateTrackingSpan(expectedSpan.ToSpan(), SpanTrackingMode.EdgeInclusive) Assert.Equal(trackingSpan.GetSpan(spanToFormat.Snapshot), spanToFormat.Span) End If Dim realCommitFormatter = Assert.IsType(Of CommitFormatter)(_testWorkspace.GetService(Of ICommitFormatter)()) realCommitFormatter.CommitRegion(spanToFormat, isExplicitFormat, useSemantics, dirtyRegion, baseSnapshot, baseTree, cancellationToken) 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.Threading Imports System.Xml.Linq Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit Imports Microsoft.CodeAnalysis.Indentation Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.Text.Shared.Extensions Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Imports Microsoft.VisualStudio.Text.Operations Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.LineCommit Friend Class CommitTestData Implements IDisposable Public ReadOnly Buffer As ITextBuffer Public ReadOnly CommandHandler As CommitCommandHandler Public ReadOnly EditorOperations As IEditorOperations Public ReadOnly Workspace As TestWorkspace Public ReadOnly View As ITextView Public ReadOnly UndoHistory As ITextUndoHistory Private ReadOnly _formatter As FormatterMock Private ReadOnly _inlineRenameService As InlineRenameServiceMock Public Shared Function Create(test As XElement) As CommitTestData Dim workspace = TestWorkspace.Create(test, composition:=EditorTestCompositions.EditorFeaturesWpf) Return New CommitTestData(workspace) End Function Public Sub New(workspace As TestWorkspace) Me.Workspace = workspace View = workspace.Documents.Single().GetTextView() EditorOperations = workspace.GetService(Of IEditorOperationsFactoryService).GetEditorOperations(View) Dim position = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value View.Caret.MoveTo(New SnapshotPoint(View.TextSnapshot, position)) Buffer = workspace.Documents.Single().GetTextBuffer() ' HACK: We may have already created a CommitBufferManager for the buffer, so remove it If Buffer.Properties.ContainsProperty(GetType(CommitBufferManager)) Then Dim oldManager = Buffer.Properties.GetProperty(Of CommitBufferManager)(GetType(CommitBufferManager)) oldManager.RemoveReferencingView() Buffer.Properties.RemoveProperty(GetType(CommitBufferManager)) End If Dim textUndoHistoryRegistry = workspace.GetService(Of ITextUndoHistoryRegistry)() UndoHistory = textUndoHistoryRegistry.GetHistory(View.TextBuffer) _formatter = New FormatterMock(workspace) _inlineRenameService = New InlineRenameServiceMock() Dim commitManagerFactory As New CommitBufferManagerFactory(_formatter, _inlineRenameService, workspace.GetService(Of IThreadingContext)) ' Make sure the manager exists for the buffer Dim commitManager = commitManagerFactory.CreateForBuffer(Buffer) commitManager.AddReferencingView() CommandHandler = New CommitCommandHandler( commitManagerFactory, workspace.GetService(Of IEditorOperationsFactoryService), workspace.GetService(Of ISmartIndentationService), textUndoHistoryRegistry) End Sub Friend Sub AssertHadCommit(expectCommit As Boolean) Assert.Equal(expectCommit, _formatter.GotCommit) End Sub Friend Sub AssertUsedSemantics(expected As Boolean) Assert.Equal(expected, _formatter.UsedSemantics) End Sub Friend Sub StartInlineRenameSession() _inlineRenameService.HasSession = True End Sub Public Sub Dispose() Implements IDisposable.Dispose Workspace.Dispose() End Sub Private Class InlineRenameServiceMock Implements IInlineRenameService Public Property HasSession As Boolean Public ReadOnly Property ActiveSession As IInlineRenameSession Implements IInlineRenameService.ActiveSession Get Return If(HasSession, New MockInlineRenameSession(), Nothing) End Get End Property Public Function StartInlineSession(snapshot As Document, triggerSpan As TextSpan, Optional cancellationToken As CancellationToken = Nothing) As InlineRenameSessionInfo Implements IInlineRenameService.StartInlineSession Throw New NotImplementedException() End Function Private Class MockInlineRenameSession Implements IInlineRenameSession Public Sub Cancel() Implements IInlineRenameSession.Cancel Throw New NotImplementedException() End Sub Public Sub Commit(Optional previewChanges As Boolean = False) Implements IInlineRenameSession.Commit Throw New NotImplementedException() End Sub End Class End Class Private Class FormatterMock Implements ICommitFormatter Private ReadOnly _testWorkspace As TestWorkspace Public Property GotCommit As Boolean Public Property UsedSemantics As Boolean Public Sub New(testWorkspace As TestWorkspace) _testWorkspace = testWorkspace End Sub Public Sub CommitRegion(spanToFormat As SnapshotSpan, isExplicitFormat As Boolean, useSemantics As Boolean, dirtyRegion As SnapshotSpan, baseSnapshot As ITextSnapshot, baseTree As SyntaxTree, cancellationToken As CancellationToken) Implements ICommitFormatter.CommitRegion GotCommit = True UsedSemantics = useSemantics ' Assert the span if we have an assertion If _testWorkspace.Documents.Any(Function(d) d.SelectedSpans.Any()) Then Dim expectedSpan = _testWorkspace.Documents.Single(Function(d) d.SelectedSpans.Any()).SelectedSpans.Single() Dim trackingSpan = _testWorkspace.Documents.Single().InitialTextSnapshot.CreateTrackingSpan(expectedSpan.ToSpan(), SpanTrackingMode.EdgeInclusive) Assert.Equal(trackingSpan.GetSpan(spanToFormat.Snapshot), spanToFormat.Span) End If Dim realCommitFormatter = Assert.IsType(Of CommitFormatter)(_testWorkspace.GetService(Of ICommitFormatter)()) realCommitFormatter.CommitRegion(spanToFormat, isExplicitFormat, useSemantics, dirtyRegion, baseSnapshot, baseTree, cancellationToken) End Sub End Class End Class End Namespace
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Features/CSharp/Portable/ConvertForToForEach/CSharpConvertForToForEachCodeRefactoringProvider.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.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.ConvertForToForEach; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.CSharp.ConvertForToForEach { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertForToForEach), Shared] internal class CSharpConvertForToForEachCodeRefactoringProvider : AbstractConvertForToForEachCodeRefactoringProvider< StatementSyntax, ForStatementSyntax, ExpressionSyntax, MemberAccessExpressionSyntax, TypeSyntax, VariableDeclaratorSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpConvertForToForEachCodeRefactoringProvider() { } protected override string GetTitle() => CSharpFeaturesResources.Convert_to_foreach; protected override SyntaxList<StatementSyntax> GetBodyStatements(ForStatementSyntax forStatement) => forStatement.Statement is BlockSyntax block ? block.Statements : SyntaxFactory.SingletonList(forStatement.Statement); protected override bool TryGetForStatementComponents( ForStatementSyntax forStatement, out SyntaxToken iterationVariable, out ExpressionSyntax initializer, out MemberAccessExpressionSyntax memberAccess, out ExpressionSyntax stepValueExpressionOpt, CancellationToken cancellationToken) { // Look for very specific forms. Basically, only minor variations around: // for (var i = 0; i < expr.Lenth; i++) if (forStatement.Declaration != null && forStatement.Condition.IsKind(SyntaxKind.LessThanExpression) && forStatement.Incrementors.Count == 1) { var declaration = forStatement.Declaration; if (declaration.Variables.Count == 1) { var declarator = declaration.Variables[0]; if (declarator.Initializer != null) { iterationVariable = declarator.Identifier; initializer = declarator.Initializer.Value; var binaryExpression = (BinaryExpressionSyntax)forStatement.Condition; // Look for: i < expr.Length if (binaryExpression.Left is IdentifierNameSyntax identifierName && identifierName.Identifier.ValueText == iterationVariable.ValueText && binaryExpression.Right is MemberAccessExpressionSyntax) { memberAccess = (MemberAccessExpressionSyntax)binaryExpression.Right; var incrementor = forStatement.Incrementors[0]; return TryGetStepValue(iterationVariable, incrementor, out stepValueExpressionOpt); } } } } iterationVariable = default; memberAccess = null; initializer = null; stepValueExpressionOpt = null; return false; } private static bool TryGetStepValue( SyntaxToken iterationVariable, ExpressionSyntax incrementor, out ExpressionSyntax stepValue) { // support // x++ // ++x // x += constant_1 ExpressionSyntax operand; switch (incrementor.Kind()) { case SyntaxKind.PostIncrementExpression: operand = ((PostfixUnaryExpressionSyntax)incrementor).Operand; stepValue = null; break; case SyntaxKind.PreIncrementExpression: operand = ((PrefixUnaryExpressionSyntax)incrementor).Operand; stepValue = null; break; case SyntaxKind.AddAssignmentExpression: var assignment = (AssignmentExpressionSyntax)incrementor; operand = assignment.Left; stepValue = assignment.Right; break; default: stepValue = null; return false; } return operand is IdentifierNameSyntax identifierName && identifierName.Identifier.ValueText == iterationVariable.ValueText; } protected override SyntaxNode ConvertForNode( ForStatementSyntax forStatement, TypeSyntax typeNode, SyntaxToken foreachIdentifier, ExpressionSyntax collectionExpression, ITypeSymbol iterationVariableType, OptionSet optionSet) { typeNode ??= iterationVariableType.GenerateTypeSyntax(); return SyntaxFactory.ForEachStatement( SyntaxFactory.Token(SyntaxKind.ForEachKeyword).WithTriviaFrom(forStatement.ForKeyword), forStatement.OpenParenToken, typeNode, foreachIdentifier, SyntaxFactory.Token(SyntaxKind.InKeyword), collectionExpression, forStatement.CloseParenToken, forStatement.Statement); } // C# has no special variable declarator forms that would cause us to not be able to convert. protected override bool IsValidVariableDeclarator(VariableDeclaratorSyntax firstVariable) => 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.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.ConvertForToForEach; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.CSharp.ConvertForToForEach { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertForToForEach), Shared] internal class CSharpConvertForToForEachCodeRefactoringProvider : AbstractConvertForToForEachCodeRefactoringProvider< StatementSyntax, ForStatementSyntax, ExpressionSyntax, MemberAccessExpressionSyntax, TypeSyntax, VariableDeclaratorSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpConvertForToForEachCodeRefactoringProvider() { } protected override string GetTitle() => CSharpFeaturesResources.Convert_to_foreach; protected override SyntaxList<StatementSyntax> GetBodyStatements(ForStatementSyntax forStatement) => forStatement.Statement is BlockSyntax block ? block.Statements : SyntaxFactory.SingletonList(forStatement.Statement); protected override bool TryGetForStatementComponents( ForStatementSyntax forStatement, out SyntaxToken iterationVariable, out ExpressionSyntax initializer, out MemberAccessExpressionSyntax memberAccess, out ExpressionSyntax stepValueExpressionOpt, CancellationToken cancellationToken) { // Look for very specific forms. Basically, only minor variations around: // for (var i = 0; i < expr.Lenth; i++) if (forStatement.Declaration != null && forStatement.Condition.IsKind(SyntaxKind.LessThanExpression) && forStatement.Incrementors.Count == 1) { var declaration = forStatement.Declaration; if (declaration.Variables.Count == 1) { var declarator = declaration.Variables[0]; if (declarator.Initializer != null) { iterationVariable = declarator.Identifier; initializer = declarator.Initializer.Value; var binaryExpression = (BinaryExpressionSyntax)forStatement.Condition; // Look for: i < expr.Length if (binaryExpression.Left is IdentifierNameSyntax identifierName && identifierName.Identifier.ValueText == iterationVariable.ValueText && binaryExpression.Right is MemberAccessExpressionSyntax) { memberAccess = (MemberAccessExpressionSyntax)binaryExpression.Right; var incrementor = forStatement.Incrementors[0]; return TryGetStepValue(iterationVariable, incrementor, out stepValueExpressionOpt); } } } } iterationVariable = default; memberAccess = null; initializer = null; stepValueExpressionOpt = null; return false; } private static bool TryGetStepValue( SyntaxToken iterationVariable, ExpressionSyntax incrementor, out ExpressionSyntax stepValue) { // support // x++ // ++x // x += constant_1 ExpressionSyntax operand; switch (incrementor.Kind()) { case SyntaxKind.PostIncrementExpression: operand = ((PostfixUnaryExpressionSyntax)incrementor).Operand; stepValue = null; break; case SyntaxKind.PreIncrementExpression: operand = ((PrefixUnaryExpressionSyntax)incrementor).Operand; stepValue = null; break; case SyntaxKind.AddAssignmentExpression: var assignment = (AssignmentExpressionSyntax)incrementor; operand = assignment.Left; stepValue = assignment.Right; break; default: stepValue = null; return false; } return operand is IdentifierNameSyntax identifierName && identifierName.Identifier.ValueText == iterationVariable.ValueText; } protected override SyntaxNode ConvertForNode( ForStatementSyntax forStatement, TypeSyntax typeNode, SyntaxToken foreachIdentifier, ExpressionSyntax collectionExpression, ITypeSymbol iterationVariableType, OptionSet optionSet) { typeNode ??= iterationVariableType.GenerateTypeSyntax(); return SyntaxFactory.ForEachStatement( SyntaxFactory.Token(SyntaxKind.ForEachKeyword).WithTriviaFrom(forStatement.ForKeyword), forStatement.OpenParenToken, typeNode, foreachIdentifier, SyntaxFactory.Token(SyntaxKind.InKeyword), collectionExpression, forStatement.CloseParenToken, forStatement.Statement); } // C# has no special variable declarator forms that would cause us to not be able to convert. protected override bool IsValidVariableDeclarator(VariableDeclaratorSyntax firstVariable) => true; } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/EditorFeatures/Core/EditorConfigSettings/ISettingsEditorViewModel.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.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor { internal interface ISettingsEditorViewModel { void NotifyOfUpdate(); Task<SourceText> UpdateEditorConfigAsync(SourceText sourceText); } }
// Licensed to the .NET Foundation under one or more 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.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor { internal interface ISettingsEditorViewModel { void NotifyOfUpdate(); Task<SourceText> UpdateEditorConfigAsync(SourceText sourceText); } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioWorkspaceImpl.OpenFileTracker.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.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; using IAsyncServiceProvider = Microsoft.VisualStudio.Shell.IAsyncServiceProvider; using Task = System.Threading.Tasks.Task; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal partial class VisualStudioWorkspaceImpl { /// <summary> /// Singleton the subscribes to the running document table and connects/disconnects files to files that are opened. /// </summary> public sealed class OpenFileTracker : IRunningDocumentTableEventListener { private readonly ForegroundThreadAffinitizedObject _foregroundAffinitization; private readonly VisualStudioWorkspaceImpl _workspace; private readonly IAsynchronousOperationListener _asyncOperationListener; private readonly RunningDocumentTableEventTracker _runningDocumentTableEventTracker; #region Fields read/written to from multiple threads to track files that need to be checked /// <summary> /// A object to be used for a gate for modifications to <see cref="_fileNamesToCheckForOpenDocuments"/>, /// <see cref="_justEnumerateTheEntireRunningDocumentTable"/> and <see cref="_taskPending"/>. These are the only mutable fields /// in this class that are modified from multiple threads. /// </summary> private readonly object _gate = new(); private HashSet<string>? _fileNamesToCheckForOpenDocuments; /// <summary> /// Tracks whether we have decided to just scan the entire running document table for files that might already be in the workspace rather than checking /// each file one-by-one. This starts out at true, because we are created asynchronously, and files might have already been added to the workspace /// that we never got a call to <see cref="QueueCheckForFilesBeingOpen(ImmutableArray{string})"/> for. /// </summary> private bool _justEnumerateTheEntireRunningDocumentTable = true; private bool _taskPending; #endregion #region Fields read/and written to only on the UI thread to track active context for files private readonly ReferenceCountedDisposableCache<IVsHierarchy, HierarchyEventSink> _hierarchyEventSinkCache = new(); /// <summary> /// The IVsHierarchies we have subscribed to to watch for any changes to this moniker. We track this per moniker, so /// when a document is closed we know what we have to incrementally unsubscribe from rather than having to unsubscribe from everything. /// </summary> private readonly MultiDictionary<string, IReferenceCountedDisposable<ICacheEntry<IVsHierarchy, HierarchyEventSink>>> _watchedHierarchiesForDocumentMoniker = new(); #endregion /// <summary> /// A cutoff to use when we should stop checking the RDT for individual documents and just rescan all open documents. /// </summary> /// <remarks>If a single document is added to a project, we need to check if it's already open. We can easily do /// that by calling <see cref="IVsRunningDocumentTable4.GetDocumentCookie(string)"/> and going from there. That's fine /// for a few documents, but is not wise during solution load when you have potentially thousands of files. In that /// case, we can just enumerate all open files and check if we know about them, on the assumption the number of /// open files is far less than the number of total files. /// /// This cutoff of 10 was chosen arbitrarily and with no evidence whatsoever.</remarks> private const int CutoffForCheckingAllRunningDocumentTableDocuments = 10; private OpenFileTracker(VisualStudioWorkspaceImpl workspace, IVsRunningDocumentTable runningDocumentTable, IComponentModel componentModel) { _workspace = workspace; _foregroundAffinitization = new ForegroundThreadAffinitizedObject(workspace._threadingContext, assertIsForeground: true); _asyncOperationListener = componentModel.GetService<IAsynchronousOperationListenerProvider>().GetListener(FeatureAttribute.Workspace); _runningDocumentTableEventTracker = new RunningDocumentTableEventTracker(workspace._threadingContext, componentModel.GetService<IVsEditorAdaptersFactoryService>(), runningDocumentTable, this); } void IRunningDocumentTableEventListener.OnOpenDocument(string moniker, ITextBuffer textBuffer, IVsHierarchy? hierarchy, IVsWindowFrame? _) => TryOpeningDocumentsForMoniker(moniker, textBuffer, hierarchy); void IRunningDocumentTableEventListener.OnCloseDocument(string moniker) => TryClosingDocumentsForMoniker(moniker); void IRunningDocumentTableEventListener.OnRefreshDocumentContext(string moniker, IVsHierarchy hierarchy) => RefreshContextForMoniker(moniker, hierarchy); /// <summary> /// When a file is renamed, the old document is removed and a new document is added by the workspace. /// </summary> void IRunningDocumentTableEventListener.OnRenameDocument(string newMoniker, string oldMoniker, ITextBuffer buffer) { } public static async Task<OpenFileTracker> CreateAsync(VisualStudioWorkspaceImpl workspace, IAsyncServiceProvider asyncServiceProvider) { var runningDocumentTable = (IVsRunningDocumentTable?)await asyncServiceProvider.GetServiceAsync(typeof(SVsRunningDocumentTable)).ConfigureAwait(true); Assumes.Present(runningDocumentTable); var componentModel = (IComponentModel?)await asyncServiceProvider.GetServiceAsync(typeof(SComponentModel)).ConfigureAwait(true); Assumes.Present(componentModel); return new OpenFileTracker(workspace, runningDocumentTable, componentModel); } private void TryOpeningDocumentsForMoniker(string moniker, ITextBuffer textBuffer, IVsHierarchy? hierarchy) { _foregroundAffinitization.AssertIsForeground(); _workspace.ApplyChangeToWorkspace(w => { var documentIds = _workspace.CurrentSolution.GetDocumentIdsWithFilePath(moniker); if (documentIds.IsDefaultOrEmpty) { return; } if (documentIds.All(w.IsDocumentOpen)) { return; } ProjectId activeContextProjectId; if (documentIds.Length == 1) { activeContextProjectId = documentIds.Single().ProjectId; } else { activeContextProjectId = GetActiveContextProjectIdAndWatchHierarchies(moniker, documentIds.Select(d => d.ProjectId), hierarchy); } var textContainer = textBuffer.AsTextContainer(); foreach (var documentId in documentIds) { if (!w.IsDocumentOpen(documentId) && !_workspace._documentsNotFromFiles.Contains(documentId)) { var isCurrentContext = documentId.ProjectId == activeContextProjectId; if (w.CurrentSolution.ContainsDocument(documentId)) { w.OnDocumentOpened(documentId, textContainer, isCurrentContext); } else if (w.CurrentSolution.ContainsAdditionalDocument(documentId)) { w.OnAdditionalDocumentOpened(documentId, textContainer, isCurrentContext); } else { Debug.Assert(w.CurrentSolution.ContainsAnalyzerConfigDocument(documentId)); w.OnAnalyzerConfigDocumentOpened(documentId, textContainer, isCurrentContext); } } } }); } private ProjectId GetActiveContextProjectIdAndWatchHierarchies(string moniker, IEnumerable<ProjectId> projectIds, IVsHierarchy? hierarchy) { _foregroundAffinitization.AssertIsForeground(); // First clear off any existing IVsHierarchies we are watching. Any ones that still matter we will resubscribe to. // We could be fancy and diff, but the cost is probably negligible. UnsubscribeFromWatchedHierarchies(moniker); if (hierarchy == null) { // Any item in the RDT should have a hierarchy associated; in this case we don't so there's absolutely nothing // we can do at this point. return projectIds.First(); } void WatchHierarchy(IVsHierarchy hierarchyToWatch) { _watchedHierarchiesForDocumentMoniker.Add(moniker, _hierarchyEventSinkCache.GetOrCreate(hierarchyToWatch, static (h, self) => new HierarchyEventSink(h, self), this)); } // Take a snapshot of the immutable data structure here to avoid mutation underneath us var projectToHierarchyMap = _workspace._projectToHierarchyMap; var solution = _workspace.CurrentSolution; // We now must chase to the actual hierarchy that we know about. First, we'll chase through multiple shared asset projects if // we need to do so. while (true) { var contextHierarchy = hierarchy.GetActiveProjectContext(); // The check for if contextHierarchy == hierarchy is working around downstream impacts of https://devdiv.visualstudio.com/DevDiv/_git/CPS/pullrequest/158271 // Since that bug means shared projects have themselves as their own owner, it sometimes results in us corrupting state where we end up // having the context of shared project be itself, it seems. if (contextHierarchy == null || contextHierarchy == hierarchy) { break; } WatchHierarchy(hierarchy); hierarchy = contextHierarchy; } // We may have multiple projects with the same hierarchy, but we can use __VSHPROPID8.VSHPROPID_ActiveIntellisenseProjectContext to distinguish if (ErrorHandler.Succeeded(hierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID8.VSHPROPID_ActiveIntellisenseProjectContext, out var contextProjectNameObject))) { WatchHierarchy(hierarchy); if (contextProjectNameObject is string contextProjectName) { var project = _workspace.GetProjectWithHierarchyAndName(hierarchy, contextProjectName); if (project != null && projectIds.Contains(project.Id)) { return project.Id; } } } // At this point, we should hopefully have only one project that maches by hierarchy. If there's multiple, at this point we can't figure anything // out better. var matchingProjectId = projectIds.FirstOrDefault(id => projectToHierarchyMap.GetValueOrDefault(id, null) == hierarchy); if (matchingProjectId != null) { return matchingProjectId; } // If we had some trouble finding the project, we'll just pick one arbitrarily return projectIds.First(); } private void UnsubscribeFromWatchedHierarchies(string moniker) { _foregroundAffinitization.AssertIsForeground(); foreach (var watchedHierarchy in _watchedHierarchiesForDocumentMoniker[moniker]) { watchedHierarchy.Dispose(); } _watchedHierarchiesForDocumentMoniker.Remove(moniker); } private void RefreshContextForMoniker(string moniker, IVsHierarchy hierarchy) { _foregroundAffinitization.AssertIsForeground(); _workspace.ApplyChangeToWorkspace(w => { var documentIds = _workspace.CurrentSolution.GetDocumentIdsWithFilePath(moniker); if (documentIds.IsDefaultOrEmpty || documentIds.Length == 1) { return; } if (!documentIds.All(w.IsDocumentOpen)) { return; } var activeProjectId = GetActiveContextProjectIdAndWatchHierarchies(moniker, documentIds.Select(d => d.ProjectId), hierarchy); w.OnDocumentContextUpdated(documentIds.First(d => d.ProjectId == activeProjectId)); }); } private void RefreshContextsForHierarchyPropertyChange(IVsHierarchy hierarchy) { _foregroundAffinitization.AssertIsForeground(); // We're going to go through each file that has subscriptions, and update them appropriately. // We have to clone this since we will be modifying it under the covers. foreach (var moniker in _watchedHierarchiesForDocumentMoniker.Keys.ToList()) { foreach (var subscribedHierarchy in _watchedHierarchiesForDocumentMoniker[moniker]) { if (subscribedHierarchy.Target.Key == hierarchy) { RefreshContextForMoniker(moniker, hierarchy); } } } } private void TryClosingDocumentsForMoniker(string moniker) { _foregroundAffinitization.AssertIsForeground(); UnsubscribeFromWatchedHierarchies(moniker); _workspace.ApplyChangeToWorkspace(w => { var documentIds = w.CurrentSolution.GetDocumentIdsWithFilePath(moniker); if (documentIds.IsDefaultOrEmpty) { return; } foreach (var documentId in documentIds) { if (w.IsDocumentOpen(documentId) && !_workspace._documentsNotFromFiles.Contains(documentId)) { if (w.CurrentSolution.ContainsDocument(documentId)) { w.OnDocumentClosed(documentId, new FileTextLoader(moniker, defaultEncoding: null)); } else if (w.CurrentSolution.ContainsAdditionalDocument(documentId)) { w.OnAdditionalDocumentClosed(documentId, new FileTextLoader(moniker, defaultEncoding: null)); } else { Debug.Assert(w.CurrentSolution.ContainsAnalyzerConfigDocument(documentId)); w.OnAnalyzerConfigDocumentClosed(documentId, new FileTextLoader(moniker, defaultEncoding: null)); } } } }); } /// <summary> /// Queues a new task to check for files being open for these file names. /// </summary> public void QueueCheckForFilesBeingOpen(ImmutableArray<string> newFileNames) { ForegroundThreadAffinitizedObject.ThisCanBeCalledOnAnyThread(); var shouldStartTask = false; lock (_gate) { // If we've already decided to enumerate the full table, nothing further to do. if (!_justEnumerateTheEntireRunningDocumentTable) { // If this is going to push us over our threshold for scanning the entire table then just give up if ((_fileNamesToCheckForOpenDocuments?.Count ?? 0) + newFileNames.Length > CutoffForCheckingAllRunningDocumentTableDocuments) { _fileNamesToCheckForOpenDocuments = null; _justEnumerateTheEntireRunningDocumentTable = true; } else { if (_fileNamesToCheckForOpenDocuments == null) { _fileNamesToCheckForOpenDocuments = new HashSet<string>(newFileNames); } else { foreach (var filename in newFileNames) { _fileNamesToCheckForOpenDocuments.Add(filename); } } } } if (!_taskPending) { _taskPending = true; shouldStartTask = true; } } if (shouldStartTask) { var asyncToken = _asyncOperationListener.BeginAsyncOperation(nameof(QueueCheckForFilesBeingOpen)); Task.Run(async () => { await _foregroundAffinitization.ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(); ProcessQueuedWorkOnUIThread(); }).CompletesAsyncOperation(asyncToken); } } public void ProcessQueuedWorkOnUIThread() { _foregroundAffinitization.AssertIsForeground(); // Just pulling off the values from the shared state to the local function. HashSet<string>? fileNamesToCheckForOpenDocuments; bool justEnumerateTheEntireRunningDocumentTable; lock (_gate) { fileNamesToCheckForOpenDocuments = _fileNamesToCheckForOpenDocuments; justEnumerateTheEntireRunningDocumentTable = _justEnumerateTheEntireRunningDocumentTable; _fileNamesToCheckForOpenDocuments = null; _justEnumerateTheEntireRunningDocumentTable = false; _taskPending = false; } if (justEnumerateTheEntireRunningDocumentTable) { var documents = _runningDocumentTableEventTracker.EnumerateDocumentSet(); foreach (var (moniker, textBuffer, hierarchy) in documents) { TryOpeningDocumentsForMoniker(moniker, textBuffer, hierarchy); } } else if (fileNamesToCheckForOpenDocuments != null) { foreach (var fileName in fileNamesToCheckForOpenDocuments) { if (_runningDocumentTableEventTracker.IsFileOpen(fileName) && _runningDocumentTableEventTracker.TryGetBufferFromMoniker(fileName, out var buffer)) { var hierarchy = _runningDocumentTableEventTracker.GetDocumentHierarchy(fileName); TryOpeningDocumentsForMoniker(fileName, buffer, hierarchy); } } } } private class HierarchyEventSink : IVsHierarchyEvents, IDisposable { private readonly IVsHierarchy _hierarchy; private readonly uint _cookie; private readonly OpenFileTracker _openFileTracker; public HierarchyEventSink(IVsHierarchy hierarchy, OpenFileTracker openFileTracker) { _hierarchy = hierarchy; _openFileTracker = openFileTracker; ErrorHandler.ThrowOnFailure(_hierarchy.AdviseHierarchyEvents(this, out _cookie)); } void IDisposable.Dispose() => _hierarchy.UnadviseHierarchyEvents(_cookie); int IVsHierarchyEvents.OnItemAdded(uint itemidParent, uint itemidSiblingPrev, uint itemidAdded) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnItemsAppended(uint itemidParent) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnItemDeleted(uint itemid) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnPropertyChanged(uint itemid, int propid, uint flags) { if (propid == (int)__VSHPROPID7.VSHPROPID_SharedItemContextHierarchy || propid == (int)__VSHPROPID8.VSHPROPID_ActiveIntellisenseProjectContext) { _openFileTracker.RefreshContextsForHierarchyPropertyChange(_hierarchy); } return VSConstants.S_OK; } int IVsHierarchyEvents.OnInvalidateItems(uint itemidParent) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnInvalidateIcon(IntPtr hicon) => VSConstants.E_NOTIMPL; } } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; using IAsyncServiceProvider = Microsoft.VisualStudio.Shell.IAsyncServiceProvider; using Task = System.Threading.Tasks.Task; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal partial class VisualStudioWorkspaceImpl { /// <summary> /// Singleton the subscribes to the running document table and connects/disconnects files to files that are opened. /// </summary> public sealed class OpenFileTracker : IRunningDocumentTableEventListener { private readonly ForegroundThreadAffinitizedObject _foregroundAffinitization; private readonly VisualStudioWorkspaceImpl _workspace; private readonly IAsynchronousOperationListener _asyncOperationListener; private readonly RunningDocumentTableEventTracker _runningDocumentTableEventTracker; #region Fields read/written to from multiple threads to track files that need to be checked /// <summary> /// A object to be used for a gate for modifications to <see cref="_fileNamesToCheckForOpenDocuments"/>, /// <see cref="_justEnumerateTheEntireRunningDocumentTable"/> and <see cref="_taskPending"/>. These are the only mutable fields /// in this class that are modified from multiple threads. /// </summary> private readonly object _gate = new(); private HashSet<string>? _fileNamesToCheckForOpenDocuments; /// <summary> /// Tracks whether we have decided to just scan the entire running document table for files that might already be in the workspace rather than checking /// each file one-by-one. This starts out at true, because we are created asynchronously, and files might have already been added to the workspace /// that we never got a call to <see cref="QueueCheckForFilesBeingOpen(ImmutableArray{string})"/> for. /// </summary> private bool _justEnumerateTheEntireRunningDocumentTable = true; private bool _taskPending; #endregion #region Fields read/and written to only on the UI thread to track active context for files private readonly ReferenceCountedDisposableCache<IVsHierarchy, HierarchyEventSink> _hierarchyEventSinkCache = new(); /// <summary> /// The IVsHierarchies we have subscribed to to watch for any changes to this moniker. We track this per moniker, so /// when a document is closed we know what we have to incrementally unsubscribe from rather than having to unsubscribe from everything. /// </summary> private readonly MultiDictionary<string, IReferenceCountedDisposable<ICacheEntry<IVsHierarchy, HierarchyEventSink>>> _watchedHierarchiesForDocumentMoniker = new(); #endregion /// <summary> /// A cutoff to use when we should stop checking the RDT for individual documents and just rescan all open documents. /// </summary> /// <remarks>If a single document is added to a project, we need to check if it's already open. We can easily do /// that by calling <see cref="IVsRunningDocumentTable4.GetDocumentCookie(string)"/> and going from there. That's fine /// for a few documents, but is not wise during solution load when you have potentially thousands of files. In that /// case, we can just enumerate all open files and check if we know about them, on the assumption the number of /// open files is far less than the number of total files. /// /// This cutoff of 10 was chosen arbitrarily and with no evidence whatsoever.</remarks> private const int CutoffForCheckingAllRunningDocumentTableDocuments = 10; private OpenFileTracker(VisualStudioWorkspaceImpl workspace, IVsRunningDocumentTable runningDocumentTable, IComponentModel componentModel) { _workspace = workspace; _foregroundAffinitization = new ForegroundThreadAffinitizedObject(workspace._threadingContext, assertIsForeground: true); _asyncOperationListener = componentModel.GetService<IAsynchronousOperationListenerProvider>().GetListener(FeatureAttribute.Workspace); _runningDocumentTableEventTracker = new RunningDocumentTableEventTracker(workspace._threadingContext, componentModel.GetService<IVsEditorAdaptersFactoryService>(), runningDocumentTable, this); } void IRunningDocumentTableEventListener.OnOpenDocument(string moniker, ITextBuffer textBuffer, IVsHierarchy? hierarchy, IVsWindowFrame? _) => TryOpeningDocumentsForMoniker(moniker, textBuffer, hierarchy); void IRunningDocumentTableEventListener.OnCloseDocument(string moniker) => TryClosingDocumentsForMoniker(moniker); void IRunningDocumentTableEventListener.OnRefreshDocumentContext(string moniker, IVsHierarchy hierarchy) => RefreshContextForMoniker(moniker, hierarchy); /// <summary> /// When a file is renamed, the old document is removed and a new document is added by the workspace. /// </summary> void IRunningDocumentTableEventListener.OnRenameDocument(string newMoniker, string oldMoniker, ITextBuffer buffer) { } public static async Task<OpenFileTracker> CreateAsync(VisualStudioWorkspaceImpl workspace, IAsyncServiceProvider asyncServiceProvider) { var runningDocumentTable = (IVsRunningDocumentTable?)await asyncServiceProvider.GetServiceAsync(typeof(SVsRunningDocumentTable)).ConfigureAwait(true); Assumes.Present(runningDocumentTable); var componentModel = (IComponentModel?)await asyncServiceProvider.GetServiceAsync(typeof(SComponentModel)).ConfigureAwait(true); Assumes.Present(componentModel); return new OpenFileTracker(workspace, runningDocumentTable, componentModel); } private void TryOpeningDocumentsForMoniker(string moniker, ITextBuffer textBuffer, IVsHierarchy? hierarchy) { _foregroundAffinitization.AssertIsForeground(); _workspace.ApplyChangeToWorkspace(w => { var documentIds = _workspace.CurrentSolution.GetDocumentIdsWithFilePath(moniker); if (documentIds.IsDefaultOrEmpty) { return; } if (documentIds.All(w.IsDocumentOpen)) { return; } ProjectId activeContextProjectId; if (documentIds.Length == 1) { activeContextProjectId = documentIds.Single().ProjectId; } else { activeContextProjectId = GetActiveContextProjectIdAndWatchHierarchies(moniker, documentIds.Select(d => d.ProjectId), hierarchy); } var textContainer = textBuffer.AsTextContainer(); foreach (var documentId in documentIds) { if (!w.IsDocumentOpen(documentId) && !_workspace._documentsNotFromFiles.Contains(documentId)) { var isCurrentContext = documentId.ProjectId == activeContextProjectId; if (w.CurrentSolution.ContainsDocument(documentId)) { w.OnDocumentOpened(documentId, textContainer, isCurrentContext); } else if (w.CurrentSolution.ContainsAdditionalDocument(documentId)) { w.OnAdditionalDocumentOpened(documentId, textContainer, isCurrentContext); } else { Debug.Assert(w.CurrentSolution.ContainsAnalyzerConfigDocument(documentId)); w.OnAnalyzerConfigDocumentOpened(documentId, textContainer, isCurrentContext); } } } }); } private ProjectId GetActiveContextProjectIdAndWatchHierarchies(string moniker, IEnumerable<ProjectId> projectIds, IVsHierarchy? hierarchy) { _foregroundAffinitization.AssertIsForeground(); // First clear off any existing IVsHierarchies we are watching. Any ones that still matter we will resubscribe to. // We could be fancy and diff, but the cost is probably negligible. UnsubscribeFromWatchedHierarchies(moniker); if (hierarchy == null) { // Any item in the RDT should have a hierarchy associated; in this case we don't so there's absolutely nothing // we can do at this point. return projectIds.First(); } void WatchHierarchy(IVsHierarchy hierarchyToWatch) { _watchedHierarchiesForDocumentMoniker.Add(moniker, _hierarchyEventSinkCache.GetOrCreate(hierarchyToWatch, static (h, self) => new HierarchyEventSink(h, self), this)); } // Take a snapshot of the immutable data structure here to avoid mutation underneath us var projectToHierarchyMap = _workspace._projectToHierarchyMap; var solution = _workspace.CurrentSolution; // We now must chase to the actual hierarchy that we know about. First, we'll chase through multiple shared asset projects if // we need to do so. while (true) { var contextHierarchy = hierarchy.GetActiveProjectContext(); // The check for if contextHierarchy == hierarchy is working around downstream impacts of https://devdiv.visualstudio.com/DevDiv/_git/CPS/pullrequest/158271 // Since that bug means shared projects have themselves as their own owner, it sometimes results in us corrupting state where we end up // having the context of shared project be itself, it seems. if (contextHierarchy == null || contextHierarchy == hierarchy) { break; } WatchHierarchy(hierarchy); hierarchy = contextHierarchy; } // We may have multiple projects with the same hierarchy, but we can use __VSHPROPID8.VSHPROPID_ActiveIntellisenseProjectContext to distinguish if (ErrorHandler.Succeeded(hierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID8.VSHPROPID_ActiveIntellisenseProjectContext, out var contextProjectNameObject))) { WatchHierarchy(hierarchy); if (contextProjectNameObject is string contextProjectName) { var project = _workspace.GetProjectWithHierarchyAndName(hierarchy, contextProjectName); if (project != null && projectIds.Contains(project.Id)) { return project.Id; } } } // At this point, we should hopefully have only one project that maches by hierarchy. If there's multiple, at this point we can't figure anything // out better. var matchingProjectId = projectIds.FirstOrDefault(id => projectToHierarchyMap.GetValueOrDefault(id, null) == hierarchy); if (matchingProjectId != null) { return matchingProjectId; } // If we had some trouble finding the project, we'll just pick one arbitrarily return projectIds.First(); } private void UnsubscribeFromWatchedHierarchies(string moniker) { _foregroundAffinitization.AssertIsForeground(); foreach (var watchedHierarchy in _watchedHierarchiesForDocumentMoniker[moniker]) { watchedHierarchy.Dispose(); } _watchedHierarchiesForDocumentMoniker.Remove(moniker); } private void RefreshContextForMoniker(string moniker, IVsHierarchy hierarchy) { _foregroundAffinitization.AssertIsForeground(); _workspace.ApplyChangeToWorkspace(w => { var documentIds = _workspace.CurrentSolution.GetDocumentIdsWithFilePath(moniker); if (documentIds.IsDefaultOrEmpty || documentIds.Length == 1) { return; } if (!documentIds.All(w.IsDocumentOpen)) { return; } var activeProjectId = GetActiveContextProjectIdAndWatchHierarchies(moniker, documentIds.Select(d => d.ProjectId), hierarchy); w.OnDocumentContextUpdated(documentIds.First(d => d.ProjectId == activeProjectId)); }); } private void RefreshContextsForHierarchyPropertyChange(IVsHierarchy hierarchy) { _foregroundAffinitization.AssertIsForeground(); // We're going to go through each file that has subscriptions, and update them appropriately. // We have to clone this since we will be modifying it under the covers. foreach (var moniker in _watchedHierarchiesForDocumentMoniker.Keys.ToList()) { foreach (var subscribedHierarchy in _watchedHierarchiesForDocumentMoniker[moniker]) { if (subscribedHierarchy.Target.Key == hierarchy) { RefreshContextForMoniker(moniker, hierarchy); } } } } private void TryClosingDocumentsForMoniker(string moniker) { _foregroundAffinitization.AssertIsForeground(); UnsubscribeFromWatchedHierarchies(moniker); _workspace.ApplyChangeToWorkspace(w => { var documentIds = w.CurrentSolution.GetDocumentIdsWithFilePath(moniker); if (documentIds.IsDefaultOrEmpty) { return; } foreach (var documentId in documentIds) { if (w.IsDocumentOpen(documentId) && !_workspace._documentsNotFromFiles.Contains(documentId)) { if (w.CurrentSolution.ContainsDocument(documentId)) { w.OnDocumentClosed(documentId, new FileTextLoader(moniker, defaultEncoding: null)); } else if (w.CurrentSolution.ContainsAdditionalDocument(documentId)) { w.OnAdditionalDocumentClosed(documentId, new FileTextLoader(moniker, defaultEncoding: null)); } else { Debug.Assert(w.CurrentSolution.ContainsAnalyzerConfigDocument(documentId)); w.OnAnalyzerConfigDocumentClosed(documentId, new FileTextLoader(moniker, defaultEncoding: null)); } } } }); } /// <summary> /// Queues a new task to check for files being open for these file names. /// </summary> public void QueueCheckForFilesBeingOpen(ImmutableArray<string> newFileNames) { ForegroundThreadAffinitizedObject.ThisCanBeCalledOnAnyThread(); var shouldStartTask = false; lock (_gate) { // If we've already decided to enumerate the full table, nothing further to do. if (!_justEnumerateTheEntireRunningDocumentTable) { // If this is going to push us over our threshold for scanning the entire table then just give up if ((_fileNamesToCheckForOpenDocuments?.Count ?? 0) + newFileNames.Length > CutoffForCheckingAllRunningDocumentTableDocuments) { _fileNamesToCheckForOpenDocuments = null; _justEnumerateTheEntireRunningDocumentTable = true; } else { if (_fileNamesToCheckForOpenDocuments == null) { _fileNamesToCheckForOpenDocuments = new HashSet<string>(newFileNames); } else { foreach (var filename in newFileNames) { _fileNamesToCheckForOpenDocuments.Add(filename); } } } } if (!_taskPending) { _taskPending = true; shouldStartTask = true; } } if (shouldStartTask) { var asyncToken = _asyncOperationListener.BeginAsyncOperation(nameof(QueueCheckForFilesBeingOpen)); Task.Run(async () => { await _foregroundAffinitization.ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(); ProcessQueuedWorkOnUIThread(); }).CompletesAsyncOperation(asyncToken); } } public void ProcessQueuedWorkOnUIThread() { _foregroundAffinitization.AssertIsForeground(); // Just pulling off the values from the shared state to the local function. HashSet<string>? fileNamesToCheckForOpenDocuments; bool justEnumerateTheEntireRunningDocumentTable; lock (_gate) { fileNamesToCheckForOpenDocuments = _fileNamesToCheckForOpenDocuments; justEnumerateTheEntireRunningDocumentTable = _justEnumerateTheEntireRunningDocumentTable; _fileNamesToCheckForOpenDocuments = null; _justEnumerateTheEntireRunningDocumentTable = false; _taskPending = false; } if (justEnumerateTheEntireRunningDocumentTable) { var documents = _runningDocumentTableEventTracker.EnumerateDocumentSet(); foreach (var (moniker, textBuffer, hierarchy) in documents) { TryOpeningDocumentsForMoniker(moniker, textBuffer, hierarchy); } } else if (fileNamesToCheckForOpenDocuments != null) { foreach (var fileName in fileNamesToCheckForOpenDocuments) { if (_runningDocumentTableEventTracker.IsFileOpen(fileName) && _runningDocumentTableEventTracker.TryGetBufferFromMoniker(fileName, out var buffer)) { var hierarchy = _runningDocumentTableEventTracker.GetDocumentHierarchy(fileName); TryOpeningDocumentsForMoniker(fileName, buffer, hierarchy); } } } } private class HierarchyEventSink : IVsHierarchyEvents, IDisposable { private readonly IVsHierarchy _hierarchy; private readonly uint _cookie; private readonly OpenFileTracker _openFileTracker; public HierarchyEventSink(IVsHierarchy hierarchy, OpenFileTracker openFileTracker) { _hierarchy = hierarchy; _openFileTracker = openFileTracker; ErrorHandler.ThrowOnFailure(_hierarchy.AdviseHierarchyEvents(this, out _cookie)); } void IDisposable.Dispose() => _hierarchy.UnadviseHierarchyEvents(_cookie); int IVsHierarchyEvents.OnItemAdded(uint itemidParent, uint itemidSiblingPrev, uint itemidAdded) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnItemsAppended(uint itemidParent) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnItemDeleted(uint itemid) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnPropertyChanged(uint itemid, int propid, uint flags) { if (propid == (int)__VSHPROPID7.VSHPROPID_SharedItemContextHierarchy || propid == (int)__VSHPROPID8.VSHPROPID_ActiveIntellisenseProjectContext) { _openFileTracker.RefreshContextsForHierarchyPropertyChange(_hierarchy); } return VSConstants.S_OK; } int IVsHierarchyEvents.OnInvalidateItems(uint itemidParent) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnInvalidateIcon(IntPtr hicon) => VSConstants.E_NOTIMPL; } } } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/ExpressionEvaluator/CSharp/Test/ResultProvider/TypeNameFormatterTests.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.Collections.ObjectModel; using Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class TypeNameFormatterTests : CSharpResultProviderTestBase { [Fact] public void Primitives() { Assert.Equal("object", typeof(object).GetTypeName()); Assert.Equal("bool", typeof(bool).GetTypeName()); Assert.Equal("char", typeof(char).GetTypeName()); Assert.Equal("sbyte", typeof(sbyte).GetTypeName()); Assert.Equal("byte", typeof(byte).GetTypeName()); Assert.Equal("short", typeof(short).GetTypeName()); Assert.Equal("ushort", typeof(ushort).GetTypeName()); Assert.Equal("int", typeof(int).GetTypeName()); Assert.Equal("uint", typeof(uint).GetTypeName()); Assert.Equal("long", typeof(long).GetTypeName()); Assert.Equal("ulong", typeof(ulong).GetTypeName()); Assert.Equal("float", typeof(float).GetTypeName()); Assert.Equal("double", typeof(double).GetTypeName()); Assert.Equal("decimal", typeof(decimal).GetTypeName()); Assert.Equal("string", typeof(string).GetTypeName()); } [Fact, WorkItem(1016796, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1016796")] public void NestedTypes() { var source = @" public class A { public class B { } } namespace N { public class A { public class B { } } public class G1<T> { public class G2<T> { public class G3<U> { } class G4<U, V> { } } } } "; var assembly = GetAssembly(source); Assert.Equal("A", assembly.GetType("A").GetTypeName()); Assert.Equal("A.B", assembly.GetType("A+B").GetTypeName()); Assert.Equal("N.A", assembly.GetType("N.A").GetTypeName()); Assert.Equal("N.A.B", assembly.GetType("N.A+B").GetTypeName()); Assert.Equal("N.G1<int>.G2<float>.G3<double>", assembly.GetType("N.G1`1+G2`1+G3`1").MakeGenericType(typeof(int), typeof(float), typeof(double)).GetTypeName()); Assert.Equal("N.G1<int>.G2<float>.G4<double, ushort>", assembly.GetType("N.G1`1+G2`1+G4`2").MakeGenericType(typeof(int), typeof(float), typeof(double), typeof(ushort)).GetTypeName()); } [Fact] public void GenericTypes() { var source = @" public class A { public class B { } } namespace N { public class C<T, U> { public class D<V, W> { } } } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("A"); var typeB = typeA.GetNestedType("B"); var typeC = assembly.GetType("N.C`2"); var typeD = typeC.GetNestedType("D`2"); var typeInt = typeof(int); var typeString = typeof(string); var typeCIntString = typeC.MakeGenericType(typeInt, typeString); Assert.Equal("N.C<T, U>", typeC.GetTypeName()); Assert.Equal("N.C<int, string>", typeCIntString.GetTypeName()); Assert.Equal("N.C<A, A.B>", typeC.MakeGenericType(typeA, typeB).GetTypeName()); Assert.Equal("N.C<int, string>.D<A, A.B>", typeD.MakeGenericType(typeInt, typeString, typeA, typeB).GetTypeName()); Assert.Equal("N.C<A, N.C<int, string>>.D<N.C<int, string>, A.B>", typeD.MakeGenericType(typeA, typeCIntString, typeCIntString, typeB).GetTypeName()); } [Fact] public void NonGenericInGeneric() { var source = @" public class A<T> { public class B { } } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("A`1"); var typeB = typeA.GetNestedType("B"); Assert.Equal("A<int>.B", typeB.MakeGenericType(typeof(int)).GetTypeName()); } [Fact] public void PrimitiveNullableTypes() { Assert.Equal("int?", typeof(int?).GetTypeName()); Assert.Equal("bool?", typeof(bool?).GetTypeName()); } [Fact] public void NullableTypes() { var source = @" namespace N { public struct A<T> { public struct B<U> { } } public struct C { } } "; var typeNullable = typeof(System.Nullable<>); var assembly = GetAssembly(source); var typeA = assembly.GetType("N.A`1"); var typeB = typeA.GetNestedType("B`1"); var typeC = assembly.GetType("N.C"); Assert.Equal("N.C?", typeNullable.MakeGenericType(typeC).GetTypeName()); Assert.Equal("N.A<N.C>?", typeNullable.MakeGenericType(typeA.MakeGenericType(typeC)).GetTypeName()); Assert.Equal("N.A<N.C>.B<N.C>?", typeNullable.MakeGenericType(typeB.MakeGenericType(typeC, typeC)).GetTypeName()); } [Fact] public void PrimitiveArrayTypes() { Assert.Equal("int[]", typeof(int[]).GetTypeName()); Assert.Equal("int[,]", typeof(int[,]).GetTypeName()); Assert.Equal("int[][,]", typeof(int[][,]).GetTypeName()); Assert.Equal("int[,][]", typeof(int[,][]).GetTypeName()); } [Fact] public void ArrayTypes() { var source = @" namespace N { public class A<T> { public class B<U> { } } public class C { } } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("N.A`1"); var typeB = typeA.GetNestedType("B`1"); var typeC = assembly.GetType("N.C"); Assert.NotEqual(typeC.MakeArrayType(), typeC.MakeArrayType(1)); Assert.Equal("N.C[]", typeC.MakeArrayType().GetTypeName()); Assert.Equal("N.C[]", typeC.MakeArrayType(1).GetTypeName()); // NOTE: Multi-dimensional array that happens to exactly one dimension. Assert.Equal("N.A<N.C>[,]", typeA.MakeGenericType(typeC).MakeArrayType(2).GetTypeName()); Assert.Equal("N.A<N.C[]>.B<N.C>[,,]", typeB.MakeGenericType(typeC.MakeArrayType(), typeC).MakeArrayType(3).GetTypeName()); } [Fact] public void CustomBoundsArrayTypes() { Array instance = Array.CreateInstance(typeof(int), new[] { 1, 2, 3, }, new[] { 4, 5, 6, }); Assert.Equal("int[,,]", instance.GetType().GetTypeName()); Assert.Equal("int[][,,]", instance.GetType().MakeArrayType().GetTypeName()); } [Fact] public void PrimitivePointerTypes() { Assert.Equal("int*", typeof(int).MakePointerType().GetTypeName()); Assert.Equal("int**", typeof(int).MakePointerType().MakePointerType().GetTypeName()); Assert.Equal("int*[]", typeof(int).MakePointerType().MakeArrayType().GetTypeName()); } [Fact] public void PointerTypes() { var source = @" namespace N { public struct A<T> { public struct B<U> { } } public struct C { } } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("N.A`1"); var typeB = typeA.GetNestedType("B`1"); var typeC = assembly.GetType("N.C"); Assert.Equal("N.C*", typeC.MakePointerType().GetTypeName()); Assert.Equal("N.A<N.C>*", typeA.MakeGenericType(typeC).MakePointerType().GetTypeName()); Assert.Equal("N.A<N.C>.B<N.C>*", typeB.MakeGenericType(typeC, typeC).MakePointerType().GetTypeName()); } [Fact] public void Void() { Assert.Equal("void", typeof(void).GetTypeName()); Assert.Equal("void*", typeof(void).MakePointerType().GetTypeName()); } [Fact] public void KeywordIdentifiers() { var source = @" public class @object { public class @true { } } namespace @return { public class @yield<@async> { public class @await { } } namespace @false { public class @null { } } } "; var assembly = GetAssembly(source); var objectType = assembly.GetType("object"); var trueType = objectType.GetNestedType("true"); var nullType = assembly.GetType("return.false.null"); var yieldType = assembly.GetType("return.yield`1"); var constructedYieldType = yieldType.MakeGenericType(nullType); var awaitType = yieldType.GetNestedType("await"); var constructedAwaitType = awaitType.MakeGenericType(nullType); Assert.Equal("object", objectType.GetTypeName(escapeKeywordIdentifiers: false)); Assert.Equal("object.true", trueType.GetTypeName(escapeKeywordIdentifiers: false)); Assert.Equal("return.false.null", nullType.GetTypeName(escapeKeywordIdentifiers: false)); Assert.Equal("return.yield<async>", yieldType.GetTypeName(escapeKeywordIdentifiers: false)); Assert.Equal("return.yield<return.false.null>", constructedYieldType.GetTypeName(escapeKeywordIdentifiers: false)); Assert.Equal("return.yield<return.false.null>.await", constructedAwaitType.GetTypeName(escapeKeywordIdentifiers: false)); Assert.Equal("@object", objectType.GetTypeName(escapeKeywordIdentifiers: true)); Assert.Equal("@object.@true", trueType.GetTypeName(escapeKeywordIdentifiers: true)); Assert.Equal("@return.@false.@null", nullType.GetTypeName(escapeKeywordIdentifiers: true)); Assert.Equal("@return.@yield<@async>", yieldType.GetTypeName(escapeKeywordIdentifiers: true)); Assert.Equal("@return.@yield<@return.@false.@null>", constructedYieldType.GetTypeName(escapeKeywordIdentifiers: true)); Assert.Equal("@return.@yield<@return.@false.@null>.@await", constructedAwaitType.GetTypeName(escapeKeywordIdentifiers: true)); } [WorkItem(1087216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087216")] [Fact] public void DynamicAttribute_KeywordEscaping() { var attributes = new[] { true }; Assert.Equal("dynamic", typeof(object).GetTypeName(MakeCustomTypeInfo(attributes), escapeKeywordIdentifiers: false)); Assert.Equal("dynamic", typeof(object).GetTypeName(MakeCustomTypeInfo(attributes), escapeKeywordIdentifiers: true)); } [WorkItem(1087216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087216")] [Fact] public void DynamicAttribute_Locations() { // Standalone. Assert.Equal("dynamic", typeof(object).GetTypeName(MakeCustomTypeInfo(true))); // Array element type. Assert.Equal("dynamic[]", typeof(object[]).GetTypeName(MakeCustomTypeInfo(false, true))); Assert.Equal("dynamic[][]", typeof(object[][]).GetTypeName(MakeCustomTypeInfo(false, false, true))); // Type argument of top-level type. Assert.Equal("System.Func<dynamic>", typeof(Func<object>).GetTypeName(MakeCustomTypeInfo(false, true))); var source = @" namespace N { public struct A<T> { public struct B<U> { } } public struct C { } } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("N.A`1"); var typeB = typeA.GetNestedType("B`1"); var typeBConstructed = typeB.MakeGenericType(typeof(object), typeof(object)); // Type argument of nested type. Assert.Equal("N.A<object>.B<dynamic>", typeBConstructed.GetTypeName(MakeCustomTypeInfo(false, false, true))); Assert.Equal("N.A<dynamic>.B<object>", typeBConstructed.GetTypeName(MakeCustomTypeInfo(false, true, false))); Assert.Equal("N.A<dynamic>.B<dynamic>[]", typeBConstructed.MakeArrayType().GetTypeName(MakeCustomTypeInfo(false, false, true, true))); } [WorkItem(1087216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087216")] [Fact] public void DynamicAttribute_InvalidFlags() { // Invalid true. Assert.Equal("int", typeof(int).GetTypeName(MakeCustomTypeInfo(true))); Assert.Equal("dynamic[]", typeof(object[]).GetTypeName(MakeCustomTypeInfo(true, true))); // Too many. Assert.Equal("dynamic", typeof(object).GetTypeName(MakeCustomTypeInfo(true, true))); Assert.Equal("object", typeof(object).GetTypeName(MakeCustomTypeInfo(false, true))); // Too few. Assert.Equal("object[]", typeof(object[]).GetTypeName(MakeCustomTypeInfo(true))); Assert.Equal("object[]", typeof(object[]).GetTypeName(MakeCustomTypeInfo(false))); // Type argument of top-level type. Assert.Equal("System.Func<object>", typeof(Func<object>).GetTypeName(MakeCustomTypeInfo(true))); var source = @" namespace N { public struct A<T> { public struct B<U> { } } public struct C { } } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("N.A`1"); var typeB = typeA.GetNestedType("B`1"); var typeBConstructed = typeB.MakeGenericType(typeof(object), typeof(object)); // Type argument of nested type. Assert.Equal("N.A<object>.B<object>", typeBConstructed.GetTypeName(MakeCustomTypeInfo(false))); Assert.Equal("N.A<dynamic>.B<object>", typeBConstructed.GetTypeName(MakeCustomTypeInfo(false, true))); Assert.Equal("N.A<dynamic>.B<object>[]", typeBConstructed.MakeArrayType().GetTypeName(MakeCustomTypeInfo(false, false, true))); } [WorkItem(1087216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087216")] [Fact] public void DynamicAttribute_OtherGuid() { var typeInfo = DkmClrCustomTypeInfo.Create(Guid.NewGuid(), new ReadOnlyCollection<byte>(new byte[] { 1 })); Assert.Equal("object", typeof(object).GetTypeName(typeInfo)); Assert.Equal("object[]", typeof(object[]).GetTypeName(typeInfo)); } [Fact] public void MangledTypeParameterName() { var il = @" .class public auto ansi beforefieldinit Type`1<'<>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 } } "; 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 type = assembly.GetType("Type`1"); var typeName = type.GetTypeName(); Assert.Equal("Type<<>Mangled>", typeName); } } }
// Licensed to the .NET Foundation under one or more 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.Collections.ObjectModel; using Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class TypeNameFormatterTests : CSharpResultProviderTestBase { [Fact] public void Primitives() { Assert.Equal("object", typeof(object).GetTypeName()); Assert.Equal("bool", typeof(bool).GetTypeName()); Assert.Equal("char", typeof(char).GetTypeName()); Assert.Equal("sbyte", typeof(sbyte).GetTypeName()); Assert.Equal("byte", typeof(byte).GetTypeName()); Assert.Equal("short", typeof(short).GetTypeName()); Assert.Equal("ushort", typeof(ushort).GetTypeName()); Assert.Equal("int", typeof(int).GetTypeName()); Assert.Equal("uint", typeof(uint).GetTypeName()); Assert.Equal("long", typeof(long).GetTypeName()); Assert.Equal("ulong", typeof(ulong).GetTypeName()); Assert.Equal("float", typeof(float).GetTypeName()); Assert.Equal("double", typeof(double).GetTypeName()); Assert.Equal("decimal", typeof(decimal).GetTypeName()); Assert.Equal("string", typeof(string).GetTypeName()); } [Fact, WorkItem(1016796, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1016796")] public void NestedTypes() { var source = @" public class A { public class B { } } namespace N { public class A { public class B { } } public class G1<T> { public class G2<T> { public class G3<U> { } class G4<U, V> { } } } } "; var assembly = GetAssembly(source); Assert.Equal("A", assembly.GetType("A").GetTypeName()); Assert.Equal("A.B", assembly.GetType("A+B").GetTypeName()); Assert.Equal("N.A", assembly.GetType("N.A").GetTypeName()); Assert.Equal("N.A.B", assembly.GetType("N.A+B").GetTypeName()); Assert.Equal("N.G1<int>.G2<float>.G3<double>", assembly.GetType("N.G1`1+G2`1+G3`1").MakeGenericType(typeof(int), typeof(float), typeof(double)).GetTypeName()); Assert.Equal("N.G1<int>.G2<float>.G4<double, ushort>", assembly.GetType("N.G1`1+G2`1+G4`2").MakeGenericType(typeof(int), typeof(float), typeof(double), typeof(ushort)).GetTypeName()); } [Fact] public void GenericTypes() { var source = @" public class A { public class B { } } namespace N { public class C<T, U> { public class D<V, W> { } } } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("A"); var typeB = typeA.GetNestedType("B"); var typeC = assembly.GetType("N.C`2"); var typeD = typeC.GetNestedType("D`2"); var typeInt = typeof(int); var typeString = typeof(string); var typeCIntString = typeC.MakeGenericType(typeInt, typeString); Assert.Equal("N.C<T, U>", typeC.GetTypeName()); Assert.Equal("N.C<int, string>", typeCIntString.GetTypeName()); Assert.Equal("N.C<A, A.B>", typeC.MakeGenericType(typeA, typeB).GetTypeName()); Assert.Equal("N.C<int, string>.D<A, A.B>", typeD.MakeGenericType(typeInt, typeString, typeA, typeB).GetTypeName()); Assert.Equal("N.C<A, N.C<int, string>>.D<N.C<int, string>, A.B>", typeD.MakeGenericType(typeA, typeCIntString, typeCIntString, typeB).GetTypeName()); } [Fact] public void NonGenericInGeneric() { var source = @" public class A<T> { public class B { } } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("A`1"); var typeB = typeA.GetNestedType("B"); Assert.Equal("A<int>.B", typeB.MakeGenericType(typeof(int)).GetTypeName()); } [Fact] public void PrimitiveNullableTypes() { Assert.Equal("int?", typeof(int?).GetTypeName()); Assert.Equal("bool?", typeof(bool?).GetTypeName()); } [Fact] public void NullableTypes() { var source = @" namespace N { public struct A<T> { public struct B<U> { } } public struct C { } } "; var typeNullable = typeof(System.Nullable<>); var assembly = GetAssembly(source); var typeA = assembly.GetType("N.A`1"); var typeB = typeA.GetNestedType("B`1"); var typeC = assembly.GetType("N.C"); Assert.Equal("N.C?", typeNullable.MakeGenericType(typeC).GetTypeName()); Assert.Equal("N.A<N.C>?", typeNullable.MakeGenericType(typeA.MakeGenericType(typeC)).GetTypeName()); Assert.Equal("N.A<N.C>.B<N.C>?", typeNullable.MakeGenericType(typeB.MakeGenericType(typeC, typeC)).GetTypeName()); } [Fact] public void PrimitiveArrayTypes() { Assert.Equal("int[]", typeof(int[]).GetTypeName()); Assert.Equal("int[,]", typeof(int[,]).GetTypeName()); Assert.Equal("int[][,]", typeof(int[][,]).GetTypeName()); Assert.Equal("int[,][]", typeof(int[,][]).GetTypeName()); } [Fact] public void ArrayTypes() { var source = @" namespace N { public class A<T> { public class B<U> { } } public class C { } } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("N.A`1"); var typeB = typeA.GetNestedType("B`1"); var typeC = assembly.GetType("N.C"); Assert.NotEqual(typeC.MakeArrayType(), typeC.MakeArrayType(1)); Assert.Equal("N.C[]", typeC.MakeArrayType().GetTypeName()); Assert.Equal("N.C[]", typeC.MakeArrayType(1).GetTypeName()); // NOTE: Multi-dimensional array that happens to exactly one dimension. Assert.Equal("N.A<N.C>[,]", typeA.MakeGenericType(typeC).MakeArrayType(2).GetTypeName()); Assert.Equal("N.A<N.C[]>.B<N.C>[,,]", typeB.MakeGenericType(typeC.MakeArrayType(), typeC).MakeArrayType(3).GetTypeName()); } [Fact] public void CustomBoundsArrayTypes() { Array instance = Array.CreateInstance(typeof(int), new[] { 1, 2, 3, }, new[] { 4, 5, 6, }); Assert.Equal("int[,,]", instance.GetType().GetTypeName()); Assert.Equal("int[][,,]", instance.GetType().MakeArrayType().GetTypeName()); } [Fact] public void PrimitivePointerTypes() { Assert.Equal("int*", typeof(int).MakePointerType().GetTypeName()); Assert.Equal("int**", typeof(int).MakePointerType().MakePointerType().GetTypeName()); Assert.Equal("int*[]", typeof(int).MakePointerType().MakeArrayType().GetTypeName()); } [Fact] public void PointerTypes() { var source = @" namespace N { public struct A<T> { public struct B<U> { } } public struct C { } } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("N.A`1"); var typeB = typeA.GetNestedType("B`1"); var typeC = assembly.GetType("N.C"); Assert.Equal("N.C*", typeC.MakePointerType().GetTypeName()); Assert.Equal("N.A<N.C>*", typeA.MakeGenericType(typeC).MakePointerType().GetTypeName()); Assert.Equal("N.A<N.C>.B<N.C>*", typeB.MakeGenericType(typeC, typeC).MakePointerType().GetTypeName()); } [Fact] public void Void() { Assert.Equal("void", typeof(void).GetTypeName()); Assert.Equal("void*", typeof(void).MakePointerType().GetTypeName()); } [Fact] public void KeywordIdentifiers() { var source = @" public class @object { public class @true { } } namespace @return { public class @yield<@async> { public class @await { } } namespace @false { public class @null { } } } "; var assembly = GetAssembly(source); var objectType = assembly.GetType("object"); var trueType = objectType.GetNestedType("true"); var nullType = assembly.GetType("return.false.null"); var yieldType = assembly.GetType("return.yield`1"); var constructedYieldType = yieldType.MakeGenericType(nullType); var awaitType = yieldType.GetNestedType("await"); var constructedAwaitType = awaitType.MakeGenericType(nullType); Assert.Equal("object", objectType.GetTypeName(escapeKeywordIdentifiers: false)); Assert.Equal("object.true", trueType.GetTypeName(escapeKeywordIdentifiers: false)); Assert.Equal("return.false.null", nullType.GetTypeName(escapeKeywordIdentifiers: false)); Assert.Equal("return.yield<async>", yieldType.GetTypeName(escapeKeywordIdentifiers: false)); Assert.Equal("return.yield<return.false.null>", constructedYieldType.GetTypeName(escapeKeywordIdentifiers: false)); Assert.Equal("return.yield<return.false.null>.await", constructedAwaitType.GetTypeName(escapeKeywordIdentifiers: false)); Assert.Equal("@object", objectType.GetTypeName(escapeKeywordIdentifiers: true)); Assert.Equal("@object.@true", trueType.GetTypeName(escapeKeywordIdentifiers: true)); Assert.Equal("@return.@false.@null", nullType.GetTypeName(escapeKeywordIdentifiers: true)); Assert.Equal("@return.@yield<@async>", yieldType.GetTypeName(escapeKeywordIdentifiers: true)); Assert.Equal("@return.@yield<@return.@false.@null>", constructedYieldType.GetTypeName(escapeKeywordIdentifiers: true)); Assert.Equal("@return.@yield<@return.@false.@null>.@await", constructedAwaitType.GetTypeName(escapeKeywordIdentifiers: true)); } [WorkItem(1087216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087216")] [Fact] public void DynamicAttribute_KeywordEscaping() { var attributes = new[] { true }; Assert.Equal("dynamic", typeof(object).GetTypeName(MakeCustomTypeInfo(attributes), escapeKeywordIdentifiers: false)); Assert.Equal("dynamic", typeof(object).GetTypeName(MakeCustomTypeInfo(attributes), escapeKeywordIdentifiers: true)); } [WorkItem(1087216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087216")] [Fact] public void DynamicAttribute_Locations() { // Standalone. Assert.Equal("dynamic", typeof(object).GetTypeName(MakeCustomTypeInfo(true))); // Array element type. Assert.Equal("dynamic[]", typeof(object[]).GetTypeName(MakeCustomTypeInfo(false, true))); Assert.Equal("dynamic[][]", typeof(object[][]).GetTypeName(MakeCustomTypeInfo(false, false, true))); // Type argument of top-level type. Assert.Equal("System.Func<dynamic>", typeof(Func<object>).GetTypeName(MakeCustomTypeInfo(false, true))); var source = @" namespace N { public struct A<T> { public struct B<U> { } } public struct C { } } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("N.A`1"); var typeB = typeA.GetNestedType("B`1"); var typeBConstructed = typeB.MakeGenericType(typeof(object), typeof(object)); // Type argument of nested type. Assert.Equal("N.A<object>.B<dynamic>", typeBConstructed.GetTypeName(MakeCustomTypeInfo(false, false, true))); Assert.Equal("N.A<dynamic>.B<object>", typeBConstructed.GetTypeName(MakeCustomTypeInfo(false, true, false))); Assert.Equal("N.A<dynamic>.B<dynamic>[]", typeBConstructed.MakeArrayType().GetTypeName(MakeCustomTypeInfo(false, false, true, true))); } [WorkItem(1087216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087216")] [Fact] public void DynamicAttribute_InvalidFlags() { // Invalid true. Assert.Equal("int", typeof(int).GetTypeName(MakeCustomTypeInfo(true))); Assert.Equal("dynamic[]", typeof(object[]).GetTypeName(MakeCustomTypeInfo(true, true))); // Too many. Assert.Equal("dynamic", typeof(object).GetTypeName(MakeCustomTypeInfo(true, true))); Assert.Equal("object", typeof(object).GetTypeName(MakeCustomTypeInfo(false, true))); // Too few. Assert.Equal("object[]", typeof(object[]).GetTypeName(MakeCustomTypeInfo(true))); Assert.Equal("object[]", typeof(object[]).GetTypeName(MakeCustomTypeInfo(false))); // Type argument of top-level type. Assert.Equal("System.Func<object>", typeof(Func<object>).GetTypeName(MakeCustomTypeInfo(true))); var source = @" namespace N { public struct A<T> { public struct B<U> { } } public struct C { } } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("N.A`1"); var typeB = typeA.GetNestedType("B`1"); var typeBConstructed = typeB.MakeGenericType(typeof(object), typeof(object)); // Type argument of nested type. Assert.Equal("N.A<object>.B<object>", typeBConstructed.GetTypeName(MakeCustomTypeInfo(false))); Assert.Equal("N.A<dynamic>.B<object>", typeBConstructed.GetTypeName(MakeCustomTypeInfo(false, true))); Assert.Equal("N.A<dynamic>.B<object>[]", typeBConstructed.MakeArrayType().GetTypeName(MakeCustomTypeInfo(false, false, true))); } [WorkItem(1087216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087216")] [Fact] public void DynamicAttribute_OtherGuid() { var typeInfo = DkmClrCustomTypeInfo.Create(Guid.NewGuid(), new ReadOnlyCollection<byte>(new byte[] { 1 })); Assert.Equal("object", typeof(object).GetTypeName(typeInfo)); Assert.Equal("object[]", typeof(object[]).GetTypeName(typeInfo)); } [Fact] public void MangledTypeParameterName() { var il = @" .class public auto ansi beforefieldinit Type`1<'<>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 } } "; 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 type = assembly.GetType("Type`1"); var typeName = type.GetTypeName(); Assert.Equal("Type<<>Mangled>", typeName); } } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Features/LanguageServer/Protocol/Extensions/Extensions.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 System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.Text.Adornments; namespace Microsoft.CodeAnalysis.LanguageServer { internal static class Extensions { public static Uri GetURI(this TextDocument document) { return ProtocolConversions.GetUriFromFilePath(document.FilePath); } public static ImmutableArray<Document> GetDocuments(this Solution solution, Uri documentUri) => GetDocuments(solution, documentUri, clientName: null, logger: null); public static ImmutableArray<Document> GetDocuments(this Solution solution, Uri documentUri, string? clientName) => GetDocuments(solution, documentUri, clientName, logger: null); public static ImmutableArray<Document> GetDocuments(this Solution solution, Uri documentUri, string? clientName, ILspLogger? logger) { var documentIds = GetDocumentIds(solution, documentUri); var documents = documentIds.SelectAsArray(id => solution.GetRequiredDocument(id)); return FilterDocumentsByClientName(documents, clientName, logger); } public static ImmutableArray<DocumentId> GetDocumentIds(this Solution solution, Uri documentUri) { // TODO: we need to normalize this. but for now, we check both absolute and local path // right now, based on who calls this, solution might has "/" or "\\" as directory // separator var documentIds = solution.GetDocumentIdsWithFilePath(documentUri.AbsolutePath); if (!documentIds.Any()) { documentIds = solution.GetDocumentIdsWithFilePath(documentUri.LocalPath); } return documentIds; } private static ImmutableArray<Document> FilterDocumentsByClientName(ImmutableArray<Document> documents, string? clientName, ILspLogger? logger) { // If we don't have a client name, then we're done filtering if (clientName == null) { return documents; } // We have a client name, so we need to filter to only documents that match that name return documents.WhereAsArray(document => { var documentPropertiesService = document.Services.GetService<DocumentPropertiesService>(); // When a client name is specified, only return documents that have a matching client name. // Allows the razor lsp server to return results only for razor documents. // This workaround should be removed when https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1106064/ // is fixed (so that the razor language server is only asked about razor buffers). var documentClientName = documentPropertiesService?.DiagnosticsLspClientName; var clientNameMatch = Equals(documentClientName, clientName); if (!clientNameMatch && logger is not null) { logger.TraceInformation($"Found matching document but it's client name '{documentClientName}' is not a match."); } return clientNameMatch; }); } public static Document? GetDocument(this Solution solution, TextDocumentIdentifier documentIdentifier) => solution.GetDocument(documentIdentifier, clientName: null); public static Document? GetDocument(this Solution solution, TextDocumentIdentifier documentIdentifier, string? clientName) { var documents = solution.GetDocuments(documentIdentifier.Uri, clientName, logger: null); if (documents.Length == 0) { return null; } return documents.FindDocumentInProjectContext(documentIdentifier); } public static Document FindDocumentInProjectContext(this ImmutableArray<Document> documents, TextDocumentIdentifier documentIdentifier) { if (documents.Length > 1) { // We have more than one document; try to find the one that matches the right context if (documentIdentifier is VSTextDocumentIdentifier vsDocumentIdentifier && vsDocumentIdentifier.ProjectContext != null) { var projectId = ProtocolConversions.ProjectContextToProjectId(vsDocumentIdentifier.ProjectContext); var matchingDocument = documents.FirstOrDefault(d => d.Project.Id == projectId); if (matchingDocument != null) { return matchingDocument; } } else { // We were not passed a project context. This can happen when the LSP powered NavBar is not enabled. // This branch should be removed when we're using the LSP based navbar in all scenarios. var solution = documents.First().Project.Solution; // Lookup which of the linked documents is currently active in the workspace. var documentIdInCurrentContext = solution.Workspace.GetDocumentIdInCurrentContext(documents.First().Id); return solution.GetRequiredDocument(documentIdInCurrentContext); } } // We either have only one document or have multiple, but none of them matched our context. In the // latter case, we'll just return the first one arbitrarily since this might just be some temporary mis-sync // of client and server state. return documents[0]; } public static async Task<int> GetPositionFromLinePositionAsync(this TextDocument document, LinePosition linePosition, CancellationToken cancellationToken) { var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); return text.Lines.GetPosition(linePosition); } public static bool HasVisualStudioLspCapability(this ClientCapabilities? clientCapabilities) { if (clientCapabilities is VSInternalClientCapabilities vsClientCapabilities) { return vsClientCapabilities.SupportsVisualStudioExtensions; } return false; } public static bool HasCompletionListDataCapability(this ClientCapabilities clientCapabilities) { if (!TryGetVSCompletionListSetting(clientCapabilities, out var completionListSetting)) { return false; } return completionListSetting.Data; } public static bool HasCompletionListCommitCharactersCapability(this ClientCapabilities clientCapabilities) { if (!TryGetVSCompletionListSetting(clientCapabilities, out var completionListSetting)) { return false; } return completionListSetting.CommitCharacters; } public static string GetMarkdownLanguageName(this Document document) { switch (document.Project.Language) { case LanguageNames.CSharp: return "csharp"; case LanguageNames.VisualBasic: return "vb"; case LanguageNames.FSharp: return "fsharp"; case "TypeScript": return "typescript"; default: throw new ArgumentException(string.Format("Document project language {0} is not valid", document.Project.Language)); } } public static ClassifiedTextElement GetClassifiedText(this DefinitionItem definition) => new ClassifiedTextElement(definition.DisplayParts.Select(part => new ClassifiedTextRun(part.Tag.ToClassificationTypeName(), part.Text))); public static bool IsRazorDocument(this Document document) { // Only razor docs have an ISpanMappingService, so we can use the presence of that to determine if this doc // belongs to them. var spanMapper = document.Services.GetService<ISpanMappingService>(); return spanMapper != null; } private static bool TryGetVSCompletionListSetting(ClientCapabilities clientCapabilities, [NotNullWhen(returnValue: true)] out VSInternalCompletionListSetting? completionListSetting) { if (clientCapabilities is not VSInternalClientCapabilities vsClientCapabilities) { completionListSetting = null; return false; } var textDocumentCapability = vsClientCapabilities.TextDocument; if (textDocumentCapability == null) { completionListSetting = null; return false; } if (textDocumentCapability.Completion is not VSInternalCompletionSetting vsCompletionSetting) { completionListSetting = null; return false; } completionListSetting = vsCompletionSetting.CompletionList; if (completionListSetting == null) { 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; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.Text.Adornments; namespace Microsoft.CodeAnalysis.LanguageServer { internal static class Extensions { public static Uri GetURI(this TextDocument document) { return ProtocolConversions.GetUriFromFilePath(document.FilePath); } public static ImmutableArray<Document> GetDocuments(this Solution solution, Uri documentUri) => GetDocuments(solution, documentUri, clientName: null, logger: null); public static ImmutableArray<Document> GetDocuments(this Solution solution, Uri documentUri, string? clientName) => GetDocuments(solution, documentUri, clientName, logger: null); public static ImmutableArray<Document> GetDocuments(this Solution solution, Uri documentUri, string? clientName, ILspLogger? logger) { var documentIds = GetDocumentIds(solution, documentUri); var documents = documentIds.SelectAsArray(id => solution.GetRequiredDocument(id)); return FilterDocumentsByClientName(documents, clientName, logger); } public static ImmutableArray<DocumentId> GetDocumentIds(this Solution solution, Uri documentUri) { // TODO: we need to normalize this. but for now, we check both absolute and local path // right now, based on who calls this, solution might has "/" or "\\" as directory // separator var documentIds = solution.GetDocumentIdsWithFilePath(documentUri.AbsolutePath); if (!documentIds.Any()) { documentIds = solution.GetDocumentIdsWithFilePath(documentUri.LocalPath); } return documentIds; } private static ImmutableArray<Document> FilterDocumentsByClientName(ImmutableArray<Document> documents, string? clientName, ILspLogger? logger) { // If we don't have a client name, then we're done filtering if (clientName == null) { return documents; } // We have a client name, so we need to filter to only documents that match that name return documents.WhereAsArray(document => { var documentPropertiesService = document.Services.GetService<DocumentPropertiesService>(); // When a client name is specified, only return documents that have a matching client name. // Allows the razor lsp server to return results only for razor documents. // This workaround should be removed when https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1106064/ // is fixed (so that the razor language server is only asked about razor buffers). var documentClientName = documentPropertiesService?.DiagnosticsLspClientName; var clientNameMatch = Equals(documentClientName, clientName); if (!clientNameMatch && logger is not null) { logger.TraceInformation($"Found matching document but it's client name '{documentClientName}' is not a match."); } return clientNameMatch; }); } public static Document? GetDocument(this Solution solution, TextDocumentIdentifier documentIdentifier) => solution.GetDocument(documentIdentifier, clientName: null); public static Document? GetDocument(this Solution solution, TextDocumentIdentifier documentIdentifier, string? clientName) { var documents = solution.GetDocuments(documentIdentifier.Uri, clientName, logger: null); if (documents.Length == 0) { return null; } return documents.FindDocumentInProjectContext(documentIdentifier); } public static Document FindDocumentInProjectContext(this ImmutableArray<Document> documents, TextDocumentIdentifier documentIdentifier) { if (documents.Length > 1) { // We have more than one document; try to find the one that matches the right context if (documentIdentifier is VSTextDocumentIdentifier vsDocumentIdentifier && vsDocumentIdentifier.ProjectContext != null) { var projectId = ProtocolConversions.ProjectContextToProjectId(vsDocumentIdentifier.ProjectContext); var matchingDocument = documents.FirstOrDefault(d => d.Project.Id == projectId); if (matchingDocument != null) { return matchingDocument; } } else { // We were not passed a project context. This can happen when the LSP powered NavBar is not enabled. // This branch should be removed when we're using the LSP based navbar in all scenarios. var solution = documents.First().Project.Solution; // Lookup which of the linked documents is currently active in the workspace. var documentIdInCurrentContext = solution.Workspace.GetDocumentIdInCurrentContext(documents.First().Id); return solution.GetRequiredDocument(documentIdInCurrentContext); } } // We either have only one document or have multiple, but none of them matched our context. In the // latter case, we'll just return the first one arbitrarily since this might just be some temporary mis-sync // of client and server state. return documents[0]; } public static async Task<int> GetPositionFromLinePositionAsync(this TextDocument document, LinePosition linePosition, CancellationToken cancellationToken) { var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); return text.Lines.GetPosition(linePosition); } public static bool HasVisualStudioLspCapability(this ClientCapabilities? clientCapabilities) { if (clientCapabilities is VSInternalClientCapabilities vsClientCapabilities) { return vsClientCapabilities.SupportsVisualStudioExtensions; } return false; } public static bool HasCompletionListDataCapability(this ClientCapabilities clientCapabilities) { if (!TryGetVSCompletionListSetting(clientCapabilities, out var completionListSetting)) { return false; } return completionListSetting.Data; } public static bool HasCompletionListCommitCharactersCapability(this ClientCapabilities clientCapabilities) { if (!TryGetVSCompletionListSetting(clientCapabilities, out var completionListSetting)) { return false; } return completionListSetting.CommitCharacters; } public static string GetMarkdownLanguageName(this Document document) { switch (document.Project.Language) { case LanguageNames.CSharp: return "csharp"; case LanguageNames.VisualBasic: return "vb"; case LanguageNames.FSharp: return "fsharp"; case "TypeScript": return "typescript"; default: throw new ArgumentException(string.Format("Document project language {0} is not valid", document.Project.Language)); } } public static ClassifiedTextElement GetClassifiedText(this DefinitionItem definition) => new ClassifiedTextElement(definition.DisplayParts.Select(part => new ClassifiedTextRun(part.Tag.ToClassificationTypeName(), part.Text))); public static bool IsRazorDocument(this Document document) { // Only razor docs have an ISpanMappingService, so we can use the presence of that to determine if this doc // belongs to them. var spanMapper = document.Services.GetService<ISpanMappingService>(); return spanMapper != null; } private static bool TryGetVSCompletionListSetting(ClientCapabilities clientCapabilities, [NotNullWhen(returnValue: true)] out VSInternalCompletionListSetting? completionListSetting) { if (clientCapabilities is not VSInternalClientCapabilities vsClientCapabilities) { completionListSetting = null; return false; } var textDocumentCapability = vsClientCapabilities.TextDocument; if (textDocumentCapability == null) { completionListSetting = null; return false; } if (textDocumentCapability.Completion is not VSInternalCompletionSetting vsCompletionSetting) { completionListSetting = null; return false; } completionListSetting = vsCompletionSetting.CompletionList; if (completionListSetting == null) { return false; } return true; } } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/AbstractTriviaDataFactory.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 Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting { internal abstract partial class AbstractTriviaDataFactory { private const int SpaceCacheSize = 10; private const int LineBreakCacheSize = 5; private const int IndentationLevelCacheSize = 20; protected readonly TreeData TreeInfo; protected readonly AnalyzerConfigOptions Options; protected readonly bool UseTabs; protected readonly int TabSize; protected readonly int IndentationSize; private readonly Whitespace[] _spaces; private readonly Whitespace?[,] _whitespaces = new Whitespace[LineBreakCacheSize, IndentationLevelCacheSize]; protected AbstractTriviaDataFactory(TreeData treeInfo, AnalyzerConfigOptions options) { Contract.ThrowIfNull(treeInfo); Contract.ThrowIfNull(options); this.TreeInfo = treeInfo; this.Options = options; UseTabs = options.GetOption(FormattingOptions2.UseTabs); TabSize = options.GetOption(FormattingOptions2.TabSize); IndentationSize = options.GetOption(FormattingOptions2.IndentationSize); _spaces = new Whitespace[SpaceCacheSize]; for (var i = 0; i < SpaceCacheSize; i++) { _spaces[i] = new Whitespace(this.Options, space: i, elastic: false, language: treeInfo.Root.Language); } } protected TriviaData GetSpaceTriviaData(int space, bool elastic = false) { Contract.ThrowIfFalse(space >= 0); // if result has elastic trivia in them, never use cache if (elastic) { return new Whitespace(this.Options, space, elastic: true, language: this.TreeInfo.Root.Language); } if (space < SpaceCacheSize) { return _spaces[space]; } // create a new space return new Whitespace(this.Options, space, elastic: false, language: this.TreeInfo.Root.Language); } protected TriviaData GetWhitespaceTriviaData(int lineBreaks, int indentation, bool useTriviaAsItIs, bool elastic) { Contract.ThrowIfFalse(lineBreaks >= 0); Contract.ThrowIfFalse(indentation >= 0); // we can use cache // #1. if whitespace trivia don't have any elastic trivia and // #2. analysis (Item1) didn't find anything preventing us from using cache such as trailing whitespace before new line // #3. number of line breaks (Item2) are under cache capacity (line breaks) // #4. indentation (Item3) is aligned to indentation level var canUseCache = !elastic && useTriviaAsItIs && lineBreaks > 0 && lineBreaks <= LineBreakCacheSize && indentation % IndentationSize == 0; if (canUseCache) { var indentationLevel = indentation / IndentationSize; if (indentationLevel < IndentationLevelCacheSize) { var lineIndex = lineBreaks - 1; EnsureWhitespaceTriviaInfo(lineIndex, indentationLevel); return _whitespaces[lineIndex, indentationLevel]!; } } return useTriviaAsItIs ? new Whitespace(this.Options, lineBreaks, indentation, elastic, language: this.TreeInfo.Root.Language) : new ModifiedWhitespace(this.Options, lineBreaks, indentation, elastic, language: this.TreeInfo.Root.Language); } private void EnsureWhitespaceTriviaInfo(int lineIndex, int indentationLevel) { Contract.ThrowIfFalse(lineIndex >= 0 && lineIndex < LineBreakCacheSize); Contract.ThrowIfFalse(indentationLevel >= 0 && indentationLevel < _whitespaces.Length / _whitespaces.Rank); // set up caches if (_whitespaces[lineIndex, indentationLevel] == null) { var indentation = indentationLevel * IndentationSize; var triviaInfo = new Whitespace(this.Options, lineBreaks: lineIndex + 1, indentation: indentation, elastic: false, language: this.TreeInfo.Root.Language); Interlocked.CompareExchange(ref _whitespaces[lineIndex, indentationLevel], triviaInfo, null); } } public abstract TriviaData CreateLeadingTrivia(SyntaxToken token); public abstract TriviaData CreateTrailingTrivia(SyntaxToken token); public abstract TriviaData Create(SyntaxToken token1, SyntaxToken token2); } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting { internal abstract partial class AbstractTriviaDataFactory { private const int SpaceCacheSize = 10; private const int LineBreakCacheSize = 5; private const int IndentationLevelCacheSize = 20; protected readonly TreeData TreeInfo; protected readonly AnalyzerConfigOptions Options; protected readonly bool UseTabs; protected readonly int TabSize; protected readonly int IndentationSize; private readonly Whitespace[] _spaces; private readonly Whitespace?[,] _whitespaces = new Whitespace[LineBreakCacheSize, IndentationLevelCacheSize]; protected AbstractTriviaDataFactory(TreeData treeInfo, AnalyzerConfigOptions options) { Contract.ThrowIfNull(treeInfo); Contract.ThrowIfNull(options); this.TreeInfo = treeInfo; this.Options = options; UseTabs = options.GetOption(FormattingOptions2.UseTabs); TabSize = options.GetOption(FormattingOptions2.TabSize); IndentationSize = options.GetOption(FormattingOptions2.IndentationSize); _spaces = new Whitespace[SpaceCacheSize]; for (var i = 0; i < SpaceCacheSize; i++) { _spaces[i] = new Whitespace(this.Options, space: i, elastic: false, language: treeInfo.Root.Language); } } protected TriviaData GetSpaceTriviaData(int space, bool elastic = false) { Contract.ThrowIfFalse(space >= 0); // if result has elastic trivia in them, never use cache if (elastic) { return new Whitespace(this.Options, space, elastic: true, language: this.TreeInfo.Root.Language); } if (space < SpaceCacheSize) { return _spaces[space]; } // create a new space return new Whitespace(this.Options, space, elastic: false, language: this.TreeInfo.Root.Language); } protected TriviaData GetWhitespaceTriviaData(int lineBreaks, int indentation, bool useTriviaAsItIs, bool elastic) { Contract.ThrowIfFalse(lineBreaks >= 0); Contract.ThrowIfFalse(indentation >= 0); // we can use cache // #1. if whitespace trivia don't have any elastic trivia and // #2. analysis (Item1) didn't find anything preventing us from using cache such as trailing whitespace before new line // #3. number of line breaks (Item2) are under cache capacity (line breaks) // #4. indentation (Item3) is aligned to indentation level var canUseCache = !elastic && useTriviaAsItIs && lineBreaks > 0 && lineBreaks <= LineBreakCacheSize && indentation % IndentationSize == 0; if (canUseCache) { var indentationLevel = indentation / IndentationSize; if (indentationLevel < IndentationLevelCacheSize) { var lineIndex = lineBreaks - 1; EnsureWhitespaceTriviaInfo(lineIndex, indentationLevel); return _whitespaces[lineIndex, indentationLevel]!; } } return useTriviaAsItIs ? new Whitespace(this.Options, lineBreaks, indentation, elastic, language: this.TreeInfo.Root.Language) : new ModifiedWhitespace(this.Options, lineBreaks, indentation, elastic, language: this.TreeInfo.Root.Language); } private void EnsureWhitespaceTriviaInfo(int lineIndex, int indentationLevel) { Contract.ThrowIfFalse(lineIndex >= 0 && lineIndex < LineBreakCacheSize); Contract.ThrowIfFalse(indentationLevel >= 0 && indentationLevel < _whitespaces.Length / _whitespaces.Rank); // set up caches if (_whitespaces[lineIndex, indentationLevel] == null) { var indentation = indentationLevel * IndentationSize; var triviaInfo = new Whitespace(this.Options, lineBreaks: lineIndex + 1, indentation: indentation, elastic: false, language: this.TreeInfo.Root.Language); Interlocked.CompareExchange(ref _whitespaces[lineIndex, indentationLevel], triviaInfo, null); } } public abstract TriviaData CreateLeadingTrivia(SyntaxToken token); public abstract TriviaData CreateTrailingTrivia(SyntaxToken token); public abstract TriviaData Create(SyntaxToken token1, SyntaxToken token2); } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Compilers/Core/Portable/CommandLine/SarifErrorLogger.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; using System.Globalization; using System.IO; using System.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Base class for the <see cref="SarifV1ErrorLogger"/> and <see cref="SarifV2ErrorLogger"/> classes. /// The SarifV2ErrorLogger produces the standardized SARIF v2.1.0. The SarifV1ErrorLogger produces /// the non-standardized SARIF v1.0.0. It is retained (and in fact, is retained as the default) /// for compatibility with previous versions of the compiler. Customers who want to integrate /// with standardized SARIF tooling should specify /errorlog:logFilePath;version=2 on the command /// line to produce SARIF v2.1.0. /// </summary> internal abstract class SarifErrorLogger : ErrorLogger, IDisposable { protected JsonWriter _writer { get; } protected CultureInfo _culture { get; } protected SarifErrorLogger(Stream stream, CultureInfo culture) { Debug.Assert(stream != null); Debug.Assert(stream!.Position == 0); _writer = new JsonWriter(new StreamWriter(stream)); _culture = culture; } // protected abstract string PrimaryLocationPropertyName { get; } protected abstract void WritePhysicalLocation(Location diagnosticLocation); public virtual void Dispose() { _writer.Dispose(); } protected void WriteRegion(FileLinePositionSpan span) { // Note that SARIF lines and columns are 1-based, but FileLinePositionSpan is 0-based _writer.WriteObjectStart("region"); _writer.Write("startLine", span.StartLinePosition.Line + 1); _writer.Write("startColumn", span.StartLinePosition.Character + 1); _writer.Write("endLine", span.EndLinePosition.Line + 1); _writer.Write("endColumn", span.EndLinePosition.Character + 1); _writer.WriteObjectEnd(); // region } protected static string GetLevel(DiagnosticSeverity severity) { switch (severity) { case DiagnosticSeverity.Info: return "note"; case DiagnosticSeverity.Error: return "error"; case DiagnosticSeverity.Warning: return "warning"; case DiagnosticSeverity.Hidden: default: // hidden diagnostics are not reported on the command line and therefore not currently given to // the error logger. We could represent it with a custom property in the SARIF log if that changes. Debug.Assert(false); goto case DiagnosticSeverity.Warning; } } protected void WriteResultProperties(Diagnostic diagnostic) { // Currently, the following are always inherited from the descriptor and therefore will be // captured as rule metadata and need not be logged here. IsWarningAsError is also omitted // because it can be inferred from level vs. defaultLevel in the log. Debug.Assert(diagnostic.CustomTags.SequenceEqual(diagnostic.Descriptor.ImmutableCustomTags)); Debug.Assert(diagnostic.Category == diagnostic.Descriptor.Category); Debug.Assert(diagnostic.DefaultSeverity == diagnostic.Descriptor.DefaultSeverity); Debug.Assert(diagnostic.IsEnabledByDefault == diagnostic.Descriptor.IsEnabledByDefault); if (diagnostic.WarningLevel > 0 || diagnostic.Properties.Count > 0) { _writer.WriteObjectStart("properties"); if (diagnostic.WarningLevel > 0) { _writer.Write("warningLevel", diagnostic.WarningLevel); } if (diagnostic.Properties.Count > 0) { _writer.WriteObjectStart("customProperties"); foreach (var pair in diagnostic.Properties.OrderBy(x => x.Key, StringComparer.Ordinal)) { _writer.Write(pair.Key, pair.Value); } _writer.WriteObjectEnd(); } _writer.WriteObjectEnd(); // properties } } protected static bool HasPath(Location location) { return !string.IsNullOrEmpty(location.GetLineSpan().Path); } private static readonly Uri s_fileRoot = new Uri("file:///"); protected static string GetUri(string path) { Debug.Assert(!string.IsNullOrEmpty(path)); // Note that in general, these "paths" are opaque strings to be // interpreted by resolvers (see SyntaxTree.FilePath documentation). // Common case: absolute path -> absolute URI if (Path.IsPathRooted(path)) { // N.B. URI does not handle multiple backslashes or `..` well, so call GetFullPath // to normalize before going to URI var fullPath = Path.GetFullPath(path); if (Uri.TryCreate(fullPath, UriKind.Absolute, out var uri)) { // We use Uri.AbsoluteUri and not Uri.ToString() because Uri.ToString() // is unescaped (e.g. spaces remain unreplaced by %20) and therefore // not well-formed. return uri.AbsoluteUri; } } else { // Attempt to normalize the directory separators if (!PathUtilities.IsUnixLikePlatform) { path = path.Replace(@"\\", @"\"); path = PathUtilities.NormalizeWithForwardSlash(path); } if (Uri.TryCreate(path, UriKind.Relative, out var uri)) { // First fallback attempt: attempt to interpret as relative path/URI. // (Perhaps the resolver works that way.) // There is no AbsoluteUri equivalent for relative URI references and ToString() // won't escape without this relative -> absolute -> relative trick. return s_fileRoot.MakeRelativeUri(new Uri(s_fileRoot, uri)).ToString(); } } // Last resort: UrlEncode the whole opaque string. return System.Net.WebUtility.UrlEncode(path); } } }
// Licensed to the .NET Foundation under one or more 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; using System.Globalization; using System.IO; using System.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Base class for the <see cref="SarifV1ErrorLogger"/> and <see cref="SarifV2ErrorLogger"/> classes. /// The SarifV2ErrorLogger produces the standardized SARIF v2.1.0. The SarifV1ErrorLogger produces /// the non-standardized SARIF v1.0.0. It is retained (and in fact, is retained as the default) /// for compatibility with previous versions of the compiler. Customers who want to integrate /// with standardized SARIF tooling should specify /errorlog:logFilePath;version=2 on the command /// line to produce SARIF v2.1.0. /// </summary> internal abstract class SarifErrorLogger : ErrorLogger, IDisposable { protected JsonWriter _writer { get; } protected CultureInfo _culture { get; } protected SarifErrorLogger(Stream stream, CultureInfo culture) { Debug.Assert(stream != null); Debug.Assert(stream!.Position == 0); _writer = new JsonWriter(new StreamWriter(stream)); _culture = culture; } // protected abstract string PrimaryLocationPropertyName { get; } protected abstract void WritePhysicalLocation(Location diagnosticLocation); public virtual void Dispose() { _writer.Dispose(); } protected void WriteRegion(FileLinePositionSpan span) { // Note that SARIF lines and columns are 1-based, but FileLinePositionSpan is 0-based _writer.WriteObjectStart("region"); _writer.Write("startLine", span.StartLinePosition.Line + 1); _writer.Write("startColumn", span.StartLinePosition.Character + 1); _writer.Write("endLine", span.EndLinePosition.Line + 1); _writer.Write("endColumn", span.EndLinePosition.Character + 1); _writer.WriteObjectEnd(); // region } protected static string GetLevel(DiagnosticSeverity severity) { switch (severity) { case DiagnosticSeverity.Info: return "note"; case DiagnosticSeverity.Error: return "error"; case DiagnosticSeverity.Warning: return "warning"; case DiagnosticSeverity.Hidden: default: // hidden diagnostics are not reported on the command line and therefore not currently given to // the error logger. We could represent it with a custom property in the SARIF log if that changes. Debug.Assert(false); goto case DiagnosticSeverity.Warning; } } protected void WriteResultProperties(Diagnostic diagnostic) { // Currently, the following are always inherited from the descriptor and therefore will be // captured as rule metadata and need not be logged here. IsWarningAsError is also omitted // because it can be inferred from level vs. defaultLevel in the log. Debug.Assert(diagnostic.CustomTags.SequenceEqual(diagnostic.Descriptor.ImmutableCustomTags)); Debug.Assert(diagnostic.Category == diagnostic.Descriptor.Category); Debug.Assert(diagnostic.DefaultSeverity == diagnostic.Descriptor.DefaultSeverity); Debug.Assert(diagnostic.IsEnabledByDefault == diagnostic.Descriptor.IsEnabledByDefault); if (diagnostic.WarningLevel > 0 || diagnostic.Properties.Count > 0) { _writer.WriteObjectStart("properties"); if (diagnostic.WarningLevel > 0) { _writer.Write("warningLevel", diagnostic.WarningLevel); } if (diagnostic.Properties.Count > 0) { _writer.WriteObjectStart("customProperties"); foreach (var pair in diagnostic.Properties.OrderBy(x => x.Key, StringComparer.Ordinal)) { _writer.Write(pair.Key, pair.Value); } _writer.WriteObjectEnd(); } _writer.WriteObjectEnd(); // properties } } protected static bool HasPath(Location location) { return !string.IsNullOrEmpty(location.GetLineSpan().Path); } private static readonly Uri s_fileRoot = new Uri("file:///"); protected static string GetUri(string path) { Debug.Assert(!string.IsNullOrEmpty(path)); // Note that in general, these "paths" are opaque strings to be // interpreted by resolvers (see SyntaxTree.FilePath documentation). // Common case: absolute path -> absolute URI if (Path.IsPathRooted(path)) { // N.B. URI does not handle multiple backslashes or `..` well, so call GetFullPath // to normalize before going to URI var fullPath = Path.GetFullPath(path); if (Uri.TryCreate(fullPath, UriKind.Absolute, out var uri)) { // We use Uri.AbsoluteUri and not Uri.ToString() because Uri.ToString() // is unescaped (e.g. spaces remain unreplaced by %20) and therefore // not well-formed. return uri.AbsoluteUri; } } else { // Attempt to normalize the directory separators if (!PathUtilities.IsUnixLikePlatform) { path = path.Replace(@"\\", @"\"); path = PathUtilities.NormalizeWithForwardSlash(path); } if (Uri.TryCreate(path, UriKind.Relative, out var uri)) { // First fallback attempt: attempt to interpret as relative path/URI. // (Perhaps the resolver works that way.) // There is no AbsoluteUri equivalent for relative URI references and ToString() // won't escape without this relative -> absolute -> relative trick. return s_fileRoot.MakeRelativeUri(new Uri(s_fileRoot, uri)).ToString(); } } // Last resort: UrlEncode the whole opaque string. return System.Net.WebUtility.UrlEncode(path); } } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Analyzers/VisualBasic/Analyzers/ValidateFormatString/VisualBasicValidateFormatStringDiagnosticAnalyzer.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.Diagnostics Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.ValidateFormatString Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.ValidateFormatString <DiagnosticAnalyzer(LanguageNames.VisualBasic)> Friend Class VisualBasicValidateFormatStringDiagnosticAnalyzer Inherits AbstractValidateFormatStringDiagnosticAnalyzer(Of SyntaxKind) Protected Overrides Function GetSyntaxFacts() As ISyntaxFacts Return VisualBasicSyntaxFacts.Instance End Function Protected Overrides Function TryGetMatchingNamedArgument( arguments As SeparatedSyntaxList(Of SyntaxNode), searchArgumentName As String) As SyntaxNode For Each argument In arguments Dim simpleArgumentSyntax = TryCast(argument, SimpleArgumentSyntax) If Not simpleArgumentSyntax Is Nothing AndAlso simpleArgumentSyntax.NameColonEquals?.Name.Identifier.ValueText.Equals(searchArgumentName) Then Return argument End If Next Return Nothing End Function Protected Overrides Function GetArgumentExpression(syntaxNode As SyntaxNode) As SyntaxNode Return DirectCast(syntaxNode, ArgumentSyntax).GetArgumentExpression 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 Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.ValidateFormatString Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.ValidateFormatString <DiagnosticAnalyzer(LanguageNames.VisualBasic)> Friend Class VisualBasicValidateFormatStringDiagnosticAnalyzer Inherits AbstractValidateFormatStringDiagnosticAnalyzer(Of SyntaxKind) Protected Overrides Function GetSyntaxFacts() As ISyntaxFacts Return VisualBasicSyntaxFacts.Instance End Function Protected Overrides Function TryGetMatchingNamedArgument( arguments As SeparatedSyntaxList(Of SyntaxNode), searchArgumentName As String) As SyntaxNode For Each argument In arguments Dim simpleArgumentSyntax = TryCast(argument, SimpleArgumentSyntax) If Not simpleArgumentSyntax Is Nothing AndAlso simpleArgumentSyntax.NameColonEquals?.Name.Identifier.ValueText.Equals(searchArgumentName) Then Return argument End If Next Return Nothing End Function Protected Overrides Function GetArgumentExpression(syntaxNode As SyntaxNode) As SyntaxNode Return DirectCast(syntaxNode, ArgumentSyntax).GetArgumentExpression End Function End Class End Namespace
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Features/VisualBasic/Portable/GenerateDefaultConstructors/VisualBasicGenerateDefaultConstructorsService.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.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.GenerateDefaultConstructors Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.GenerateDefaultConstructors <ExportLanguageService(GetType(IGenerateDefaultConstructorsService), LanguageNames.VisualBasic), [Shared]> Partial Friend Class VisualBasicGenerateDefaultConstructorsService Inherits AbstractGenerateDefaultConstructorsService(Of VisualBasicGenerateDefaultConstructorsService) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overrides Function TryInitializeState( semanticDocument As SemanticDocument, textSpan As TextSpan, cancellationToken As CancellationToken, ByRef classType As INamedTypeSymbol) As Boolean cancellationToken.ThrowIfCancellationRequested() ' Offer the feature if we're on the header for the class/struct, or if we're on the ' first base-type of a class. Dim syntaxFacts = semanticDocument.Document.GetLanguageService(Of ISyntaxFactsService)() Dim typeDecl As SyntaxNode = Nothing If syntaxFacts.IsOnTypeHeader(semanticDocument.Root, textSpan.Start, typeDecl) Then classType = TryCast(semanticDocument.SemanticModel.GetDeclaredSymbol(typeDecl), INamedTypeSymbol) Return classType IsNot Nothing AndAlso classType.TypeKind = TypeKind.Class End If Dim token = semanticDocument.Root.FindToken(textSpan.Start) Dim type = token.GetAncestor(Of TypeSyntax)() If type IsNot Nothing AndAlso type.IsParentKind(SyntaxKind.InheritsStatement) Then Dim baseList = DirectCast(type.Parent, InheritsStatementSyntax) If baseList.Types.Count > 0 AndAlso baseList.Types(0) Is type AndAlso baseList.IsParentKind(SyntaxKind.ClassBlock) Then classType = TryCast(semanticDocument.SemanticModel.GetDeclaredSymbol(baseList.Parent, cancellationToken), INamedTypeSymbol) Return classType IsNot Nothing End If End If classType = Nothing Return False 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.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.GenerateDefaultConstructors Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.GenerateDefaultConstructors <ExportLanguageService(GetType(IGenerateDefaultConstructorsService), LanguageNames.VisualBasic), [Shared]> Partial Friend Class VisualBasicGenerateDefaultConstructorsService Inherits AbstractGenerateDefaultConstructorsService(Of VisualBasicGenerateDefaultConstructorsService) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overrides Function TryInitializeState( semanticDocument As SemanticDocument, textSpan As TextSpan, cancellationToken As CancellationToken, ByRef classType As INamedTypeSymbol) As Boolean cancellationToken.ThrowIfCancellationRequested() ' Offer the feature if we're on the header for the class/struct, or if we're on the ' first base-type of a class. Dim syntaxFacts = semanticDocument.Document.GetLanguageService(Of ISyntaxFactsService)() Dim typeDecl As SyntaxNode = Nothing If syntaxFacts.IsOnTypeHeader(semanticDocument.Root, textSpan.Start, typeDecl) Then classType = TryCast(semanticDocument.SemanticModel.GetDeclaredSymbol(typeDecl), INamedTypeSymbol) Return classType IsNot Nothing AndAlso classType.TypeKind = TypeKind.Class End If Dim token = semanticDocument.Root.FindToken(textSpan.Start) Dim type = token.GetAncestor(Of TypeSyntax)() If type IsNot Nothing AndAlso type.IsParentKind(SyntaxKind.InheritsStatement) Then Dim baseList = DirectCast(type.Parent, InheritsStatementSyntax) If baseList.Types.Count > 0 AndAlso baseList.Types(0) Is type AndAlso baseList.IsParentKind(SyntaxKind.ClassBlock) Then classType = TryCast(semanticDocument.SemanticModel.GetDeclaredSymbol(baseList.Parent, cancellationToken), INamedTypeSymbol) Return classType IsNot Nothing End If End If classType = Nothing Return False End Function End Class End Namespace
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/EditorFeatures/Core/Implementation/EditAndContinue/EditAndContinueHostWorkspaceEventListener.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.EditAndContinue; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue { /// <summary> /// Notifies EnC service of host workspace events. /// </summary> [ExportEventListener(WellKnownEventListeners.Workspace, WorkspaceKind.Host), Shared] internal sealed class EditAndContinueHostWorkspaceEventListener : IEventListener<object>, IEventListenerStoppable { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public EditAndContinueHostWorkspaceEventListener() { } public void StartListening(Workspace workspace, object serviceOpt) { workspace.DocumentOpened += WorkspaceDocumentOpened; } public void StopListening(Workspace workspace) { workspace.DocumentOpened -= WorkspaceDocumentOpened; } private void WorkspaceDocumentOpened(object? sender, DocumentEventArgs e) { var proxy = new RemoteEditAndContinueServiceProxy(e.Document.Project.Solution.Workspace); _ = Task.Run(() => proxy.OnSourceFileUpdatedAsync(e.Document, CancellationToken.None)).ReportNonFatalErrorAsync(); } } }
// Licensed to the .NET Foundation under one or more 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.EditAndContinue; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue { /// <summary> /// Notifies EnC service of host workspace events. /// </summary> [ExportEventListener(WellKnownEventListeners.Workspace, WorkspaceKind.Host), Shared] internal sealed class EditAndContinueHostWorkspaceEventListener : IEventListener<object>, IEventListenerStoppable { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public EditAndContinueHostWorkspaceEventListener() { } public void StartListening(Workspace workspace, object serviceOpt) { workspace.DocumentOpened += WorkspaceDocumentOpened; } public void StopListening(Workspace workspace) { workspace.DocumentOpened -= WorkspaceDocumentOpened; } private void WorkspaceDocumentOpened(object? sender, DocumentEventArgs e) { var proxy = new RemoteEditAndContinueServiceProxy(e.Document.Project.Solution.Workspace); _ = Task.Run(() => proxy.OnSourceFileUpdatedAsync(e.Document, CancellationToken.None)).ReportNonFatalErrorAsync(); } } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Compilers/CSharp/Portable/Symbols/TypeUnification.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.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal static class TypeUnification { /// <summary> /// Determine whether there is any substitution of type parameters that will /// make two types identical. /// </summary> public static bool CanUnify(TypeSymbol t1, TypeSymbol t2) { if (TypeSymbol.Equals(t1, t2, TypeCompareKind.CLRSignatureCompareOptions)) { return true; } MutableTypeMap? substitution = null; bool result = CanUnifyHelper(t1, t2, ref substitution); #if DEBUG if (result && ((object)t1 != null && (object)t2 != null)) { var substituted1 = SubstituteAllTypeParameters(substitution, TypeWithAnnotations.Create(t1)); var substituted2 = SubstituteAllTypeParameters(substitution, TypeWithAnnotations.Create(t2)); Debug.Assert(substituted1.Type.Equals(substituted2.Type, TypeCompareKind.CLRSignatureCompareOptions)); Debug.Assert(substituted1.CustomModifiers.SequenceEqual(substituted2.CustomModifiers)); } #endif return result; } #if DEBUG private static TypeWithAnnotations SubstituteAllTypeParameters(AbstractTypeMap? substitution, TypeWithAnnotations type) { if (substitution != null) { TypeWithAnnotations previous; do { previous = type; type = type.SubstituteType(substitution); } while (!type.IsSameAs(previous)); } return type; } #endif private static bool CanUnifyHelper(TypeSymbol t1, TypeSymbol t2, ref MutableTypeMap? substitution) { return CanUnifyHelper(TypeWithAnnotations.Create(t1), TypeWithAnnotations.Create(t2), ref substitution); } /// <summary> /// Determine whether there is any substitution of type parameters that will /// make two types identical. /// </summary> /// <param name="t1">LHS</param> /// <param name="t2">RHS</param> /// <param name="substitution"> /// Substitutions performed so far (or null for none). /// Keys are type parameters, values are types (possibly type parameters). /// Will be updated with new substitutions by the callee. /// Should be ignored when false is returned. /// </param> /// <returns>True if there exists a type map such that Map(LHS) == Map(RHS).</returns> /// <remarks> /// Derived from Dev10's BSYMMGR::UnifyTypes. /// Two types will not unify if they have different custom modifiers. /// </remarks> private static bool CanUnifyHelper(TypeWithAnnotations t1, TypeWithAnnotations t2, ref MutableTypeMap? substitution) { if (!t1.HasType || !t2.HasType) { return t1.IsSameAs(t2); } if (substitution != null) { t1 = t1.SubstituteType(substitution); t2 = t2.SubstituteType(substitution); } if (TypeSymbol.Equals(t1.Type, t2.Type, TypeCompareKind.CLRSignatureCompareOptions) && t1.CustomModifiers.SequenceEqual(t2.CustomModifiers)) { return true; } // We can avoid a lot of redundant checks if we ensure that we only have to check // for type parameters on the LHS if (!t1.Type.IsTypeParameter() && t2.Type.IsTypeParameter()) { TypeWithAnnotations tmp = t1; t1 = t2; t2 = tmp; } // If t1 is not a type parameter, then neither is t2 Debug.Assert(t1.Type.IsTypeParameter() || !t2.Type.IsTypeParameter()); switch (t1.Type.Kind) { case SymbolKind.ArrayType: { if (t2.TypeKind != t1.TypeKind || !t2.CustomModifiers.SequenceEqual(t1.CustomModifiers)) { return false; } ArrayTypeSymbol at1 = (ArrayTypeSymbol)t1.Type; ArrayTypeSymbol at2 = (ArrayTypeSymbol)t2.Type; if (!at1.HasSameShapeAs(at2)) { return false; } return CanUnifyHelper(at1.ElementTypeWithAnnotations, at2.ElementTypeWithAnnotations, ref substitution); } case SymbolKind.PointerType: { if (t2.TypeKind != t1.TypeKind || !t2.CustomModifiers.SequenceEqual(t1.CustomModifiers)) { return false; } PointerTypeSymbol pt1 = (PointerTypeSymbol)t1.Type; PointerTypeSymbol pt2 = (PointerTypeSymbol)t2.Type; return CanUnifyHelper(pt1.PointedAtTypeWithAnnotations, pt2.PointedAtTypeWithAnnotations, ref substitution); } case SymbolKind.NamedType: case SymbolKind.ErrorType: { if (t2.TypeKind != t1.TypeKind || !t2.CustomModifiers.SequenceEqual(t1.CustomModifiers)) { return false; } NamedTypeSymbol nt1 = (NamedTypeSymbol)t1.Type; NamedTypeSymbol nt2 = (NamedTypeSymbol)t2.Type; if (!nt1.IsGenericType || !nt2.IsGenericType) { // Initial TypeSymbol.Equals(...) && CustomModifiers.SequenceEqual(...) failed above, // and custom modifiers compared equal in this case block, so the types must be distinct. Debug.Assert(!nt1.Equals(nt2, TypeCompareKind.CLRSignatureCompareOptions)); return false; } int arity = nt1.Arity; if (nt2.Arity != arity || !TypeSymbol.Equals(nt2.OriginalDefinition, nt1.OriginalDefinition, TypeCompareKind.ConsiderEverything)) { return false; } var nt1Arguments = nt1.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; var nt2Arguments = nt2.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; for (int i = 0; i < arity; i++) { if (!CanUnifyHelper(nt1Arguments[i], nt2Arguments[i], ref substitution)) { return false; } } // Note: Dev10 folds this into the loop since GetTypeArgsAll includes type args for containing types // TODO: Calling CanUnifyHelper for the containing type is an overkill, we simply need to go through type arguments for all containers. return (object)nt1.ContainingType == null || CanUnifyHelper(nt1.ContainingType, nt2.ContainingType, ref substitution); } case SymbolKind.TypeParameter: { // These substitutions are not allowed in C# if (t2.Type.IsPointerOrFunctionPointer() || t2.IsVoidType()) { return false; } TypeParameterSymbol tp1 = (TypeParameterSymbol)t1.Type; // Perform the "occurs check" - i.e. ensure that t2 doesn't contain t1 to avoid recursive types // Note: t2 can't be the same type param - we would have caught that with ReferenceEquals above if (Contains(t2.Type, tp1)) { return false; } if (t1.CustomModifiers.IsDefaultOrEmpty) { AddSubstitution(ref substitution, tp1, t2); return true; } if (t1.CustomModifiers.SequenceEqual(t2.CustomModifiers)) { AddSubstitution(ref substitution, tp1, TypeWithAnnotations.Create(t2.Type)); return true; } if (t1.CustomModifiers.Length < t2.CustomModifiers.Length && t1.CustomModifiers.SequenceEqual(t2.CustomModifiers.Take(t1.CustomModifiers.Length))) { AddSubstitution(ref substitution, tp1, TypeWithAnnotations.Create(t2.Type, customModifiers: ImmutableArray.Create(t2.CustomModifiers, t1.CustomModifiers.Length, t2.CustomModifiers.Length - t1.CustomModifiers.Length))); return true; } if (t2.Type.IsTypeParameter()) { var tp2 = (TypeParameterSymbol)t2.Type; if (t2.CustomModifiers.IsDefaultOrEmpty) { AddSubstitution(ref substitution, tp2, t1); return true; } if (t2.CustomModifiers.Length < t1.CustomModifiers.Length && t2.CustomModifiers.SequenceEqual(t1.CustomModifiers.Take(t2.CustomModifiers.Length))) { AddSubstitution(ref substitution, tp2, TypeWithAnnotations.Create(t1.Type, customModifiers: ImmutableArray.Create(t1.CustomModifiers, t2.CustomModifiers.Length, t1.CustomModifiers.Length - t2.CustomModifiers.Length))); return true; } } return false; } default: { return false; } } } private static void AddSubstitution(ref MutableTypeMap? substitution, TypeParameterSymbol tp1, TypeWithAnnotations t2) { if (substitution == null) { substitution = new MutableTypeMap(); } // MutableTypeMap.Add will throw if the key has already been added. However, // if t1 was already in the substitution, it would have been substituted at the // start of CanUnifyHelper and we wouldn't be here. substitution.Add(tp1, t2); } /// <summary> /// Return true if the given type contains the specified type parameter. /// </summary> private static bool Contains(TypeSymbol type, TypeParameterSymbol typeParam) { switch (type.Kind) { case SymbolKind.ArrayType: return Contains(((ArrayTypeSymbol)type).ElementType, typeParam); case SymbolKind.PointerType: return Contains(((PointerTypeSymbol)type).PointedAtType, typeParam); case SymbolKind.NamedType: case SymbolKind.ErrorType: { NamedTypeSymbol namedType = (NamedTypeSymbol)type; while ((object)namedType != null) { var typeParts = namedType.IsTupleType ? namedType.TupleElementTypesWithAnnotations : namedType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; foreach (TypeWithAnnotations typePart in typeParts) { if (Contains(typePart.Type, typeParam)) { return true; } } namedType = namedType.ContainingType; } return false; } case SymbolKind.TypeParameter: return TypeSymbol.Equals(type, typeParam, TypeCompareKind.ConsiderEverything); 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.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal static class TypeUnification { /// <summary> /// Determine whether there is any substitution of type parameters that will /// make two types identical. /// </summary> public static bool CanUnify(TypeSymbol t1, TypeSymbol t2) { if (TypeSymbol.Equals(t1, t2, TypeCompareKind.CLRSignatureCompareOptions)) { return true; } MutableTypeMap? substitution = null; bool result = CanUnifyHelper(t1, t2, ref substitution); #if DEBUG if (result && ((object)t1 != null && (object)t2 != null)) { var substituted1 = SubstituteAllTypeParameters(substitution, TypeWithAnnotations.Create(t1)); var substituted2 = SubstituteAllTypeParameters(substitution, TypeWithAnnotations.Create(t2)); Debug.Assert(substituted1.Type.Equals(substituted2.Type, TypeCompareKind.CLRSignatureCompareOptions)); Debug.Assert(substituted1.CustomModifiers.SequenceEqual(substituted2.CustomModifiers)); } #endif return result; } #if DEBUG private static TypeWithAnnotations SubstituteAllTypeParameters(AbstractTypeMap? substitution, TypeWithAnnotations type) { if (substitution != null) { TypeWithAnnotations previous; do { previous = type; type = type.SubstituteType(substitution); } while (!type.IsSameAs(previous)); } return type; } #endif private static bool CanUnifyHelper(TypeSymbol t1, TypeSymbol t2, ref MutableTypeMap? substitution) { return CanUnifyHelper(TypeWithAnnotations.Create(t1), TypeWithAnnotations.Create(t2), ref substitution); } /// <summary> /// Determine whether there is any substitution of type parameters that will /// make two types identical. /// </summary> /// <param name="t1">LHS</param> /// <param name="t2">RHS</param> /// <param name="substitution"> /// Substitutions performed so far (or null for none). /// Keys are type parameters, values are types (possibly type parameters). /// Will be updated with new substitutions by the callee. /// Should be ignored when false is returned. /// </param> /// <returns>True if there exists a type map such that Map(LHS) == Map(RHS).</returns> /// <remarks> /// Derived from Dev10's BSYMMGR::UnifyTypes. /// Two types will not unify if they have different custom modifiers. /// </remarks> private static bool CanUnifyHelper(TypeWithAnnotations t1, TypeWithAnnotations t2, ref MutableTypeMap? substitution) { if (!t1.HasType || !t2.HasType) { return t1.IsSameAs(t2); } if (substitution != null) { t1 = t1.SubstituteType(substitution); t2 = t2.SubstituteType(substitution); } if (TypeSymbol.Equals(t1.Type, t2.Type, TypeCompareKind.CLRSignatureCompareOptions) && t1.CustomModifiers.SequenceEqual(t2.CustomModifiers)) { return true; } // We can avoid a lot of redundant checks if we ensure that we only have to check // for type parameters on the LHS if (!t1.Type.IsTypeParameter() && t2.Type.IsTypeParameter()) { TypeWithAnnotations tmp = t1; t1 = t2; t2 = tmp; } // If t1 is not a type parameter, then neither is t2 Debug.Assert(t1.Type.IsTypeParameter() || !t2.Type.IsTypeParameter()); switch (t1.Type.Kind) { case SymbolKind.ArrayType: { if (t2.TypeKind != t1.TypeKind || !t2.CustomModifiers.SequenceEqual(t1.CustomModifiers)) { return false; } ArrayTypeSymbol at1 = (ArrayTypeSymbol)t1.Type; ArrayTypeSymbol at2 = (ArrayTypeSymbol)t2.Type; if (!at1.HasSameShapeAs(at2)) { return false; } return CanUnifyHelper(at1.ElementTypeWithAnnotations, at2.ElementTypeWithAnnotations, ref substitution); } case SymbolKind.PointerType: { if (t2.TypeKind != t1.TypeKind || !t2.CustomModifiers.SequenceEqual(t1.CustomModifiers)) { return false; } PointerTypeSymbol pt1 = (PointerTypeSymbol)t1.Type; PointerTypeSymbol pt2 = (PointerTypeSymbol)t2.Type; return CanUnifyHelper(pt1.PointedAtTypeWithAnnotations, pt2.PointedAtTypeWithAnnotations, ref substitution); } case SymbolKind.NamedType: case SymbolKind.ErrorType: { if (t2.TypeKind != t1.TypeKind || !t2.CustomModifiers.SequenceEqual(t1.CustomModifiers)) { return false; } NamedTypeSymbol nt1 = (NamedTypeSymbol)t1.Type; NamedTypeSymbol nt2 = (NamedTypeSymbol)t2.Type; if (!nt1.IsGenericType || !nt2.IsGenericType) { // Initial TypeSymbol.Equals(...) && CustomModifiers.SequenceEqual(...) failed above, // and custom modifiers compared equal in this case block, so the types must be distinct. Debug.Assert(!nt1.Equals(nt2, TypeCompareKind.CLRSignatureCompareOptions)); return false; } int arity = nt1.Arity; if (nt2.Arity != arity || !TypeSymbol.Equals(nt2.OriginalDefinition, nt1.OriginalDefinition, TypeCompareKind.ConsiderEverything)) { return false; } var nt1Arguments = nt1.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; var nt2Arguments = nt2.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; for (int i = 0; i < arity; i++) { if (!CanUnifyHelper(nt1Arguments[i], nt2Arguments[i], ref substitution)) { return false; } } // Note: Dev10 folds this into the loop since GetTypeArgsAll includes type args for containing types // TODO: Calling CanUnifyHelper for the containing type is an overkill, we simply need to go through type arguments for all containers. return (object)nt1.ContainingType == null || CanUnifyHelper(nt1.ContainingType, nt2.ContainingType, ref substitution); } case SymbolKind.TypeParameter: { // These substitutions are not allowed in C# if (t2.Type.IsPointerOrFunctionPointer() || t2.IsVoidType()) { return false; } TypeParameterSymbol tp1 = (TypeParameterSymbol)t1.Type; // Perform the "occurs check" - i.e. ensure that t2 doesn't contain t1 to avoid recursive types // Note: t2 can't be the same type param - we would have caught that with ReferenceEquals above if (Contains(t2.Type, tp1)) { return false; } if (t1.CustomModifiers.IsDefaultOrEmpty) { AddSubstitution(ref substitution, tp1, t2); return true; } if (t1.CustomModifiers.SequenceEqual(t2.CustomModifiers)) { AddSubstitution(ref substitution, tp1, TypeWithAnnotations.Create(t2.Type)); return true; } if (t1.CustomModifiers.Length < t2.CustomModifiers.Length && t1.CustomModifiers.SequenceEqual(t2.CustomModifiers.Take(t1.CustomModifiers.Length))) { AddSubstitution(ref substitution, tp1, TypeWithAnnotations.Create(t2.Type, customModifiers: ImmutableArray.Create(t2.CustomModifiers, t1.CustomModifiers.Length, t2.CustomModifiers.Length - t1.CustomModifiers.Length))); return true; } if (t2.Type.IsTypeParameter()) { var tp2 = (TypeParameterSymbol)t2.Type; if (t2.CustomModifiers.IsDefaultOrEmpty) { AddSubstitution(ref substitution, tp2, t1); return true; } if (t2.CustomModifiers.Length < t1.CustomModifiers.Length && t2.CustomModifiers.SequenceEqual(t1.CustomModifiers.Take(t2.CustomModifiers.Length))) { AddSubstitution(ref substitution, tp2, TypeWithAnnotations.Create(t1.Type, customModifiers: ImmutableArray.Create(t1.CustomModifiers, t2.CustomModifiers.Length, t1.CustomModifiers.Length - t2.CustomModifiers.Length))); return true; } } return false; } default: { return false; } } } private static void AddSubstitution(ref MutableTypeMap? substitution, TypeParameterSymbol tp1, TypeWithAnnotations t2) { if (substitution == null) { substitution = new MutableTypeMap(); } // MutableTypeMap.Add will throw if the key has already been added. However, // if t1 was already in the substitution, it would have been substituted at the // start of CanUnifyHelper and we wouldn't be here. substitution.Add(tp1, t2); } /// <summary> /// Return true if the given type contains the specified type parameter. /// </summary> private static bool Contains(TypeSymbol type, TypeParameterSymbol typeParam) { switch (type.Kind) { case SymbolKind.ArrayType: return Contains(((ArrayTypeSymbol)type).ElementType, typeParam); case SymbolKind.PointerType: return Contains(((PointerTypeSymbol)type).PointedAtType, typeParam); case SymbolKind.NamedType: case SymbolKind.ErrorType: { NamedTypeSymbol namedType = (NamedTypeSymbol)type; while ((object)namedType != null) { var typeParts = namedType.IsTupleType ? namedType.TupleElementTypesWithAnnotations : namedType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; foreach (TypeWithAnnotations typePart in typeParts) { if (Contains(typePart.Type, typeParam)) { return true; } } namedType = namedType.ContainingType; } return false; } case SymbolKind.TypeParameter: return TypeSymbol.Equals(type, typeParam, TypeCompareKind.ConsiderEverything); default: return false; } } } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Compilers/CSharp/Test/Emit/Emit/EditAndContinue/SymbolMatcherTests.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 System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { public class SymbolMatcherTests : EditAndContinueTestBase { private static PEAssemblySymbol CreatePEAssemblySymbol(string source) { var compilation = CreateCompilation(source, options: TestOptions.DebugDll); var reference = compilation.EmitToImageReference(); return (PEAssemblySymbol)CreateCompilation("", new[] { reference }).GetReferencedAssemblySymbol(reference); } [Fact] public void ConcurrentAccess() { var source = @"class A { B F; D P { get; set; } void M(A a, B b, S s, I i) { } delegate void D(S s); class B { } struct S { } interface I { } } class B { A M<T, U>() where T : A where U : T, I { return null; } event D E; delegate void D(S s); struct S { } interface I { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var builder = new List<Symbol>(); var type = compilation1.GetMember<NamedTypeSymbol>("A"); builder.Add(type); builder.AddRange(type.GetMembers()); type = compilation1.GetMember<NamedTypeSymbol>("B"); builder.Add(type); builder.AddRange(type.GetMembers()); var members = builder.ToImmutableArray(); Assert.True(members.Length > 10); for (int i = 0; i < 10; i++) { var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var tasks = new Task[10]; for (int j = 0; j < tasks.Length; j++) { int startAt = i + j + 1; tasks[j] = Task.Run(() => { MatchAll(matcher, members, startAt); Thread.Sleep(10); }); } Task.WaitAll(tasks); } } private static void MatchAll(CSharpSymbolMatcher matcher, ImmutableArray<Symbol> members, int startAt) { int n = members.Length; for (int i = 0; i < n; i++) { var member = members[(i + startAt) % n]; var other = matcher.MapDefinition((Cci.IDefinition)member.GetCciAdapter()); Assert.NotNull(other); } } [Fact] public void TypeArguments() { const string source = @"class A<T> { class B<U> { static A<V> M<V>(A<U>.B<T> x, A<object>.S y) { return null; } static A<V> M<V>(A<U>.B<T> x, A<V>.S y) { return null; } } struct S { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var members = compilation1.GetMember<NamedTypeSymbol>("A.B").GetMembers("M"); Assert.Equal(2, members.Length); foreach (var member in members) { var other = matcher.MapDefinition((Cci.IMethodDefinition)member.GetCciAdapter()); Assert.NotNull(other); } } [Fact] public void Constraints() { const string source = @"interface I<T> where T : I<T> { } class C { static void M<T>(I<T> o) where T : I<T> { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<MethodSymbol>("C.M"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } [Fact] public void CustomModifiers() { var ilSource = @".class public abstract A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public abstract virtual instance object modopt(A) [] F(int32 modopt(object) *p) { } }"; var metadataRef = CompileIL(ilSource); var source = @"unsafe class B : A { public override object[] F(int* p) { return null; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, references: new[] { metadataRef }); var compilation1 = compilation0.WithSource(source); var member1 = compilation1.GetMember<MethodSymbol>("B.F"); Assert.Equal(1, ((PointerTypeSymbol)member1.Parameters[0].Type).PointedAtTypeWithAnnotations.CustomModifiers.Length); Assert.Equal(1, ((ArrayTypeSymbol)member1.ReturnType).ElementTypeWithAnnotations.CustomModifiers.Length); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var other = (MethodSymbol)matcher.MapDefinition(member1.GetCciAdapter()).GetInternalSymbol(); Assert.NotNull(other); Assert.Equal(1, ((PointerTypeSymbol)other.Parameters[0].Type).PointedAtTypeWithAnnotations.CustomModifiers.Length); Assert.Equal(1, ((ArrayTypeSymbol)other.ReturnType).ElementTypeWithAnnotations.CustomModifiers.Length); } [Fact] public void CustomModifiers_InAttribute_Source() { // The parameter is emitted as // int32& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) var source0 = @" abstract class C { // matching public abstract void F(in int x); public virtual void G(in int x) => throw null; // non-matching public void H(in int x) => throw null; }"; var source1 = @" abstract class C { // matching public abstract void F(in int x); public virtual void G(in int x) => throw null; // non-matching public void H(int x) => throw null; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var g0 = compilation0.GetMember<MethodSymbol>("C.G"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var h1 = compilation1.GetMember<MethodSymbol>("C.H"); Assert.Same(f0, (MethodSymbol)matcher.MapDefinition(f1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(g0, (MethodSymbol)matcher.MapDefinition(g1.GetCciAdapter()).GetInternalSymbol()); Assert.Null(matcher.MapDefinition(h1.GetCciAdapter())); } [Fact] public void CustomModifiers_InAttribute_Metadata() { // The parameter is emitted as // int32& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) var source0 = @" abstract class C { // matching public abstract void F(in int x); public virtual void G(in int x) => throw null; // non-matching public void H(in int x) => throw null; }"; var source1 = @" abstract class C { // matching public abstract void F(in int x); public virtual void G(in int x) => throw null; // non-matching public void H(int x) => throw null; }"; var peAssemblySymbol = CreatePEAssemblySymbol(source0); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll).WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, peAssemblySymbol); var f0 = peAssemblySymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember("F"); var g0 = peAssemblySymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember("G"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var h1 = compilation1.GetMember<MethodSymbol>("C.H"); Assert.Equal(f0, (MethodSymbol)matcher.MapDefinition(f1.GetCciAdapter()).GetInternalSymbol()); Assert.Equal(g0, (MethodSymbol)matcher.MapDefinition(g1.GetCciAdapter()).GetInternalSymbol()); Assert.Null(matcher.MapDefinition(h1.GetCciAdapter())); } [ConditionalFact(typeof(DesktopOnly))] public void VaryingCompilationReferences() { string libSource = @" public class D { } "; string source = @" public class C { public void F(D a) {} } "; var lib0 = CreateCompilation(libSource, options: TestOptions.DebugDll, assemblyName: "Lib"); var lib1 = CreateCompilation(libSource, options: TestOptions.DebugDll, assemblyName: "Lib"); var compilation0 = CreateCompilation(source, new[] { lib0.ToMetadataReference() }, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source).WithReferences(MscorlibRef, lib1.ToMetadataReference()); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var mf1 = matcher.MapDefinition(f1.GetCciAdapter()); Assert.Equal(f0, mf1.GetInternalSymbol()); } [WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")] [Fact] public void PreviousType_ArrayType() { var source0 = @" class C { static void M() { int x = 0; } class D {} }"; var source1 = @" class C { static void M() { D[] x = null; } class D {} }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var elementType = compilation1.GetMember<TypeSymbol>("C.D"); var member = compilation1.CreateArrayTypeSymbol(elementType); var other = matcher.MapReference(member.GetCciAdapter()); Assert.NotNull(other); } [WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")] [Fact] public void NoPreviousType_ArrayType() { var source0 = @" class C { static void M() { int x = 0; } }"; var source1 = @" class C { static void M() { D[] x = null; } class D {} }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var elementType = compilation1.GetMember<TypeSymbol>("C.D"); var member = compilation1.CreateArrayTypeSymbol(elementType); var other = matcher.MapReference(member.GetCciAdapter()); // For a newly added type, there is no match in the previous generation. Assert.Null(other); } [WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")] [Fact] public void NoPreviousType_PointerType() { var source0 = @" class C { static void M() { int x = 0; } }"; var source1 = @" class C { static unsafe void M() { D* x = null; } struct D {} }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var elementType = compilation1.GetMember<TypeSymbol>("C.D"); var member = compilation1.CreatePointerTypeSymbol(elementType); var other = matcher.MapReference(member.GetCciAdapter()); // For a newly added type, there is no match in the previous generation. Assert.Null(other); } [WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")] [Fact] public void NoPreviousType_GenericType() { var source0 = @" using System.Collections.Generic; class C { static void M() { int x = 0; } }"; var source1 = @" using System.Collections.Generic; class C { static void M() { List<D> x = null; } class D {} List<D> y; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<FieldSymbol>("C.y"); var other = matcher.MapReference((Cci.ITypeReference)member.Type.GetCciAdapter()); // For a newly added type, there is no match in the previous generation. Assert.Null(other); } [Fact] public void HoistedAnonymousTypes() { var source0 = @" using System; class C { static void F() { var x1 = new { A = 1 }; var x2 = new { B = 1 }; var y = new Func<int>(() => x1.A + x2.B); } } "; var source1 = @" using System; class C { static void F() { var x1 = new { A = 1 }; var x2 = new { b = 1 }; var y = new Func<int>(() => x1.A + x2.b); } }"; var peAssemblySymbol0 = CreatePEAssemblySymbol(source0); var peModule0 = (PEModuleSymbol)peAssemblySymbol0.Modules[0]; var reader0 = peModule0.Module.MetadataReader; var decoder0 = new MetadataDecoder(peModule0); var anonymousTypeMap0 = PEDeltaAssemblyBuilder.GetAnonymousTypeMapFromMetadata(reader0, decoder0); Assert.Equal("<>f__AnonymousType0", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("A", isKey: false, ignoreCase: false)))].Name); Assert.Equal("<>f__AnonymousType1", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("B", isKey: false, ignoreCase: false)))].Name); Assert.Equal(2, anonymousTypeMap0.Count); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll); var testData = new CompilationTestData(); compilation1.EmitToArray(testData: testData); var peAssemblyBuilder = (PEAssemblyBuilder)testData.Module; var c = compilation1.GetMember<NamedTypeSymbol>("C"); var displayClass = peAssemblyBuilder.GetSynthesizedTypes(c).Single(); Assert.Equal("<>c__DisplayClass0_0", displayClass.Name); var emitContext = new EmitContext(peAssemblyBuilder, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var fields = displayClass.GetFields(emitContext).ToArray(); var x1 = fields[0]; var x2 = fields[1]; Assert.Equal("x1", x1.Name); Assert.Equal("x2", x2.Name); var matcher = new CSharpSymbolMatcher(anonymousTypeMap0, null, compilation1.SourceAssembly, emitContext, peAssemblySymbol0); var mappedX1 = (Cci.IFieldDefinition)matcher.MapDefinition(x1); var mappedX2 = (Cci.IFieldDefinition)matcher.MapDefinition(x2); Assert.Equal("x1", mappedX1.Name); Assert.Null(mappedX2); } [Fact] public void HoistedAnonymousTypes_Complex() { var source0 = @" using System; class C { static void F() { var x1 = new[] { new { A = new { X = 1 } } }; var x2 = new[] { new { A = new { Y = 1 } } }; var y = new Func<int>(() => x1[0].A.X + x2[0].A.Y); } } "; var source1 = @" using System; class C { static void F() { var x1 = new[] { new { A = new { X = 1 } } }; var x2 = new[] { new { A = new { Z = 1 } } }; var y = new Func<int>(() => x1[0].A.X + x2[0].A.Z); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var peRef0 = compilation0.EmitToImageReference(); var peAssemblySymbol0 = (PEAssemblySymbol)CreateCompilation("", new[] { peRef0 }).GetReferencedAssemblySymbol(peRef0); var peModule0 = (PEModuleSymbol)peAssemblySymbol0.Modules[0]; var reader0 = peModule0.Module.MetadataReader; var decoder0 = new MetadataDecoder(peModule0); var anonymousTypeMap0 = PEDeltaAssemblyBuilder.GetAnonymousTypeMapFromMetadata(reader0, decoder0); Assert.Equal("<>f__AnonymousType0", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("A", isKey: false, ignoreCase: false)))].Name); Assert.Equal("<>f__AnonymousType1", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("X", isKey: false, ignoreCase: false)))].Name); Assert.Equal("<>f__AnonymousType2", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("Y", isKey: false, ignoreCase: false)))].Name); Assert.Equal(3, anonymousTypeMap0.Count); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll); var testData = new CompilationTestData(); compilation1.EmitToArray(testData: testData); var peAssemblyBuilder = (PEAssemblyBuilder)testData.Module; var c = compilation1.GetMember<NamedTypeSymbol>("C"); var displayClass = peAssemblyBuilder.GetSynthesizedTypes(c).Single(); Assert.Equal("<>c__DisplayClass0_0", displayClass.Name); var emitContext = new EmitContext(peAssemblyBuilder, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var fields = displayClass.GetFields(emitContext).ToArray(); AssertEx.SetEqual(fields.Select(f => f.Name), new[] { "x1", "x2" }); var x1 = fields.Where(f => f.Name == "x1").Single(); var x2 = fields.Where(f => f.Name == "x2").Single(); var matcher = new CSharpSymbolMatcher(anonymousTypeMap0, null, compilation1.SourceAssembly, emitContext, peAssemblySymbol0); var mappedX1 = (Cci.IFieldDefinition)matcher.MapDefinition(x1); var mappedX2 = (Cci.IFieldDefinition)matcher.MapDefinition(x2); Assert.Equal("x1", mappedX1.Name); Assert.Null(mappedX2); } [Fact] public void TupleField_TypeChange() { var source0 = @" class C { public (int a, int b) x; }"; var source1 = @" class C { public (int a, bool b) x; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<FieldSymbol>("C.x"); var other = matcher.MapDefinition(member.GetCciAdapter()); // If a type changes within a tuple, we do not expect types to match. Assert.Null(other); } [Fact] public void TupleField_NameChange() { var source0 = @" class C { public (int a, int b) x; }"; var source1 = @" class C { public (int a, int c) x; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<FieldSymbol>("C.x"); var other = matcher.MapDefinition(member.GetCciAdapter()); // Types must match because just an element name was changed. Assert.NotNull(other); } [Fact] public void TupleMethod_TypeChange() { var source0 = @" class C { public (int a, int b) X() { return null }; }"; var source1 = @" class C { public (int a, bool b) X() { return null }; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<MethodSymbol>("C.X"); var other = matcher.MapDefinition(member.GetCciAdapter()); // If a type changes within a tuple, we do not expect types to match. Assert.Null(other); } [Fact] public void TupleMethod_NameChange() { var source0 = @" class C { public (int a, int b) X() { return null }; }"; var source1 = @" class C { public (int a, int c) X() { return null }; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<MethodSymbol>("C.X"); var other = matcher.MapDefinition(member.GetCciAdapter()); // Types must match because just an element name was changed. Assert.NotNull(other); } [Fact] public void TupleProperty_TypeChange() { var source0 = @" class C { public (int a, int b) X { get { return null; } }; }"; var source1 = @" class C { public (int a, bool b) X { get { return null; } }; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<PropertySymbol>("C.X"); var other = matcher.MapDefinition(member.GetCciAdapter()); // If a type changes within a tuple, we do not expect types to match. Assert.Null(other); } [Fact] public void TupleProperty_NameChange() { var source0 = @" class C { public (int a, int b) X { get { return null; } }; }"; var source1 = @" class C { public (int a, int c) X { get { return null; } }; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<PropertySymbol>("C.X"); var other = matcher.MapDefinition(member.GetCciAdapter()); // Types must match because just an element name was changed. Assert.NotNull(other); } [Fact] public void TupleStructField_TypeChange() { var source0 = @" public struct Vector { public (int x, int y) Coordinates; }"; var source1 = @" public struct Vector { public (int x, int y, int z) Coordinates; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<FieldSymbol>("Vector.Coordinates"); var other = matcher.MapDefinition(member.GetCciAdapter()); // If a type changes within a tuple, we do not expect types to match. Assert.Null(other); } [Fact] public void TupleStructField_NameChange() { var source0 = @" public struct Vector { public (int x, int y) Coordinates; }"; var source1 = @" public struct Vector { public (int x, int z) Coordinates; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<FieldSymbol>("Vector.Coordinates"); var other = matcher.MapDefinition(member.GetCciAdapter()); // Types must match because just an element name was changed. Assert.NotNull(other); } [Fact] public void TupleDelegate_TypeChange() { var source0 = @" public class C { public delegate (int, int) F(); }"; var source1 = @" public class C { public delegate (int, bool) F(); }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<SourceNamedTypeSymbol>("C.F"); var other = matcher.MapDefinition(member.GetCciAdapter()); // Tuple delegate defines a type. We should be able to match old and new types by name. Assert.NotNull(other); } [Fact] public void TupleDelegate_NameChange() { var source0 = @" public class C { public delegate (int, int) F(); }"; var source1 = @" public class C { public delegate (int x, int y) F(); }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<SourceNamedTypeSymbol>("C.F"); var other = matcher.MapDefinition(member.GetCciAdapter()); // Types must match because just an element name was changed. Assert.NotNull(other); } [Fact] public void RefReturn_Method() { var source0 = @" struct C { // non-matching public ref int P() => throw null; public ref readonly int Q() => throw null; public int R() => throw null; // matching public ref readonly int S() => throw null; public ref int T() => throw null; }"; var source1 = @" struct C { // non-matching public ref bool P() => throw null; public ref int Q() => throw null; public ref int R() => throw null; // matching public ref readonly int S() => throw null; public ref int T() => throw null; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var s0 = compilation0.GetMember<MethodSymbol>("C.S"); var t0 = compilation0.GetMember<MethodSymbol>("C.T"); var p1 = compilation1.GetMember<MethodSymbol>("C.P"); var q1 = compilation1.GetMember<MethodSymbol>("C.Q"); var r1 = compilation1.GetMember<MethodSymbol>("C.R"); var s1 = compilation1.GetMember<MethodSymbol>("C.S"); var t1 = compilation1.GetMember<MethodSymbol>("C.T"); Assert.Null(matcher.MapDefinition(p1.GetCciAdapter())); Assert.Null(matcher.MapDefinition(q1.GetCciAdapter())); Assert.Null(matcher.MapDefinition(r1.GetCciAdapter())); Assert.Same(s0, matcher.MapDefinition(s1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(t0, matcher.MapDefinition(t1.GetCciAdapter()).GetInternalSymbol()); } [Fact] public void RefReturn_Property() { var source0 = @" struct C { // non-matching public ref int P => throw null; public ref readonly int Q => throw null; public int R => throw null; // matching public ref readonly int S => throw null; public ref int T => throw null; }"; var source1 = @" struct C { // non-matching public ref bool P => throw null; public ref int Q => throw null; public ref int R => throw null; // matching public ref readonly int S => throw null; public ref int T => throw null; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var s0 = compilation0.GetMember<PropertySymbol>("C.S"); var t0 = compilation0.GetMember<PropertySymbol>("C.T"); var p1 = compilation1.GetMember<PropertySymbol>("C.P"); var q1 = compilation1.GetMember<PropertySymbol>("C.Q"); var r1 = compilation1.GetMember<PropertySymbol>("C.R"); var s1 = compilation1.GetMember<PropertySymbol>("C.S"); var t1 = compilation1.GetMember<PropertySymbol>("C.T"); Assert.Null(matcher.MapDefinition(p1.GetCciAdapter())); Assert.Null(matcher.MapDefinition(q1.GetCciAdapter())); Assert.Null(matcher.MapDefinition(r1.GetCciAdapter())); Assert.Same(s0, matcher.MapDefinition(s1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(t0, matcher.MapDefinition(t1.GetCciAdapter()).GetInternalSymbol()); } [Fact] public void Property_CompilationVsPE() { var source = @" using System; interface I<T, S> { int this[int index] { set; } } class C : I<int, bool> { int _current; int I<int, bool>.this[int anotherIndex] { set { _current = anotherIndex + value; } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var peRef0 = compilation0.EmitToImageReference(); var peAssemblySymbol0 = (PEAssemblySymbol)CreateCompilation("", new[] { peRef0 }).GetReferencedAssemblySymbol(peRef0); var compilation1 = CreateCompilation(source, options: TestOptions.DebugDll); var testData = new CompilationTestData(); compilation1.EmitToArray(testData: testData); var peAssemblyBuilder = (PEAssemblyBuilder)testData.Module; var c = compilation1.GetMember<NamedTypeSymbol>("C"); var property = c.GetMember<PropertySymbol>("I<System.Int32,System.Boolean>.this[]"); var parameters = property.GetParameters().ToArray(); Assert.Equal(1, parameters.Length); Assert.Equal("anotherIndex", parameters[0].Name); var emitContext = new EmitContext(peAssemblyBuilder, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var matcher = new CSharpSymbolMatcher(null, null, compilation1.SourceAssembly, emitContext, peAssemblySymbol0); var mappedProperty = (Cci.IPropertyDefinition)matcher.MapDefinition(property.GetCciAdapter()); Assert.Equal("I<System.Int32,System.Boolean>.Item", ((PropertySymbol)mappedProperty.GetInternalSymbol()).MetadataName); } [Fact] public void Method_ParameterNullableChange() { var source0 = @" using System.Collections.Generic; class C { string c; ref string M(string? s, (string a, dynamic? b) tuple, List<string?> list) => ref c; }"; var source1 = @" using System.Collections.Generic; class C { string c; ref string? M(string s, (string? a, dynamic b) tuple, List<string> list) => ref c; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<MethodSymbol>("C.M"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } [Fact] public void Method_ParameterRename() { var source0 = @" using System.Collections.Generic; class C { string M(string s) => s.ToString(); }"; var source1 = @" using System.Collections.Generic; class C { string M(string m) => m.ToString(); }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<MethodSymbol>("C.M"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } [Fact] public void Method_ParameterRenameToDiscard() { var source0 = @" using System.Collections.Generic; class C { string M(string s) => s.ToString(); }"; var source1 = @" using System.Collections.Generic; class C { string M(string _) => ""Hello""; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<MethodSymbol>("C.M"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } [Fact] public void Field_NullableChange() { var source0 = @" class C { string S; }"; var source1 = @" class C { string? S; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<FieldSymbol>("C.S"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } [Fact] public void AnonymousTypesWithNullables() { var source0 = @" using System; class C { static T id<T>(T t) => t; static T F<T>(Func<T> f) => f(); static void M(string? x) { var y1 = new { A = id(x) }; var y2 = F(() => new { B = id(x) }); var z = new Func<string>(() => y1.A + y2.B); } }"; var source1 = @" using System; class C { static T id<T>(T t) => t; static T F<T>(Func<T> f) => f(); static void M(string? x) { if (x is null) throw new Exception(); var y1 = new { A = id(x) }; var y2 = F(() => new { B = id(x) }); var z = new Func<string>(() => y1.A + y2.B); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var peRef0 = compilation0.EmitToImageReference(); var peAssemblySymbol0 = (PEAssemblySymbol)CreateCompilation("", new[] { peRef0 }).GetReferencedAssemblySymbol(peRef0); var peModule0 = (PEModuleSymbol)peAssemblySymbol0.Modules[0]; var reader0 = peModule0.Module.MetadataReader; var decoder0 = new MetadataDecoder(peModule0); var anonymousTypeMap0 = PEDeltaAssemblyBuilder.GetAnonymousTypeMapFromMetadata(reader0, decoder0); Assert.Equal("<>f__AnonymousType0", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("A", isKey: false, ignoreCase: false)))].Name); Assert.Equal("<>f__AnonymousType1", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("B", isKey: false, ignoreCase: false)))].Name); Assert.Equal(2, anonymousTypeMap0.Count); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll); var testData = new CompilationTestData(); compilation1.EmitToArray(testData: testData); var peAssemblyBuilder = (PEAssemblyBuilder)testData.Module; var c = compilation1.GetMember<NamedTypeSymbol>("C"); var displayClass = peAssemblyBuilder.GetSynthesizedTypes(c).Single(); Assert.Equal("<>c__DisplayClass2_0", displayClass.Name); var emitContext = new EmitContext(peAssemblyBuilder, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var fields = displayClass.GetFields(emitContext).ToArray(); AssertEx.SetEqual(fields.Select(f => f.Name), new[] { "x", "y1", "y2" }); var y1 = fields.Where(f => f.Name == "y1").Single(); var y2 = fields.Where(f => f.Name == "y2").Single(); var matcher = new CSharpSymbolMatcher(anonymousTypeMap0, null, compilation1.SourceAssembly, emitContext, peAssemblySymbol0); var mappedY1 = (Cci.IFieldDefinition)matcher.MapDefinition(y1); var mappedY2 = (Cci.IFieldDefinition)matcher.MapDefinition(y2); Assert.Equal("y1", mappedY1.Name); Assert.Equal("y2", mappedY2.Name); } [Fact] public void InterfaceMembers() { var source = @" using System; interface I { static int X = 1; static event Action Y; static void M() { } void N() { } static int P { get => 1; set { } } int Q { get => 1; set { } } static event Action E { add { } remove { } } event Action F { add { } remove { } } } "; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var x0 = compilation0.GetMember<FieldSymbol>("I.X"); var y0 = compilation0.GetMember<EventSymbol>("I.Y"); var m0 = compilation0.GetMember<MethodSymbol>("I.M"); var n0 = compilation0.GetMember<MethodSymbol>("I.N"); var p0 = compilation0.GetMember<PropertySymbol>("I.P"); var q0 = compilation0.GetMember<PropertySymbol>("I.Q"); var e0 = compilation0.GetMember<EventSymbol>("I.E"); var f0 = compilation0.GetMember<EventSymbol>("I.F"); var x1 = compilation1.GetMember<FieldSymbol>("I.X"); var y1 = compilation1.GetMember<EventSymbol>("I.Y"); var m1 = compilation1.GetMember<MethodSymbol>("I.M"); var n1 = compilation1.GetMember<MethodSymbol>("I.N"); var p1 = compilation1.GetMember<PropertySymbol>("I.P"); var q1 = compilation1.GetMember<PropertySymbol>("I.Q"); var e1 = compilation1.GetMember<EventSymbol>("I.E"); var f1 = compilation1.GetMember<EventSymbol>("I.F"); Assert.Same(x0, matcher.MapDefinition(x1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(y0, matcher.MapDefinition(y1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(m0, matcher.MapDefinition(m1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(n0, matcher.MapDefinition(n1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(p0, matcher.MapDefinition(p1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(q0, matcher.MapDefinition(q1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(e0, matcher.MapDefinition(e1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(f0, matcher.MapDefinition(f1.GetCciAdapter()).GetInternalSymbol()); } [Fact] public void FunctionPointerMembersTranslated() { var source = @" unsafe class C { delegate*<void> f1; delegate*<C, C, C> f2; delegate*<ref C> f3; delegate*<ref readonly C> f4; delegate*<ref C, void> f5; delegate*<in C, void> f6; delegate*<out C, void> f7; } "; var compilation0 = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9); var compilation1 = compilation0.WithSource(source); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); for (int i = 1; i <= 7; i++) { var f_0 = compilation0.GetMember<FieldSymbol>($"C.f{i}"); var f_1 = compilation1.GetMember<FieldSymbol>($"C.f{i}"); Assert.Same(f_0, matcher.MapDefinition(f_1.GetCciAdapter()).GetInternalSymbol()); } } [Theory] [InlineData("C", "void")] [InlineData("C", "object")] [InlineData("C", "ref C")] [InlineData("C", "ref readonly C")] [InlineData("ref C", "ref readonly C")] public void FunctionPointerMembers_ReturnMismatch(string return1, string return2) { var source1 = $@" unsafe class C {{ delegate*<C, {return1}> f1; }}"; var source2 = $@" unsafe class C {{ delegate*<C, {return2}> f1; }}"; var compilation0 = CreateCompilation(source1, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9); var compilation1 = compilation0.WithSource(source2); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var f_1 = compilation1.GetMember<FieldSymbol>($"C.f1"); Assert.Null(matcher.MapDefinition(f_1.GetCciAdapter())); } [Theory] [InlineData("C", "object")] [InlineData("C", "ref C")] [InlineData("C", "out C")] [InlineData("C", "in C")] [InlineData("ref C", "out C")] [InlineData("ref C", "in C")] [InlineData("out C", "in C")] [InlineData("C, C", "C")] public void FunctionPointerMembers_ParamMismatch(string param1, string param2) { var source1 = $@" unsafe class C {{ delegate*<{param1}, C, void>* f1; }}"; var source2 = $@" unsafe class C {{ delegate*<{param2}, C, void>* f1; }}"; verify(source1, source2); source1 = $@" unsafe class C {{ delegate*<C, {param1}, void> f1; }}"; source2 = $@" unsafe class C {{ delegate*<C, {param2}, void> f1; }}"; verify(source1, source2); static void verify(string source1, string source2) { var compilation0 = CreateCompilation(source1, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9); var compilation1 = compilation0.WithSource(source2); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var f_1 = compilation1.GetMember<FieldSymbol>($"C.f1"); Assert.Null(matcher.MapDefinition(f_1.GetCciAdapter())); } } [Fact] public void Record_ImplementSynthesizedMember_ToString() { var source0 = @" public record R { }"; var source1 = @" public record R { public override string ToString() => ""R""; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<SourceOrdinaryMethodSymbol>("R.ToString"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } [Fact] public void Record_ImplementSynthesizedMember_PrintMembers() { var source0 = @" public record R { }"; var source1 = @" public record R { protected virtual bool PrintMembers(System.Text.StringBuilder builder) => true; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member0 = compilation0.GetMember<SynthesizedRecordPrintMembers>("R.PrintMembers"); var member1 = compilation1.GetMember<SourceOrdinaryMethodSymbol>("R.PrintMembers"); Assert.Equal(member0, (MethodSymbol)matcher.MapDefinition(member1.GetCciAdapter()).GetInternalSymbol()); } [Fact] public void Record_RemoveSynthesizedMember_PrintMembers() { var source0 = @" public record R { protected virtual bool PrintMembers(System.Text.StringBuilder builder) => true; }"; var source1 = @" public record R { }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member0 = compilation0.GetMember<SourceOrdinaryMethodSymbol>("R.PrintMembers"); var member1 = compilation1.GetMember<SynthesizedRecordPrintMembers>("R.PrintMembers"); Assert.Equal(member0, (MethodSymbol)matcher.MapDefinition(member1.GetCciAdapter()).GetInternalSymbol()); } [Fact] public void Record_ImplementSynthesizedMember_Property() { var source0 = @" public record R(int X);"; var source1 = @" public record R(int X) { public int X { get; init; } = this.X; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member0 = compilation0.GetMember<SynthesizedRecordPropertySymbol>("R.X"); var member1 = compilation1.GetMember<SourcePropertySymbol>("R.X"); Assert.Equal(member0, (PropertySymbol)matcher.MapDefinition(member1.GetCciAdapter()).GetInternalSymbol()); } [Fact] public void Record_ImplementSynthesizedMember_Constructor() { var source0 = @" public record R(int X);"; var source1 = @" public record R { public R(int X) { this.X = X; } public int X { get; init; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var members = compilation1.GetMembers("R..ctor"); // There are two, one is the copy constructor Assert.Equal(2, members.Length); var member = (SourceConstructorSymbol)members.Single(m => m.ToString() == "R.R(int)"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } [Fact] public void SynthesizedDelegates() { var source0 = @" using System; class C { static void F() { var _1 = (int a, ref int b) => a; var _2 = (in int a, int b) => { }; var _3 = (int _1, int _2, int _3, int _4, int _5, int _6, int _7, int _8, int _9, int _10, int _11, int _12, int _13, int _14, int _15, int _16, int _17, int _18, int _19, int _20, int _21, int _22, int _23, int _24, int _25, int _26, int _27, int _28, int _29, int _30, int _31, int _32, ref int _33) => { }; } } "; var source1 = @" using System; class C { static void F() { var _1 = (int c, ref int d) => c; var _2 = (in int c, int d) => { d.ToString(); }; var _3 = (int _1, int _2, int _3, int _4, int _5, int _6, int _7, int _8, int _9, int _10, int _11, int _12, int _13, int _14, int _15, int _16, int _17, int _18, int _19, int _20, int _21, int _22, int _23, int _24, int _25, int _26, int _27, int _28, int _29, int _30, int _31, int _32, ref int _33) => { _1.ToString(); }; } }"; var peAssemblySymbol0 = CreatePEAssemblySymbol(source0); var peModule0 = (PEModuleSymbol)peAssemblySymbol0.Modules[0]; var reader0 = peModule0.Module.MetadataReader; var decoder0 = new MetadataDecoder(peModule0); var synthesizedDelegates0 = PEDeltaAssemblyBuilder.GetSynthesizedDelegateMapFromMetadata(reader0, decoder0); Assert.Contains(new SynthesizedDelegateKey("<>F{00000004}`3"), synthesizedDelegates0); Assert.Contains(new SynthesizedDelegateKey("<>A{00000003}`2"), synthesizedDelegates0); Assert.Contains(new SynthesizedDelegateKey("<>A{00000000,00000001}`33"), synthesizedDelegates0); Assert.Equal(3, synthesizedDelegates0.Count); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll); var testData = new CompilationTestData(); compilation1.EmitToArray(testData: testData); var peAssemblyBuilder = (PEAssemblyBuilder)testData.Module; var c = compilation1.GetMember<NamedTypeSymbol>("C"); var displayClass = peAssemblyBuilder.GetSynthesizedTypes(c).Single(); Assert.Equal("<>c", displayClass.Name); var emitContext = new EmitContext(peAssemblyBuilder, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var fields = displayClass.GetFields(emitContext).ToArray(); var field1 = fields[1]; var field2 = fields[2]; var field3 = fields[3]; Assert.Equal("<>9__0_0", field1.Name); Assert.Equal("<>9__0_1", field2.Name); Assert.Equal("<>9__0_2", field3.Name); var matcher = new CSharpSymbolMatcher(null, synthesizedDelegates0, compilation1.SourceAssembly, emitContext, peAssemblySymbol0); var mappedField1 = (Cci.IFieldDefinition)matcher.MapDefinition(field1); var mappedField2 = (Cci.IFieldDefinition)matcher.MapDefinition(field2); var mappedField3 = (Cci.IFieldDefinition)matcher.MapDefinition(field3); Assert.Equal("<>9__0_0", mappedField1.Name); Assert.Equal("<>9__0_1", mappedField2.Name); Assert.Equal("<>9__0_2", mappedField3.Name); } } }
// Licensed to the .NET Foundation under one or more 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 System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { public class SymbolMatcherTests : EditAndContinueTestBase { private static PEAssemblySymbol CreatePEAssemblySymbol(string source) { var compilation = CreateCompilation(source, options: TestOptions.DebugDll); var reference = compilation.EmitToImageReference(); return (PEAssemblySymbol)CreateCompilation("", new[] { reference }).GetReferencedAssemblySymbol(reference); } [Fact] public void ConcurrentAccess() { var source = @"class A { B F; D P { get; set; } void M(A a, B b, S s, I i) { } delegate void D(S s); class B { } struct S { } interface I { } } class B { A M<T, U>() where T : A where U : T, I { return null; } event D E; delegate void D(S s); struct S { } interface I { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var builder = new List<Symbol>(); var type = compilation1.GetMember<NamedTypeSymbol>("A"); builder.Add(type); builder.AddRange(type.GetMembers()); type = compilation1.GetMember<NamedTypeSymbol>("B"); builder.Add(type); builder.AddRange(type.GetMembers()); var members = builder.ToImmutableArray(); Assert.True(members.Length > 10); for (int i = 0; i < 10; i++) { var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var tasks = new Task[10]; for (int j = 0; j < tasks.Length; j++) { int startAt = i + j + 1; tasks[j] = Task.Run(() => { MatchAll(matcher, members, startAt); Thread.Sleep(10); }); } Task.WaitAll(tasks); } } private static void MatchAll(CSharpSymbolMatcher matcher, ImmutableArray<Symbol> members, int startAt) { int n = members.Length; for (int i = 0; i < n; i++) { var member = members[(i + startAt) % n]; var other = matcher.MapDefinition((Cci.IDefinition)member.GetCciAdapter()); Assert.NotNull(other); } } [Fact] public void TypeArguments() { const string source = @"class A<T> { class B<U> { static A<V> M<V>(A<U>.B<T> x, A<object>.S y) { return null; } static A<V> M<V>(A<U>.B<T> x, A<V>.S y) { return null; } } struct S { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var members = compilation1.GetMember<NamedTypeSymbol>("A.B").GetMembers("M"); Assert.Equal(2, members.Length); foreach (var member in members) { var other = matcher.MapDefinition((Cci.IMethodDefinition)member.GetCciAdapter()); Assert.NotNull(other); } } [Fact] public void Constraints() { const string source = @"interface I<T> where T : I<T> { } class C { static void M<T>(I<T> o) where T : I<T> { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<MethodSymbol>("C.M"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } [Fact] public void CustomModifiers() { var ilSource = @".class public abstract A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public abstract virtual instance object modopt(A) [] F(int32 modopt(object) *p) { } }"; var metadataRef = CompileIL(ilSource); var source = @"unsafe class B : A { public override object[] F(int* p) { return null; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, references: new[] { metadataRef }); var compilation1 = compilation0.WithSource(source); var member1 = compilation1.GetMember<MethodSymbol>("B.F"); Assert.Equal(1, ((PointerTypeSymbol)member1.Parameters[0].Type).PointedAtTypeWithAnnotations.CustomModifiers.Length); Assert.Equal(1, ((ArrayTypeSymbol)member1.ReturnType).ElementTypeWithAnnotations.CustomModifiers.Length); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var other = (MethodSymbol)matcher.MapDefinition(member1.GetCciAdapter()).GetInternalSymbol(); Assert.NotNull(other); Assert.Equal(1, ((PointerTypeSymbol)other.Parameters[0].Type).PointedAtTypeWithAnnotations.CustomModifiers.Length); Assert.Equal(1, ((ArrayTypeSymbol)other.ReturnType).ElementTypeWithAnnotations.CustomModifiers.Length); } [Fact] public void CustomModifiers_InAttribute_Source() { // The parameter is emitted as // int32& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) var source0 = @" abstract class C { // matching public abstract void F(in int x); public virtual void G(in int x) => throw null; // non-matching public void H(in int x) => throw null; }"; var source1 = @" abstract class C { // matching public abstract void F(in int x); public virtual void G(in int x) => throw null; // non-matching public void H(int x) => throw null; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var g0 = compilation0.GetMember<MethodSymbol>("C.G"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var h1 = compilation1.GetMember<MethodSymbol>("C.H"); Assert.Same(f0, (MethodSymbol)matcher.MapDefinition(f1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(g0, (MethodSymbol)matcher.MapDefinition(g1.GetCciAdapter()).GetInternalSymbol()); Assert.Null(matcher.MapDefinition(h1.GetCciAdapter())); } [Fact] public void CustomModifiers_InAttribute_Metadata() { // The parameter is emitted as // int32& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) var source0 = @" abstract class C { // matching public abstract void F(in int x); public virtual void G(in int x) => throw null; // non-matching public void H(in int x) => throw null; }"; var source1 = @" abstract class C { // matching public abstract void F(in int x); public virtual void G(in int x) => throw null; // non-matching public void H(int x) => throw null; }"; var peAssemblySymbol = CreatePEAssemblySymbol(source0); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll).WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, peAssemblySymbol); var f0 = peAssemblySymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember("F"); var g0 = peAssemblySymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember("G"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var h1 = compilation1.GetMember<MethodSymbol>("C.H"); Assert.Equal(f0, (MethodSymbol)matcher.MapDefinition(f1.GetCciAdapter()).GetInternalSymbol()); Assert.Equal(g0, (MethodSymbol)matcher.MapDefinition(g1.GetCciAdapter()).GetInternalSymbol()); Assert.Null(matcher.MapDefinition(h1.GetCciAdapter())); } [ConditionalFact(typeof(DesktopOnly))] public void VaryingCompilationReferences() { string libSource = @" public class D { } "; string source = @" public class C { public void F(D a) {} } "; var lib0 = CreateCompilation(libSource, options: TestOptions.DebugDll, assemblyName: "Lib"); var lib1 = CreateCompilation(libSource, options: TestOptions.DebugDll, assemblyName: "Lib"); var compilation0 = CreateCompilation(source, new[] { lib0.ToMetadataReference() }, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source).WithReferences(MscorlibRef, lib1.ToMetadataReference()); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var mf1 = matcher.MapDefinition(f1.GetCciAdapter()); Assert.Equal(f0, mf1.GetInternalSymbol()); } [WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")] [Fact] public void PreviousType_ArrayType() { var source0 = @" class C { static void M() { int x = 0; } class D {} }"; var source1 = @" class C { static void M() { D[] x = null; } class D {} }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var elementType = compilation1.GetMember<TypeSymbol>("C.D"); var member = compilation1.CreateArrayTypeSymbol(elementType); var other = matcher.MapReference(member.GetCciAdapter()); Assert.NotNull(other); } [WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")] [Fact] public void NoPreviousType_ArrayType() { var source0 = @" class C { static void M() { int x = 0; } }"; var source1 = @" class C { static void M() { D[] x = null; } class D {} }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var elementType = compilation1.GetMember<TypeSymbol>("C.D"); var member = compilation1.CreateArrayTypeSymbol(elementType); var other = matcher.MapReference(member.GetCciAdapter()); // For a newly added type, there is no match in the previous generation. Assert.Null(other); } [WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")] [Fact] public void NoPreviousType_PointerType() { var source0 = @" class C { static void M() { int x = 0; } }"; var source1 = @" class C { static unsafe void M() { D* x = null; } struct D {} }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var elementType = compilation1.GetMember<TypeSymbol>("C.D"); var member = compilation1.CreatePointerTypeSymbol(elementType); var other = matcher.MapReference(member.GetCciAdapter()); // For a newly added type, there is no match in the previous generation. Assert.Null(other); } [WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")] [Fact] public void NoPreviousType_GenericType() { var source0 = @" using System.Collections.Generic; class C { static void M() { int x = 0; } }"; var source1 = @" using System.Collections.Generic; class C { static void M() { List<D> x = null; } class D {} List<D> y; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<FieldSymbol>("C.y"); var other = matcher.MapReference((Cci.ITypeReference)member.Type.GetCciAdapter()); // For a newly added type, there is no match in the previous generation. Assert.Null(other); } [Fact] public void HoistedAnonymousTypes() { var source0 = @" using System; class C { static void F() { var x1 = new { A = 1 }; var x2 = new { B = 1 }; var y = new Func<int>(() => x1.A + x2.B); } } "; var source1 = @" using System; class C { static void F() { var x1 = new { A = 1 }; var x2 = new { b = 1 }; var y = new Func<int>(() => x1.A + x2.b); } }"; var peAssemblySymbol0 = CreatePEAssemblySymbol(source0); var peModule0 = (PEModuleSymbol)peAssemblySymbol0.Modules[0]; var reader0 = peModule0.Module.MetadataReader; var decoder0 = new MetadataDecoder(peModule0); var anonymousTypeMap0 = PEDeltaAssemblyBuilder.GetAnonymousTypeMapFromMetadata(reader0, decoder0); Assert.Equal("<>f__AnonymousType0", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("A", isKey: false, ignoreCase: false)))].Name); Assert.Equal("<>f__AnonymousType1", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("B", isKey: false, ignoreCase: false)))].Name); Assert.Equal(2, anonymousTypeMap0.Count); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll); var testData = new CompilationTestData(); compilation1.EmitToArray(testData: testData); var peAssemblyBuilder = (PEAssemblyBuilder)testData.Module; var c = compilation1.GetMember<NamedTypeSymbol>("C"); var displayClass = peAssemblyBuilder.GetSynthesizedTypes(c).Single(); Assert.Equal("<>c__DisplayClass0_0", displayClass.Name); var emitContext = new EmitContext(peAssemblyBuilder, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var fields = displayClass.GetFields(emitContext).ToArray(); var x1 = fields[0]; var x2 = fields[1]; Assert.Equal("x1", x1.Name); Assert.Equal("x2", x2.Name); var matcher = new CSharpSymbolMatcher(anonymousTypeMap0, null, compilation1.SourceAssembly, emitContext, peAssemblySymbol0); var mappedX1 = (Cci.IFieldDefinition)matcher.MapDefinition(x1); var mappedX2 = (Cci.IFieldDefinition)matcher.MapDefinition(x2); Assert.Equal("x1", mappedX1.Name); Assert.Null(mappedX2); } [Fact] public void HoistedAnonymousTypes_Complex() { var source0 = @" using System; class C { static void F() { var x1 = new[] { new { A = new { X = 1 } } }; var x2 = new[] { new { A = new { Y = 1 } } }; var y = new Func<int>(() => x1[0].A.X + x2[0].A.Y); } } "; var source1 = @" using System; class C { static void F() { var x1 = new[] { new { A = new { X = 1 } } }; var x2 = new[] { new { A = new { Z = 1 } } }; var y = new Func<int>(() => x1[0].A.X + x2[0].A.Z); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var peRef0 = compilation0.EmitToImageReference(); var peAssemblySymbol0 = (PEAssemblySymbol)CreateCompilation("", new[] { peRef0 }).GetReferencedAssemblySymbol(peRef0); var peModule0 = (PEModuleSymbol)peAssemblySymbol0.Modules[0]; var reader0 = peModule0.Module.MetadataReader; var decoder0 = new MetadataDecoder(peModule0); var anonymousTypeMap0 = PEDeltaAssemblyBuilder.GetAnonymousTypeMapFromMetadata(reader0, decoder0); Assert.Equal("<>f__AnonymousType0", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("A", isKey: false, ignoreCase: false)))].Name); Assert.Equal("<>f__AnonymousType1", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("X", isKey: false, ignoreCase: false)))].Name); Assert.Equal("<>f__AnonymousType2", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("Y", isKey: false, ignoreCase: false)))].Name); Assert.Equal(3, anonymousTypeMap0.Count); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll); var testData = new CompilationTestData(); compilation1.EmitToArray(testData: testData); var peAssemblyBuilder = (PEAssemblyBuilder)testData.Module; var c = compilation1.GetMember<NamedTypeSymbol>("C"); var displayClass = peAssemblyBuilder.GetSynthesizedTypes(c).Single(); Assert.Equal("<>c__DisplayClass0_0", displayClass.Name); var emitContext = new EmitContext(peAssemblyBuilder, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var fields = displayClass.GetFields(emitContext).ToArray(); AssertEx.SetEqual(fields.Select(f => f.Name), new[] { "x1", "x2" }); var x1 = fields.Where(f => f.Name == "x1").Single(); var x2 = fields.Where(f => f.Name == "x2").Single(); var matcher = new CSharpSymbolMatcher(anonymousTypeMap0, null, compilation1.SourceAssembly, emitContext, peAssemblySymbol0); var mappedX1 = (Cci.IFieldDefinition)matcher.MapDefinition(x1); var mappedX2 = (Cci.IFieldDefinition)matcher.MapDefinition(x2); Assert.Equal("x1", mappedX1.Name); Assert.Null(mappedX2); } [Fact] public void TupleField_TypeChange() { var source0 = @" class C { public (int a, int b) x; }"; var source1 = @" class C { public (int a, bool b) x; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<FieldSymbol>("C.x"); var other = matcher.MapDefinition(member.GetCciAdapter()); // If a type changes within a tuple, we do not expect types to match. Assert.Null(other); } [Fact] public void TupleField_NameChange() { var source0 = @" class C { public (int a, int b) x; }"; var source1 = @" class C { public (int a, int c) x; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<FieldSymbol>("C.x"); var other = matcher.MapDefinition(member.GetCciAdapter()); // Types must match because just an element name was changed. Assert.NotNull(other); } [Fact] public void TupleMethod_TypeChange() { var source0 = @" class C { public (int a, int b) X() { return null }; }"; var source1 = @" class C { public (int a, bool b) X() { return null }; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<MethodSymbol>("C.X"); var other = matcher.MapDefinition(member.GetCciAdapter()); // If a type changes within a tuple, we do not expect types to match. Assert.Null(other); } [Fact] public void TupleMethod_NameChange() { var source0 = @" class C { public (int a, int b) X() { return null }; }"; var source1 = @" class C { public (int a, int c) X() { return null }; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<MethodSymbol>("C.X"); var other = matcher.MapDefinition(member.GetCciAdapter()); // Types must match because just an element name was changed. Assert.NotNull(other); } [Fact] public void TupleProperty_TypeChange() { var source0 = @" class C { public (int a, int b) X { get { return null; } }; }"; var source1 = @" class C { public (int a, bool b) X { get { return null; } }; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<PropertySymbol>("C.X"); var other = matcher.MapDefinition(member.GetCciAdapter()); // If a type changes within a tuple, we do not expect types to match. Assert.Null(other); } [Fact] public void TupleProperty_NameChange() { var source0 = @" class C { public (int a, int b) X { get { return null; } }; }"; var source1 = @" class C { public (int a, int c) X { get { return null; } }; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<PropertySymbol>("C.X"); var other = matcher.MapDefinition(member.GetCciAdapter()); // Types must match because just an element name was changed. Assert.NotNull(other); } [Fact] public void TupleStructField_TypeChange() { var source0 = @" public struct Vector { public (int x, int y) Coordinates; }"; var source1 = @" public struct Vector { public (int x, int y, int z) Coordinates; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<FieldSymbol>("Vector.Coordinates"); var other = matcher.MapDefinition(member.GetCciAdapter()); // If a type changes within a tuple, we do not expect types to match. Assert.Null(other); } [Fact] public void TupleStructField_NameChange() { var source0 = @" public struct Vector { public (int x, int y) Coordinates; }"; var source1 = @" public struct Vector { public (int x, int z) Coordinates; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<FieldSymbol>("Vector.Coordinates"); var other = matcher.MapDefinition(member.GetCciAdapter()); // Types must match because just an element name was changed. Assert.NotNull(other); } [Fact] public void TupleDelegate_TypeChange() { var source0 = @" public class C { public delegate (int, int) F(); }"; var source1 = @" public class C { public delegate (int, bool) F(); }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<SourceNamedTypeSymbol>("C.F"); var other = matcher.MapDefinition(member.GetCciAdapter()); // Tuple delegate defines a type. We should be able to match old and new types by name. Assert.NotNull(other); } [Fact] public void TupleDelegate_NameChange() { var source0 = @" public class C { public delegate (int, int) F(); }"; var source1 = @" public class C { public delegate (int x, int y) F(); }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<SourceNamedTypeSymbol>("C.F"); var other = matcher.MapDefinition(member.GetCciAdapter()); // Types must match because just an element name was changed. Assert.NotNull(other); } [Fact] public void RefReturn_Method() { var source0 = @" struct C { // non-matching public ref int P() => throw null; public ref readonly int Q() => throw null; public int R() => throw null; // matching public ref readonly int S() => throw null; public ref int T() => throw null; }"; var source1 = @" struct C { // non-matching public ref bool P() => throw null; public ref int Q() => throw null; public ref int R() => throw null; // matching public ref readonly int S() => throw null; public ref int T() => throw null; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var s0 = compilation0.GetMember<MethodSymbol>("C.S"); var t0 = compilation0.GetMember<MethodSymbol>("C.T"); var p1 = compilation1.GetMember<MethodSymbol>("C.P"); var q1 = compilation1.GetMember<MethodSymbol>("C.Q"); var r1 = compilation1.GetMember<MethodSymbol>("C.R"); var s1 = compilation1.GetMember<MethodSymbol>("C.S"); var t1 = compilation1.GetMember<MethodSymbol>("C.T"); Assert.Null(matcher.MapDefinition(p1.GetCciAdapter())); Assert.Null(matcher.MapDefinition(q1.GetCciAdapter())); Assert.Null(matcher.MapDefinition(r1.GetCciAdapter())); Assert.Same(s0, matcher.MapDefinition(s1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(t0, matcher.MapDefinition(t1.GetCciAdapter()).GetInternalSymbol()); } [Fact] public void RefReturn_Property() { var source0 = @" struct C { // non-matching public ref int P => throw null; public ref readonly int Q => throw null; public int R => throw null; // matching public ref readonly int S => throw null; public ref int T => throw null; }"; var source1 = @" struct C { // non-matching public ref bool P => throw null; public ref int Q => throw null; public ref int R => throw null; // matching public ref readonly int S => throw null; public ref int T => throw null; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var s0 = compilation0.GetMember<PropertySymbol>("C.S"); var t0 = compilation0.GetMember<PropertySymbol>("C.T"); var p1 = compilation1.GetMember<PropertySymbol>("C.P"); var q1 = compilation1.GetMember<PropertySymbol>("C.Q"); var r1 = compilation1.GetMember<PropertySymbol>("C.R"); var s1 = compilation1.GetMember<PropertySymbol>("C.S"); var t1 = compilation1.GetMember<PropertySymbol>("C.T"); Assert.Null(matcher.MapDefinition(p1.GetCciAdapter())); Assert.Null(matcher.MapDefinition(q1.GetCciAdapter())); Assert.Null(matcher.MapDefinition(r1.GetCciAdapter())); Assert.Same(s0, matcher.MapDefinition(s1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(t0, matcher.MapDefinition(t1.GetCciAdapter()).GetInternalSymbol()); } [Fact] public void Property_CompilationVsPE() { var source = @" using System; interface I<T, S> { int this[int index] { set; } } class C : I<int, bool> { int _current; int I<int, bool>.this[int anotherIndex] { set { _current = anotherIndex + value; } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var peRef0 = compilation0.EmitToImageReference(); var peAssemblySymbol0 = (PEAssemblySymbol)CreateCompilation("", new[] { peRef0 }).GetReferencedAssemblySymbol(peRef0); var compilation1 = CreateCompilation(source, options: TestOptions.DebugDll); var testData = new CompilationTestData(); compilation1.EmitToArray(testData: testData); var peAssemblyBuilder = (PEAssemblyBuilder)testData.Module; var c = compilation1.GetMember<NamedTypeSymbol>("C"); var property = c.GetMember<PropertySymbol>("I<System.Int32,System.Boolean>.this[]"); var parameters = property.GetParameters().ToArray(); Assert.Equal(1, parameters.Length); Assert.Equal("anotherIndex", parameters[0].Name); var emitContext = new EmitContext(peAssemblyBuilder, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var matcher = new CSharpSymbolMatcher(null, null, compilation1.SourceAssembly, emitContext, peAssemblySymbol0); var mappedProperty = (Cci.IPropertyDefinition)matcher.MapDefinition(property.GetCciAdapter()); Assert.Equal("I<System.Int32,System.Boolean>.Item", ((PropertySymbol)mappedProperty.GetInternalSymbol()).MetadataName); } [Fact] public void Method_ParameterNullableChange() { var source0 = @" using System.Collections.Generic; class C { string c; ref string M(string? s, (string a, dynamic? b) tuple, List<string?> list) => ref c; }"; var source1 = @" using System.Collections.Generic; class C { string c; ref string? M(string s, (string? a, dynamic b) tuple, List<string> list) => ref c; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<MethodSymbol>("C.M"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } [Fact] public void Method_ParameterRename() { var source0 = @" using System.Collections.Generic; class C { string M(string s) => s.ToString(); }"; var source1 = @" using System.Collections.Generic; class C { string M(string m) => m.ToString(); }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<MethodSymbol>("C.M"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } [Fact] public void Method_ParameterRenameToDiscard() { var source0 = @" using System.Collections.Generic; class C { string M(string s) => s.ToString(); }"; var source1 = @" using System.Collections.Generic; class C { string M(string _) => ""Hello""; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<MethodSymbol>("C.M"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } [Fact] public void Field_NullableChange() { var source0 = @" class C { string S; }"; var source1 = @" class C { string? S; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<FieldSymbol>("C.S"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } [Fact] public void AnonymousTypesWithNullables() { var source0 = @" using System; class C { static T id<T>(T t) => t; static T F<T>(Func<T> f) => f(); static void M(string? x) { var y1 = new { A = id(x) }; var y2 = F(() => new { B = id(x) }); var z = new Func<string>(() => y1.A + y2.B); } }"; var source1 = @" using System; class C { static T id<T>(T t) => t; static T F<T>(Func<T> f) => f(); static void M(string? x) { if (x is null) throw new Exception(); var y1 = new { A = id(x) }; var y2 = F(() => new { B = id(x) }); var z = new Func<string>(() => y1.A + y2.B); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var peRef0 = compilation0.EmitToImageReference(); var peAssemblySymbol0 = (PEAssemblySymbol)CreateCompilation("", new[] { peRef0 }).GetReferencedAssemblySymbol(peRef0); var peModule0 = (PEModuleSymbol)peAssemblySymbol0.Modules[0]; var reader0 = peModule0.Module.MetadataReader; var decoder0 = new MetadataDecoder(peModule0); var anonymousTypeMap0 = PEDeltaAssemblyBuilder.GetAnonymousTypeMapFromMetadata(reader0, decoder0); Assert.Equal("<>f__AnonymousType0", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("A", isKey: false, ignoreCase: false)))].Name); Assert.Equal("<>f__AnonymousType1", anonymousTypeMap0[new AnonymousTypeKey(ImmutableArray.Create(new AnonymousTypeKeyField("B", isKey: false, ignoreCase: false)))].Name); Assert.Equal(2, anonymousTypeMap0.Count); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll); var testData = new CompilationTestData(); compilation1.EmitToArray(testData: testData); var peAssemblyBuilder = (PEAssemblyBuilder)testData.Module; var c = compilation1.GetMember<NamedTypeSymbol>("C"); var displayClass = peAssemblyBuilder.GetSynthesizedTypes(c).Single(); Assert.Equal("<>c__DisplayClass2_0", displayClass.Name); var emitContext = new EmitContext(peAssemblyBuilder, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var fields = displayClass.GetFields(emitContext).ToArray(); AssertEx.SetEqual(fields.Select(f => f.Name), new[] { "x", "y1", "y2" }); var y1 = fields.Where(f => f.Name == "y1").Single(); var y2 = fields.Where(f => f.Name == "y2").Single(); var matcher = new CSharpSymbolMatcher(anonymousTypeMap0, null, compilation1.SourceAssembly, emitContext, peAssemblySymbol0); var mappedY1 = (Cci.IFieldDefinition)matcher.MapDefinition(y1); var mappedY2 = (Cci.IFieldDefinition)matcher.MapDefinition(y2); Assert.Equal("y1", mappedY1.Name); Assert.Equal("y2", mappedY2.Name); } [Fact] public void InterfaceMembers() { var source = @" using System; interface I { static int X = 1; static event Action Y; static void M() { } void N() { } static int P { get => 1; set { } } int Q { get => 1; set { } } static event Action E { add { } remove { } } event Action F { add { } remove { } } } "; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var x0 = compilation0.GetMember<FieldSymbol>("I.X"); var y0 = compilation0.GetMember<EventSymbol>("I.Y"); var m0 = compilation0.GetMember<MethodSymbol>("I.M"); var n0 = compilation0.GetMember<MethodSymbol>("I.N"); var p0 = compilation0.GetMember<PropertySymbol>("I.P"); var q0 = compilation0.GetMember<PropertySymbol>("I.Q"); var e0 = compilation0.GetMember<EventSymbol>("I.E"); var f0 = compilation0.GetMember<EventSymbol>("I.F"); var x1 = compilation1.GetMember<FieldSymbol>("I.X"); var y1 = compilation1.GetMember<EventSymbol>("I.Y"); var m1 = compilation1.GetMember<MethodSymbol>("I.M"); var n1 = compilation1.GetMember<MethodSymbol>("I.N"); var p1 = compilation1.GetMember<PropertySymbol>("I.P"); var q1 = compilation1.GetMember<PropertySymbol>("I.Q"); var e1 = compilation1.GetMember<EventSymbol>("I.E"); var f1 = compilation1.GetMember<EventSymbol>("I.F"); Assert.Same(x0, matcher.MapDefinition(x1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(y0, matcher.MapDefinition(y1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(m0, matcher.MapDefinition(m1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(n0, matcher.MapDefinition(n1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(p0, matcher.MapDefinition(p1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(q0, matcher.MapDefinition(q1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(e0, matcher.MapDefinition(e1.GetCciAdapter()).GetInternalSymbol()); Assert.Same(f0, matcher.MapDefinition(f1.GetCciAdapter()).GetInternalSymbol()); } [Fact] public void FunctionPointerMembersTranslated() { var source = @" unsafe class C { delegate*<void> f1; delegate*<C, C, C> f2; delegate*<ref C> f3; delegate*<ref readonly C> f4; delegate*<ref C, void> f5; delegate*<in C, void> f6; delegate*<out C, void> f7; } "; var compilation0 = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9); var compilation1 = compilation0.WithSource(source); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); for (int i = 1; i <= 7; i++) { var f_0 = compilation0.GetMember<FieldSymbol>($"C.f{i}"); var f_1 = compilation1.GetMember<FieldSymbol>($"C.f{i}"); Assert.Same(f_0, matcher.MapDefinition(f_1.GetCciAdapter()).GetInternalSymbol()); } } [Theory] [InlineData("C", "void")] [InlineData("C", "object")] [InlineData("C", "ref C")] [InlineData("C", "ref readonly C")] [InlineData("ref C", "ref readonly C")] public void FunctionPointerMembers_ReturnMismatch(string return1, string return2) { var source1 = $@" unsafe class C {{ delegate*<C, {return1}> f1; }}"; var source2 = $@" unsafe class C {{ delegate*<C, {return2}> f1; }}"; var compilation0 = CreateCompilation(source1, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9); var compilation1 = compilation0.WithSource(source2); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var f_1 = compilation1.GetMember<FieldSymbol>($"C.f1"); Assert.Null(matcher.MapDefinition(f_1.GetCciAdapter())); } [Theory] [InlineData("C", "object")] [InlineData("C", "ref C")] [InlineData("C", "out C")] [InlineData("C", "in C")] [InlineData("ref C", "out C")] [InlineData("ref C", "in C")] [InlineData("out C", "in C")] [InlineData("C, C", "C")] public void FunctionPointerMembers_ParamMismatch(string param1, string param2) { var source1 = $@" unsafe class C {{ delegate*<{param1}, C, void>* f1; }}"; var source2 = $@" unsafe class C {{ delegate*<{param2}, C, void>* f1; }}"; verify(source1, source2); source1 = $@" unsafe class C {{ delegate*<C, {param1}, void> f1; }}"; source2 = $@" unsafe class C {{ delegate*<C, {param2}, void> f1; }}"; verify(source1, source2); static void verify(string source1, string source2) { var compilation0 = CreateCompilation(source1, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9); var compilation1 = compilation0.WithSource(source2); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var f_1 = compilation1.GetMember<FieldSymbol>($"C.f1"); Assert.Null(matcher.MapDefinition(f_1.GetCciAdapter())); } } [Fact] public void Record_ImplementSynthesizedMember_ToString() { var source0 = @" public record R { }"; var source1 = @" public record R { public override string ToString() => ""R""; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member = compilation1.GetMember<SourceOrdinaryMethodSymbol>("R.ToString"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } [Fact] public void Record_ImplementSynthesizedMember_PrintMembers() { var source0 = @" public record R { }"; var source1 = @" public record R { protected virtual bool PrintMembers(System.Text.StringBuilder builder) => true; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member0 = compilation0.GetMember<SynthesizedRecordPrintMembers>("R.PrintMembers"); var member1 = compilation1.GetMember<SourceOrdinaryMethodSymbol>("R.PrintMembers"); Assert.Equal(member0, (MethodSymbol)matcher.MapDefinition(member1.GetCciAdapter()).GetInternalSymbol()); } [Fact] public void Record_RemoveSynthesizedMember_PrintMembers() { var source0 = @" public record R { protected virtual bool PrintMembers(System.Text.StringBuilder builder) => true; }"; var source1 = @" public record R { }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member0 = compilation0.GetMember<SourceOrdinaryMethodSymbol>("R.PrintMembers"); var member1 = compilation1.GetMember<SynthesizedRecordPrintMembers>("R.PrintMembers"); Assert.Equal(member0, (MethodSymbol)matcher.MapDefinition(member1.GetCciAdapter()).GetInternalSymbol()); } [Fact] public void Record_ImplementSynthesizedMember_Property() { var source0 = @" public record R(int X);"; var source1 = @" public record R(int X) { public int X { get; init; } = this.X; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var member0 = compilation0.GetMember<SynthesizedRecordPropertySymbol>("R.X"); var member1 = compilation1.GetMember<SourcePropertySymbol>("R.X"); Assert.Equal(member0, (PropertySymbol)matcher.MapDefinition(member1.GetCciAdapter()).GetInternalSymbol()); } [Fact] public void Record_ImplementSynthesizedMember_Constructor() { var source0 = @" public record R(int X);"; var source1 = @" public record R { public R(int X) { this.X = X; } public int X { get; init; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var matcher = new CSharpSymbolMatcher( null, null, compilation1.SourceAssembly, default, compilation0.SourceAssembly, default, null); var members = compilation1.GetMembers("R..ctor"); // There are two, one is the copy constructor Assert.Equal(2, members.Length); var member = (SourceConstructorSymbol)members.Single(m => m.ToString() == "R.R(int)"); var other = matcher.MapDefinition(member.GetCciAdapter()); Assert.NotNull(other); } [Fact] public void SynthesizedDelegates() { var source0 = @" using System; class C { static void F() { var _1 = (int a, ref int b) => a; var _2 = (in int a, int b) => { }; var _3 = (int _1, int _2, int _3, int _4, int _5, int _6, int _7, int _8, int _9, int _10, int _11, int _12, int _13, int _14, int _15, int _16, int _17, int _18, int _19, int _20, int _21, int _22, int _23, int _24, int _25, int _26, int _27, int _28, int _29, int _30, int _31, int _32, ref int _33) => { }; } } "; var source1 = @" using System; class C { static void F() { var _1 = (int c, ref int d) => c; var _2 = (in int c, int d) => { d.ToString(); }; var _3 = (int _1, int _2, int _3, int _4, int _5, int _6, int _7, int _8, int _9, int _10, int _11, int _12, int _13, int _14, int _15, int _16, int _17, int _18, int _19, int _20, int _21, int _22, int _23, int _24, int _25, int _26, int _27, int _28, int _29, int _30, int _31, int _32, ref int _33) => { _1.ToString(); }; } }"; var peAssemblySymbol0 = CreatePEAssemblySymbol(source0); var peModule0 = (PEModuleSymbol)peAssemblySymbol0.Modules[0]; var reader0 = peModule0.Module.MetadataReader; var decoder0 = new MetadataDecoder(peModule0); var synthesizedDelegates0 = PEDeltaAssemblyBuilder.GetSynthesizedDelegateMapFromMetadata(reader0, decoder0); Assert.Contains(new SynthesizedDelegateKey("<>F{00000004}`3"), synthesizedDelegates0); Assert.Contains(new SynthesizedDelegateKey("<>A{00000003}`2"), synthesizedDelegates0); Assert.Contains(new SynthesizedDelegateKey("<>A{00000000,00000001}`33"), synthesizedDelegates0); Assert.Equal(3, synthesizedDelegates0.Count); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll); var testData = new CompilationTestData(); compilation1.EmitToArray(testData: testData); var peAssemblyBuilder = (PEAssemblyBuilder)testData.Module; var c = compilation1.GetMember<NamedTypeSymbol>("C"); var displayClass = peAssemblyBuilder.GetSynthesizedTypes(c).Single(); Assert.Equal("<>c", displayClass.Name); var emitContext = new EmitContext(peAssemblyBuilder, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var fields = displayClass.GetFields(emitContext).ToArray(); var field1 = fields[1]; var field2 = fields[2]; var field3 = fields[3]; Assert.Equal("<>9__0_0", field1.Name); Assert.Equal("<>9__0_1", field2.Name); Assert.Equal("<>9__0_2", field3.Name); var matcher = new CSharpSymbolMatcher(null, synthesizedDelegates0, compilation1.SourceAssembly, emitContext, peAssemblySymbol0); var mappedField1 = (Cci.IFieldDefinition)matcher.MapDefinition(field1); var mappedField2 = (Cci.IFieldDefinition)matcher.MapDefinition(field2); var mappedField3 = (Cci.IFieldDefinition)matcher.MapDefinition(field3); Assert.Equal("<>9__0_0", mappedField1.Name); Assert.Equal("<>9__0_1", mappedField2.Name); Assert.Equal("<>9__0_2", mappedField3.Name); } } }
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.CompilationTracker.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 System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Logging; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class SolutionState { /// <summary> /// Tracks the changes made to a project and provides the facility to get a lazily built /// compilation for that project. As the compilation is being built, the partial results are /// stored as well so that they can be used in the 'in progress' workspace snapshot. /// </summary> private partial class CompilationTracker : ICompilationTracker { private static readonly Func<ProjectState, string> s_logBuildCompilationAsync = state => string.Join(",", state.AssemblyName, state.DocumentStates.Count); public ProjectState ProjectState { get; } /// <summary> /// Access via the <see cref="ReadState"/> and <see cref="WriteState"/> methods. /// </summary> private State _stateDoNotAccessDirectly; // guarantees only one thread is building at a time private readonly SemaphoreSlim _buildLock = new(initialCount: 1); private CompilationTracker( ProjectState project, State state) { Contract.ThrowIfNull(project); this.ProjectState = project; _stateDoNotAccessDirectly = state; } /// <summary> /// Creates a tracker for the provided project. The tracker will be in the 'empty' state /// and will have no extra information beyond the project itself. /// </summary> public CompilationTracker(ProjectState project) : this(project, State.Empty) { } private State ReadState() => Volatile.Read(ref _stateDoNotAccessDirectly); private void WriteState(State state, SolutionServices solutionServices) { if (solutionServices.SupportsCachingRecoverableObjects) { // Allow the cache service to create a strong reference to the compilation. We'll get the "furthest along" compilation we have // and hold onto that. var compilationToCache = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull() ?? state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(); solutionServices.CacheService.CacheObjectIfCachingEnabledForKey(ProjectState.Id, state, compilationToCache); } Volatile.Write(ref _stateDoNotAccessDirectly, state); } public bool HasCompilation { get { var state = this.ReadState(); return state.CompilationWithoutGeneratedDocuments != null && state.CompilationWithoutGeneratedDocuments.TryGetValue(out _) || state.DeclarationOnlyCompilation != null; } } public bool ContainsAssemblyOrModuleOrDynamic(ISymbol symbol, bool primary) { Debug.Assert(symbol.Kind == SymbolKind.Assembly || symbol.Kind == SymbolKind.NetModule || symbol.Kind == SymbolKind.DynamicType); var state = this.ReadState(); var unrootedSymbolSet = (state as FinalState)?.UnrootedSymbolSet; if (unrootedSymbolSet == null) { // this was not a tracker that has handed out a compilation (all compilations handed out must be // owned by a 'FinalState'). So this symbol could not be from us. return false; } return unrootedSymbolSet.Value.ContainsAssemblyOrModuleOrDynamic(symbol, primary); } /// <summary> /// Creates a new instance of the compilation info, retaining any already built /// compilation state as the now 'old' state /// </summary> public ICompilationTracker Fork( ProjectState newProject, CompilationAndGeneratorDriverTranslationAction? translate = null, CancellationToken cancellationToken = default) { var state = ReadState(); var baseCompilation = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken); if (baseCompilation != null) { var intermediateProjects = state is InProgressState inProgressState ? inProgressState.IntermediateProjects : ImmutableArray.Create<(ProjectState oldState, CompilationAndGeneratorDriverTranslationAction action)>(); if (translate is not null) { // We have a translation action; are we able to merge it with the prior one? var merged = false; if (intermediateProjects.Any()) { var (priorState, priorAction) = intermediateProjects.Last(); var mergedTranslation = translate.TryMergeWithPrior(priorAction); if (mergedTranslation != null) { // We can replace the prior action with this new one intermediateProjects = intermediateProjects.SetItem(intermediateProjects.Length - 1, (oldState: priorState, mergedTranslation)); merged = true; } } if (!merged) { // Just add it to the end intermediateProjects = intermediateProjects.Add((oldState: this.ProjectState, translate)); } } var newState = State.Create(baseCompilation, state.GeneratedDocuments, state.GeneratorDriver, state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken), intermediateProjects); return new CompilationTracker(newProject, newState); } var declarationOnlyCompilation = state.DeclarationOnlyCompilation; if (declarationOnlyCompilation != null) { if (translate != null) { var intermediateProjects = ImmutableArray.Create((this.ProjectState, translate)); return new CompilationTracker(newProject, new InProgressState(declarationOnlyCompilation, state.GeneratedDocuments, state.GeneratorDriver, compilationWithGeneratedDocuments: state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken), intermediateProjects)); } return new CompilationTracker(newProject, new LightDeclarationState(declarationOnlyCompilation, state.GeneratedDocuments, state.GeneratorDriver, generatedDocumentsAreFinal: false)); } // We have nothing. Just make a tracker that only points to the new project. We'll have // to rebuild its compilation from scratch if anyone asks for it. return new CompilationTracker(newProject); } public ICompilationTracker FreezePartialStateWithTree(SolutionState solution, DocumentState docState, SyntaxTree tree, CancellationToken cancellationToken) { GetPartialCompilationState( solution, docState.Id, out var inProgressProject, out var inProgressCompilation, out var sourceGeneratedDocuments, out var generatorDriver, out var metadataReferenceToProjectId, cancellationToken); if (!inProgressCompilation.SyntaxTrees.Contains(tree)) { var existingTree = inProgressCompilation.SyntaxTrees.FirstOrDefault(t => t.FilePath == tree.FilePath); if (existingTree != null) { inProgressCompilation = inProgressCompilation.ReplaceSyntaxTree(existingTree, tree); inProgressProject = inProgressProject.UpdateDocument(docState, textChanged: false, recalculateDependentVersions: false); } else { inProgressCompilation = inProgressCompilation.AddSyntaxTrees(tree); Debug.Assert(!inProgressProject.DocumentStates.Contains(docState.Id)); inProgressProject = inProgressProject.AddDocuments(ImmutableArray.Create(docState)); } } // The user is asking for an in progress snap. We don't want to create it and then // have the compilation immediately disappear. So we force it to stay around with a ConstantValueSource. // As a policy, all partial-state projects are said to have incomplete references, since the state has no guarantees. var finalState = FinalState.Create( new ConstantValueSource<Optional<Compilation>>(inProgressCompilation), new ConstantValueSource<Optional<Compilation>>(inProgressCompilation), inProgressCompilation, hasSuccessfullyLoaded: false, sourceGeneratedDocuments, generatorDriver, inProgressCompilation, this.ProjectState.Id, metadataReferenceToProjectId); return new CompilationTracker(inProgressProject, finalState); } /// <summary> /// Tries to get the latest snapshot of the compilation without waiting for it to be /// fully built. This method takes advantage of the progress side-effect produced during /// <see cref="BuildCompilationInfoAsync(SolutionState, CancellationToken)"/>. /// It will either return the already built compilation, any /// in-progress compilation or any known old compilation in that order of preference. /// The compilation state that is returned will have a compilation that is retained so /// that it cannot disappear. /// </summary> /// <param name="inProgressCompilation">The compilation to return. Contains any source generated documents that were available already added.</param> private void GetPartialCompilationState( SolutionState solution, DocumentId id, out ProjectState inProgressProject, out Compilation inProgressCompilation, out TextDocumentStates<SourceGeneratedDocumentState> sourceGeneratedDocuments, out GeneratorDriver? generatorDriver, out Dictionary<MetadataReference, ProjectId>? metadataReferenceToProjectId, CancellationToken cancellationToken) { var state = ReadState(); var compilationWithoutGeneratedDocuments = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken); // check whether we can bail out quickly for typing case var inProgressState = state as InProgressState; sourceGeneratedDocuments = state.GeneratedDocuments; generatorDriver = state.GeneratorDriver; // all changes left for this document is modifying the given document. // we can use current state as it is since we will replace the document with latest document anyway. if (inProgressState != null && compilationWithoutGeneratedDocuments != null && inProgressState.IntermediateProjects.All(t => IsTouchDocumentActionForDocument(t.action, id))) { inProgressProject = ProjectState; // We'll add in whatever generated documents we do have; these may be from a prior run prior to some changes // being made to the project, but it's the best we have so we'll use it. inProgressCompilation = compilationWithoutGeneratedDocuments.AddSyntaxTrees(sourceGeneratedDocuments.States.Values.Select(state => state.GetSyntaxTree(cancellationToken))); // This is likely a bug. It seems possible to pass out a partial compilation state that we don't // properly record assembly symbols for. metadataReferenceToProjectId = null; SolutionLogger.UseExistingPartialProjectState(); return; } inProgressProject = inProgressState != null ? inProgressState.IntermediateProjects.First().oldState : this.ProjectState; // if we already have a final compilation we are done. if (compilationWithoutGeneratedDocuments != null && state is FinalState finalState) { var finalCompilation = finalState.FinalCompilationWithGeneratedDocuments.GetValueOrNull(cancellationToken); if (finalCompilation != null) { inProgressCompilation = finalCompilation; // This should hopefully be safe to return as null. Because we already reached the 'FinalState' // before, we should have already recorded the assembly symbols for it. So not recording them // again is likely ok (as long as compilations continue to return the same IAssemblySymbols for // the same references across source edits). metadataReferenceToProjectId = null; SolutionLogger.UseExistingFullProjectState(); return; } } // 1) if we have an in-progress compilation use it. // 2) If we don't, then create a simple empty compilation/project. // 3) then, make sure that all it's p2p refs and whatnot are correct. if (compilationWithoutGeneratedDocuments == null) { inProgressProject = inProgressProject.RemoveAllDocuments(); inProgressCompilation = CreateEmptyCompilation(); } else { inProgressCompilation = compilationWithoutGeneratedDocuments; } inProgressCompilation = inProgressCompilation.AddSyntaxTrees(sourceGeneratedDocuments.States.Values.Select(state => state.GetSyntaxTree(cancellationToken))); // Now add in back a consistent set of project references. For project references // try to get either a CompilationReference or a SkeletonReference. This ensures // that the in-progress project only reports a reference to another project if it // could actually get a reference to that project's metadata. var metadataReferences = new List<MetadataReference>(); var newProjectReferences = new List<ProjectReference>(); metadataReferences.AddRange(this.ProjectState.MetadataReferences); metadataReferenceToProjectId = new Dictionary<MetadataReference, ProjectId>(); foreach (var projectReference in this.ProjectState.ProjectReferences) { var referencedProject = solution.GetProjectState(projectReference.ProjectId); if (referencedProject != null) { if (referencedProject.IsSubmission) { var previousScriptCompilation = solution.GetCompilationAsync(projectReference.ProjectId, cancellationToken).WaitAndGetResult(cancellationToken); // previous submission project must support compilation: RoslynDebug.Assert(previousScriptCompilation != null); inProgressCompilation = inProgressCompilation.WithScriptCompilationInfo(inProgressCompilation.ScriptCompilationInfo!.WithPreviousScriptCompilation(previousScriptCompilation)); } else { // get the latest metadata for the partial compilation of the referenced project. var metadata = solution.GetPartialMetadataReference(projectReference, this.ProjectState); if (metadata == null) { // if we failed to get the metadata, check to see if we previously had existing metadata and reuse it instead. var inProgressCompilationNotRef = inProgressCompilation; metadata = inProgressCompilationNotRef.ExternalReferences.FirstOrDefault( r => solution.GetProjectState(inProgressCompilationNotRef.GetAssemblyOrModuleSymbol(r) as IAssemblySymbol)?.Id == projectReference.ProjectId); } if (metadata != null) { newProjectReferences.Add(projectReference); metadataReferences.Add(metadata); metadataReferenceToProjectId.Add(metadata, projectReference.ProjectId); } } } } inProgressProject = inProgressProject.WithProjectReferences(newProjectReferences); if (!Enumerable.SequenceEqual(inProgressCompilation.ExternalReferences, metadataReferences)) { inProgressCompilation = inProgressCompilation.WithReferences(metadataReferences); } SolutionLogger.CreatePartialProjectState(); } private static bool IsTouchDocumentActionForDocument(CompilationAndGeneratorDriverTranslationAction action, DocumentId id) => action is CompilationAndGeneratorDriverTranslationAction.TouchDocumentAction touchDocumentAction && touchDocumentAction.DocumentId == id; /// <summary> /// Gets the final compilation if it is available. /// </summary> public bool TryGetCompilation([NotNullWhen(true)] out Compilation? compilation) { var state = ReadState(); if (state.FinalCompilationWithGeneratedDocuments != null && state.FinalCompilationWithGeneratedDocuments.TryGetValue(out var compilationOpt) && compilationOpt.HasValue) { compilation = compilationOpt.Value; return true; } compilation = null; return false; } public Task<Compilation> GetCompilationAsync(SolutionState solution, CancellationToken cancellationToken) { if (this.TryGetCompilation(out var compilation)) { // PERF: This is a hot code path and Task<TResult> isn't cheap, // so cache the completed tasks to reduce allocations. We also // need to avoid keeping a strong reference to the Compilation, // so use a ConditionalWeakTable. return SpecializedTasks.FromResult(compilation); } else { return GetCompilationSlowAsync(solution, cancellationToken); } } private async Task<Compilation> GetCompilationSlowAsync(SolutionState solution, CancellationToken cancellationToken) { var compilationInfo = await GetOrBuildCompilationInfoAsync(solution, lockGate: true, cancellationToken: cancellationToken).ConfigureAwait(false); return compilationInfo.Compilation; } private async Task<Compilation> GetOrBuildDeclarationCompilationAsync(SolutionServices solutionServices, CancellationToken cancellationToken) { try { cancellationToken.ThrowIfCancellationRequested(); using (await _buildLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { var state = ReadState(); // we are already in the final stage. just return it. var compilation = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken); if (compilation != null) { return compilation; } compilation = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken); if (compilation == null) { // let's see whether we have declaration only compilation if (state.DeclarationOnlyCompilation != null) { // okay, move to full declaration state. do this so that declaration only compilation never // realize symbols. var declarationOnlyCompilation = state.DeclarationOnlyCompilation.Clone(); WriteState(new FullDeclarationState(declarationOnlyCompilation, state.GeneratedDocuments, state.GeneratorDriver, state.GeneratedDocumentsAreFinal), solutionServices); return declarationOnlyCompilation; } // We've got nothing. Build it from scratch :( return await BuildDeclarationCompilationFromScratchAsync(solutionServices, cancellationToken).ConfigureAwait(false); } if (state is FullDeclarationState or FinalState) { // we have full declaration, just use it. return compilation; } (compilation, _, _) = await BuildDeclarationCompilationFromInProgressAsync(solutionServices, (InProgressState)state, compilation, cancellationToken).ConfigureAwait(false); // We must have an in progress compilation. Build off of that. return compilation; } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private async Task<CompilationInfo> GetOrBuildCompilationInfoAsync( SolutionState solution, bool lockGate, CancellationToken cancellationToken) { try { using (Logger.LogBlock(FunctionId.Workspace_Project_CompilationTracker_BuildCompilationAsync, s_logBuildCompilationAsync, ProjectState, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); var state = ReadState(); // Try to get the built compilation. If it exists, then we can just return that. var finalCompilation = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken); if (finalCompilation != null) { RoslynDebug.Assert(state.HasSuccessfullyLoaded.HasValue); return new CompilationInfo(finalCompilation, state.HasSuccessfullyLoaded.Value, state.GeneratedDocuments); } // Otherwise, we actually have to build it. Ensure that only one thread is trying to // build this compilation at a time. if (lockGate) { using (await _buildLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { return await BuildCompilationInfoAsync(solution, cancellationToken).ConfigureAwait(false); } } else { return await BuildCompilationInfoAsync(solution, cancellationToken).ConfigureAwait(false); } } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Builds the compilation matching the project state. In the process of building, also /// produce in progress snapshots that can be accessed from other threads. /// </summary> private Task<CompilationInfo> BuildCompilationInfoAsync( SolutionState solution, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var state = ReadState(); // if we already have a compilation, we must be already done! This can happen if two // threads were waiting to build, and we came in after the other succeeded. var compilation = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken); if (compilation != null) { RoslynDebug.Assert(state.HasSuccessfullyLoaded.HasValue); return Task.FromResult(new CompilationInfo(compilation, state.HasSuccessfullyLoaded.Value, state.GeneratedDocuments)); } compilation = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken); // If we have already reached FinalState in the past but the compilation was garbage collected, we still have the generated documents // so we can pass those to FinalizeCompilationAsync to avoid the recomputation. This is necessary for correctness as otherwise // we'd be reparsing trees which could result in generated documents changing identity. var authoritativeGeneratedDocuments = state.GeneratedDocumentsAreFinal ? state.GeneratedDocuments : (TextDocumentStates<SourceGeneratedDocumentState>?)null; var nonAuthoritativeGeneratedDocuments = state.GeneratedDocuments; var generatorDriver = state.GeneratorDriver; if (compilation == null) { // this can happen if compilation is already kicked out from the cache. // check whether the state we have support declaration only compilation if (state.DeclarationOnlyCompilation != null) { // we have declaration only compilation. build final one from it. return FinalizeCompilationAsync(solution, state.DeclarationOnlyCompilation, authoritativeGeneratedDocuments, nonAuthoritativeGeneratedDocuments, compilationWithStaleGeneratedTrees: null, generatorDriver, cancellationToken); } // We've got nothing. Build it from scratch :( return BuildCompilationInfoFromScratchAsync(solution, cancellationToken); } if (state is FullDeclarationState or FinalState) { // We have a declaration compilation, use it to reconstruct the final compilation return FinalizeCompilationAsync( solution, compilation, authoritativeGeneratedDocuments, nonAuthoritativeGeneratedDocuments, compilationWithStaleGeneratedTrees: null, generatorDriver, cancellationToken); } else { // We must have an in progress compilation. Build off of that. return BuildFinalStateFromInProgressStateAsync(solution, (InProgressState)state, compilation, cancellationToken); } } private async Task<CompilationInfo> BuildCompilationInfoFromScratchAsync( SolutionState solution, CancellationToken cancellationToken) { try { var compilation = await BuildDeclarationCompilationFromScratchAsync(solution.Services, cancellationToken).ConfigureAwait(false); return await FinalizeCompilationAsync( solution, compilation, authoritativeGeneratedDocuments: null, nonAuthoritativeGeneratedDocuments: TextDocumentStates<SourceGeneratedDocumentState>.Empty, compilationWithStaleGeneratedTrees: null, generatorDriver: null, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } [PerformanceSensitive( "https://github.com/dotnet/roslyn/issues/23582", Constraint = "Avoid calling " + nameof(Compilation.AddSyntaxTrees) + " in a loop due to allocation overhead.")] private async Task<Compilation> BuildDeclarationCompilationFromScratchAsync( SolutionServices solutionServices, CancellationToken cancellationToken) { try { var compilation = CreateEmptyCompilation(); var trees = ArrayBuilder<SyntaxTree>.GetInstance(ProjectState.DocumentStates.Count); foreach (var documentState in ProjectState.DocumentStates.GetStatesInCompilationOrder()) { cancellationToken.ThrowIfCancellationRequested(); // Include the tree even if the content of the document failed to load. trees.Add(await documentState.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false)); } compilation = compilation.AddSyntaxTrees(trees); trees.Free(); WriteState(new FullDeclarationState(compilation, TextDocumentStates<SourceGeneratedDocumentState>.Empty, generatorDriver: null, generatedDocumentsAreFinal: false), solutionServices); return compilation; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private Compilation CreateEmptyCompilation() { var compilationFactory = this.ProjectState.LanguageServices.GetRequiredService<ICompilationFactoryService>(); if (this.ProjectState.IsSubmission) { return compilationFactory.CreateSubmissionCompilation( this.ProjectState.AssemblyName, this.ProjectState.CompilationOptions!, this.ProjectState.HostObjectType); } else { return compilationFactory.CreateCompilation( this.ProjectState.AssemblyName, this.ProjectState.CompilationOptions!); } } private async Task<CompilationInfo> BuildFinalStateFromInProgressStateAsync( SolutionState solution, InProgressState state, Compilation inProgressCompilation, CancellationToken cancellationToken) { try { var (compilationWithoutGenerators, compilationWithGenerators, generatorDriver) = await BuildDeclarationCompilationFromInProgressAsync(solution.Services, state, inProgressCompilation, cancellationToken).ConfigureAwait(false); return await FinalizeCompilationAsync( solution, compilationWithoutGenerators, authoritativeGeneratedDocuments: null, nonAuthoritativeGeneratedDocuments: state.GeneratedDocuments, compilationWithGenerators, generatorDriver, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private async Task<(Compilation compilationWithoutGenerators, Compilation? compilationWithGenerators, GeneratorDriver? generatorDriver)> BuildDeclarationCompilationFromInProgressAsync( SolutionServices solutionServices, InProgressState state, Compilation compilationWithoutGenerators, CancellationToken cancellationToken) { try { var compilationWithGenerators = state.CompilationWithGeneratedDocuments; var generatorDriver = state.GeneratorDriver; // If compilationWithGenerators is the same as compilationWithoutGenerators, then it means a prior run of generators // didn't produce any files. In that case, we'll just make compilationWithGenerators null so we avoid doing any // transformations of it multiple times. Otherwise the transformations below and in FinalizeCompilationAsync will try // to update both at once, which is functionally fine but just unnecessary work. This function is always allowed to return // null for compilationWithGenerators in the end, so there's no harm there. if (compilationWithGenerators == compilationWithoutGenerators) { compilationWithGenerators = null; } var intermediateProjects = state.IntermediateProjects; while (intermediateProjects.Length > 0) { cancellationToken.ThrowIfCancellationRequested(); // We have a list of transformations to get to our final compilation; take the first transformation and apply it. var intermediateProject = intermediateProjects[0]; compilationWithoutGenerators = await intermediateProject.action.TransformCompilationAsync(compilationWithoutGenerators, cancellationToken).ConfigureAwait(false); if (compilationWithGenerators != null) { // Also transform the compilation that has generated files; we won't do that though if the transformation either would cause problems with // the generated documents, or if don't have any source generators in the first place. if (intermediateProject.action.CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput && intermediateProject.oldState.SourceGenerators.Any()) { compilationWithGenerators = await intermediateProject.action.TransformCompilationAsync(compilationWithGenerators, cancellationToken).ConfigureAwait(false); } else { compilationWithGenerators = null; } } if (generatorDriver != null) { generatorDriver = intermediateProject.action.TransformGeneratorDriver(generatorDriver); } // We have updated state, so store this new result; this allows us to drop the intermediate state we already processed // even if we were to get cancelled at a later point. intermediateProjects = intermediateProjects.RemoveAt(0); this.WriteState(State.Create(compilationWithoutGenerators, state.GeneratedDocuments, generatorDriver, compilationWithGenerators, intermediateProjects), solutionServices); } return (compilationWithoutGenerators, compilationWithGenerators, generatorDriver); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private readonly struct CompilationInfo { public Compilation Compilation { get; } public bool HasSuccessfullyLoaded { get; } public TextDocumentStates<SourceGeneratedDocumentState> GeneratedDocuments { get; } public CompilationInfo(Compilation compilation, bool hasSuccessfullyLoaded, TextDocumentStates<SourceGeneratedDocumentState> generatedDocuments) { Compilation = compilation; HasSuccessfullyLoaded = hasSuccessfullyLoaded; GeneratedDocuments = generatedDocuments; } } /// <summary> /// Add all appropriate references to the compilation and set it as our final compilation /// state. /// </summary> /// <param name="authoritativeGeneratedDocuments">The generated documents that can be used since they are already /// known to be correct for the given state. This would be non-null in cases where we had computed everything and /// ran generators, but then the compilation was garbage collected and are re-creating a compilation but we /// still had the prior generated result available.</param> /// <param name="nonAuthoritativeGeneratedDocuments">The generated documents from a previous pass which may /// or may not be correct for the current compilation. These states may be used to access cached results, if /// and when applicable for the current compilation.</param> /// <param name="compilationWithStaleGeneratedTrees">The compilation from a prior run that contains generated trees, which /// match the states included in <paramref name="nonAuthoritativeGeneratedDocuments"/>. If a generator run here produces /// the same set of generated documents as are in <paramref name="nonAuthoritativeGeneratedDocuments"/>, and we don't need to make any other /// changes to references, we can then use this compilation instead of re-adding source generated files again to the /// <paramref name="compilationWithoutGenerators"/>.</param> /// <param name="generatorDriver">The generator driver that can be reused for this finalization.</param> private async Task<CompilationInfo> FinalizeCompilationAsync( SolutionState solution, Compilation compilationWithoutGenerators, TextDocumentStates<SourceGeneratedDocumentState>? authoritativeGeneratedDocuments, TextDocumentStates<SourceGeneratedDocumentState> nonAuthoritativeGeneratedDocuments, Compilation? compilationWithStaleGeneratedTrees, GeneratorDriver? generatorDriver, CancellationToken cancellationToken) { try { // if HasAllInformation is false, then this project is always not completed. var hasSuccessfullyLoaded = this.ProjectState.HasAllInformation; var newReferences = new List<MetadataReference>(); var metadataReferenceToProjectId = new Dictionary<MetadataReference, ProjectId>(); newReferences.AddRange(this.ProjectState.MetadataReferences); foreach (var projectReference in this.ProjectState.ProjectReferences) { var referencedProject = solution.GetProjectState(projectReference.ProjectId); // Even though we're creating a final compilation (vs. an in progress compilation), // it's possible that the target project has been removed. if (referencedProject != null) { // If both projects are submissions, we'll count this as a previous submission link // instead of a regular metadata reference if (referencedProject.IsSubmission) { // if the referenced project is a submission project must be a submission as well: Debug.Assert(this.ProjectState.IsSubmission); // We now need to (potentially) update the prior submission compilation. That Compilation is held in the // ScriptCompilationInfo that we need to replace as a unit. var previousSubmissionCompilation = await solution.GetCompilationAsync(projectReference.ProjectId, cancellationToken).ConfigureAwait(false); if (compilationWithoutGenerators.ScriptCompilationInfo!.PreviousScriptCompilation != previousSubmissionCompilation) { compilationWithoutGenerators = compilationWithoutGenerators.WithScriptCompilationInfo( compilationWithoutGenerators.ScriptCompilationInfo!.WithPreviousScriptCompilation(previousSubmissionCompilation!)); compilationWithStaleGeneratedTrees = compilationWithStaleGeneratedTrees?.WithScriptCompilationInfo( compilationWithStaleGeneratedTrees.ScriptCompilationInfo!.WithPreviousScriptCompilation(previousSubmissionCompilation!)); } } else { var metadataReference = await solution.GetMetadataReferenceAsync( projectReference, this.ProjectState, cancellationToken).ConfigureAwait(false); // A reference can fail to be created if a skeleton assembly could not be constructed. if (metadataReference != null) { newReferences.Add(metadataReference); metadataReferenceToProjectId.Add(metadataReference, projectReference.ProjectId); } else { hasSuccessfullyLoaded = false; } } } } // Now that we know the set of references this compilation should have, update them if they're not already. // Generators cannot add references, so we can use the same set of references both for the compilation // that doesn't have generated files, and the one we're trying to reuse that has generated files. // Since we updated both of these compilations together in response to edits, we only have to check one // for a potential mismatch. if (!Enumerable.SequenceEqual(compilationWithoutGenerators.ExternalReferences, newReferences)) { compilationWithoutGenerators = compilationWithoutGenerators.WithReferences(newReferences); compilationWithStaleGeneratedTrees = compilationWithStaleGeneratedTrees?.WithReferences(newReferences); } // We will finalize the compilation by adding full contents here. // TODO: allow finalize compilation to incrementally update a prior version // https://github.com/dotnet/roslyn/issues/46418 Compilation compilationWithGenerators; TextDocumentStates<SourceGeneratedDocumentState> generatedDocuments; if (authoritativeGeneratedDocuments.HasValue) { generatedDocuments = authoritativeGeneratedDocuments.Value; compilationWithGenerators = compilationWithoutGenerators.AddSyntaxTrees( await generatedDocuments.States.Values.SelectAsArrayAsync(state => state.GetSyntaxTreeAsync(cancellationToken)).ConfigureAwait(false)); } else { using var generatedDocumentsBuilder = new TemporaryArray<SourceGeneratedDocumentState>(); if (ProjectState.SourceGenerators.Any()) { // If we don't already have a generator driver, we'll have to create one from scratch if (generatorDriver == null) { var additionalTexts = this.ProjectState.AdditionalDocumentStates.SelectAsArray(static documentState => documentState.AdditionalText); var compilationFactory = this.ProjectState.LanguageServices.GetRequiredService<ICompilationFactoryService>(); generatorDriver = compilationFactory.CreateGeneratorDriver( this.ProjectState.ParseOptions!, ProjectState.SourceGenerators, this.ProjectState.AnalyzerOptions.AnalyzerConfigOptionsProvider, additionalTexts); } generatorDriver = generatorDriver.RunGenerators(compilationWithoutGenerators, cancellationToken); var runResult = generatorDriver.GetRunResult(); // We may be able to reuse compilationWithStaleGeneratedTrees if the generated trees are identical. We will assign null // to compilationWithStaleGeneratedTrees if we at any point realize it can't be used. We'll first check the count of trees // if that changed then we absolutely can't reuse it. But if the counts match, we'll then see if each generated tree // content is identical to the prior generation run; if we find a match each time, then the set of the generated trees // and the prior generated trees are identical. if (compilationWithStaleGeneratedTrees != null) { if (nonAuthoritativeGeneratedDocuments.Count != runResult.Results.Sum(r => r.GeneratedSources.Length)) { compilationWithStaleGeneratedTrees = null; } } foreach (var generatorResult in runResult.Results) { foreach (var generatedSource in generatorResult.GeneratedSources) { var existing = FindExistingGeneratedDocumentState( nonAuthoritativeGeneratedDocuments, generatorResult.Generator, generatedSource.HintName); if (existing != null) { var newDocument = existing.WithUpdatedGeneratedContent( generatedSource.SourceText, this.ProjectState.ParseOptions!); generatedDocumentsBuilder.Add(newDocument); if (newDocument != existing) compilationWithStaleGeneratedTrees = null; } else { // NOTE: the use of generatedSource.SyntaxTree to fetch the path and options is OK, // since the tree is a lazy tree and that won't trigger the parse. var identity = SourceGeneratedDocumentIdentity.Generate( ProjectState.Id, generatedSource.HintName, generatorResult.Generator, generatedSource.SyntaxTree.FilePath); generatedDocumentsBuilder.Add( SourceGeneratedDocumentState.Create( identity, generatedSource.SourceText, generatedSource.SyntaxTree.Options, this.ProjectState.LanguageServices, solution.Services)); // The count of trees was the same, but something didn't match up. Since we're here, at least one tree // was added, and an equal number must have been removed. Rather than trying to incrementally update // this compilation, we'll just toss this and re-add all the trees. compilationWithStaleGeneratedTrees = null; } } } } // If we didn't null out this compilation, it means we can actually use it if (compilationWithStaleGeneratedTrees != null) { generatedDocuments = nonAuthoritativeGeneratedDocuments; compilationWithGenerators = compilationWithStaleGeneratedTrees; } else { generatedDocuments = new TextDocumentStates<SourceGeneratedDocumentState>(generatedDocumentsBuilder.ToImmutableAndClear()); compilationWithGenerators = compilationWithoutGenerators.AddSyntaxTrees( await generatedDocuments.States.Values.SelectAsArrayAsync(state => state.GetSyntaxTreeAsync(cancellationToken)).ConfigureAwait(false)); } } var finalState = FinalState.Create( State.CreateValueSource(compilationWithGenerators, solution.Services), State.CreateValueSource(compilationWithoutGenerators, solution.Services), compilationWithoutGenerators, hasSuccessfullyLoaded, generatedDocuments, generatorDriver, compilationWithGenerators, this.ProjectState.Id, metadataReferenceToProjectId); this.WriteState(finalState, solution.Services); return new CompilationInfo(compilationWithGenerators, hasSuccessfullyLoaded, generatedDocuments); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } // Local functions static SourceGeneratedDocumentState? FindExistingGeneratedDocumentState( TextDocumentStates<SourceGeneratedDocumentState> states, ISourceGenerator generator, string hintName) { var generatorAssemblyName = SourceGeneratedDocumentIdentity.GetGeneratorAssemblyName(generator); var generatorTypeName = SourceGeneratedDocumentIdentity.GetGeneratorTypeName(generator); foreach (var (_, state) in states.States) { if (state.SourceGeneratorAssemblyName != generatorAssemblyName) continue; if (state.SourceGeneratorTypeName != generatorTypeName) continue; if (state.HintName != hintName) continue; return state; } return null; } } public async Task<MetadataReference> GetMetadataReferenceAsync( SolutionState solution, ProjectState fromProject, ProjectReference projectReference, CancellationToken cancellationToken) { try { // if we already have the compilation and its right kind then use it. if (this.ProjectState.LanguageServices == fromProject.LanguageServices && this.TryGetCompilation(out var compilation)) { return compilation.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes); } // If same language then we can wrap the other project's compilation into a compilation reference if (this.ProjectState.LanguageServices == fromProject.LanguageServices) { // otherwise, base it off the compilation by building it first. compilation = await this.GetCompilationAsync(solution, cancellationToken).ConfigureAwait(false); return compilation.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes); } else { // otherwise get a metadata only image reference that is built by emitting the metadata from the referenced project's compilation and re-importing it. return await this.GetMetadataOnlyImageReferenceAsync(solution, projectReference, cancellationToken).ConfigureAwait(false); } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Attempts to get (without waiting) a metadata reference to a possibly in progress /// compilation. Only actual compilation references are returned. Could potentially /// return null if nothing can be provided. /// </summary> public CompilationReference? GetPartialMetadataReference(ProjectState fromProject, ProjectReference projectReference) { var state = ReadState(); // get compilation in any state it happens to be in right now. if (state.CompilationWithoutGeneratedDocuments != null && state.CompilationWithoutGeneratedDocuments.TryGetValue(out var compilationOpt) && compilationOpt.HasValue && ProjectState.LanguageServices == fromProject.LanguageServices) { // if we have a compilation and its the correct language, use a simple compilation reference return compilationOpt.Value.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes); } return null; } /// <summary> /// Gets a metadata reference to the metadata-only-image corresponding to the compilation. /// </summary> private async Task<MetadataReference> GetMetadataOnlyImageReferenceAsync( SolutionState solution, ProjectReference projectReference, CancellationToken cancellationToken) { try { using (Logger.LogBlock(FunctionId.Workspace_SkeletonAssembly_GetMetadataOnlyImage, cancellationToken)) { var version = await this.GetDependentSemanticVersionAsync(solution, cancellationToken).ConfigureAwait(false); // get or build compilation up to declaration state. this compilation will be used to provide live xml doc comment var declarationCompilation = await this.GetOrBuildDeclarationCompilationAsync(solution.Services, cancellationToken: cancellationToken).ConfigureAwait(false); solution.Workspace.LogTestMessage($"Looking for a cached skeleton assembly for {projectReference.ProjectId} before taking the lock..."); if (!MetadataOnlyReference.TryGetReference(solution, projectReference, declarationCompilation, version, out var reference)) { // using async build lock so we don't get multiple consumers attempting to build metadata-only images for the same compilation. using (await _buildLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { solution.Workspace.LogTestMessage($"Build lock taken for {ProjectState.Id}..."); // okay, we still don't have one. bring the compilation to final state since we are going to use it to create skeleton assembly var compilationInfo = await this.GetOrBuildCompilationInfoAsync(solution, lockGate: false, cancellationToken: cancellationToken).ConfigureAwait(false); reference = MetadataOnlyReference.GetOrBuildReference(solution, projectReference, compilationInfo.Compilation, version, cancellationToken); } } else { solution.Workspace.LogTestMessage($"Reusing the already cached skeleton assembly for {projectReference.ProjectId}"); } return reference; } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// check whether the compilation contains any declaration symbol from syntax trees with /// given name /// </summary> public bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(string name, SymbolFilter filter, CancellationToken cancellationToken) { // DO NOT expose declaration only compilation to outside since it can be held alive long time, we don't want to create any symbol from the declaration only compilation. var state = this.ReadState(); return state.DeclarationOnlyCompilation == null ? (bool?)null : state.DeclarationOnlyCompilation.ContainsSymbolsWithName(name, filter, cancellationToken); } /// <summary> /// check whether the compilation contains any declaration symbol from syntax trees with given name /// </summary> public bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken) { // DO NOT expose declaration only compilation to outside since it can be held alive long time, we don't want to create any symbol from the declaration only compilation. var state = this.ReadState(); return state.DeclarationOnlyCompilation == null ? (bool?)null : state.DeclarationOnlyCompilation.ContainsSymbolsWithName(predicate, filter, cancellationToken); } public Task<bool> HasSuccessfullyLoadedAsync(SolutionState solution, CancellationToken cancellationToken) { var state = this.ReadState(); if (state.HasSuccessfullyLoaded.HasValue) { return state.HasSuccessfullyLoaded.Value ? SpecializedTasks.True : SpecializedTasks.False; } else { return HasSuccessfullyLoadedSlowAsync(solution, cancellationToken); } } private async Task<bool> HasSuccessfullyLoadedSlowAsync(SolutionState solution, CancellationToken cancellationToken) { var compilationInfo = await GetOrBuildCompilationInfoAsync(solution, lockGate: true, cancellationToken: cancellationToken).ConfigureAwait(false); return compilationInfo.HasSuccessfullyLoaded; } public async ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(SolutionState solution, CancellationToken cancellationToken) { // If we don't have any generators, then we know we have no generated files, so we can skip the computation entirely. if (!this.ProjectState.SourceGenerators.Any()) { return TextDocumentStates<SourceGeneratedDocumentState>.Empty; } var compilationInfo = await GetOrBuildCompilationInfoAsync(solution, lockGate: true, cancellationToken: cancellationToken).ConfigureAwait(false); return compilationInfo.GeneratedDocuments; } public SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId) { var state = ReadState(); // If we are in FinalState, then we have correctly ran generators and then know the final contents of the // Compilation. The GeneratedDocuments can be filled for intermediate states, but those aren't guaranteed to be // correct and can be re-ran later. return state is FinalState finalState ? finalState.GeneratedDocuments.GetState(documentId) : null; } #region Versions // Dependent Versions are stored on compilation tracker so they are more likely to survive when unrelated solution branching occurs. private AsyncLazy<VersionStamp>? _lazyDependentVersion; private AsyncLazy<VersionStamp>? _lazyDependentSemanticVersion; public Task<VersionStamp> GetDependentVersionAsync(SolutionState solution, CancellationToken cancellationToken) { if (_lazyDependentVersion == null) { var tmp = solution; // temp. local to avoid a closure allocation for the fast path // note: solution is captured here, but it will go away once GetValueAsync executes. Interlocked.CompareExchange(ref _lazyDependentVersion, new AsyncLazy<VersionStamp>(c => ComputeDependentVersionAsync(tmp, c), cacheResult: true), null); } return _lazyDependentVersion.GetValueAsync(cancellationToken); } private async Task<VersionStamp> ComputeDependentVersionAsync(SolutionState solution, CancellationToken cancellationToken) { var projectState = this.ProjectState; var projVersion = projectState.Version; var docVersion = await projectState.GetLatestDocumentVersionAsync(cancellationToken).ConfigureAwait(false); var version = docVersion.GetNewerVersion(projVersion); foreach (var dependentProjectReference in projectState.ProjectReferences) { cancellationToken.ThrowIfCancellationRequested(); if (solution.ContainsProject(dependentProjectReference.ProjectId)) { var dependentProjectVersion = await solution.GetDependentVersionAsync(dependentProjectReference.ProjectId, cancellationToken).ConfigureAwait(false); version = dependentProjectVersion.GetNewerVersion(version); } } return version; } public Task<VersionStamp> GetDependentSemanticVersionAsync(SolutionState solution, CancellationToken cancellationToken) { if (_lazyDependentSemanticVersion == null) { var tmp = solution; // temp. local to avoid a closure allocation for the fast path // note: solution is captured here, but it will go away once GetValueAsync executes. Interlocked.CompareExchange(ref _lazyDependentSemanticVersion, new AsyncLazy<VersionStamp>(c => ComputeDependentSemanticVersionAsync(tmp, c), cacheResult: true), null); } return _lazyDependentSemanticVersion.GetValueAsync(cancellationToken); } private async Task<VersionStamp> ComputeDependentSemanticVersionAsync(SolutionState solution, CancellationToken cancellationToken) { var projectState = this.ProjectState; var version = await projectState.GetSemanticVersionAsync(cancellationToken).ConfigureAwait(false); foreach (var dependentProjectReference in projectState.ProjectReferences) { cancellationToken.ThrowIfCancellationRequested(); if (solution.ContainsProject(dependentProjectReference.ProjectId)) { var dependentProjectVersion = await solution.GetDependentSemanticVersionAsync(dependentProjectReference.ProjectId, cancellationToken).ConfigureAwait(false); version = dependentProjectVersion.GetNewerVersion(version); } } return version; } #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 System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Logging; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class SolutionState { /// <summary> /// Tracks the changes made to a project and provides the facility to get a lazily built /// compilation for that project. As the compilation is being built, the partial results are /// stored as well so that they can be used in the 'in progress' workspace snapshot. /// </summary> private partial class CompilationTracker : ICompilationTracker { private static readonly Func<ProjectState, string> s_logBuildCompilationAsync = state => string.Join(",", state.AssemblyName, state.DocumentStates.Count); public ProjectState ProjectState { get; } /// <summary> /// Access via the <see cref="ReadState"/> and <see cref="WriteState"/> methods. /// </summary> private State _stateDoNotAccessDirectly; // guarantees only one thread is building at a time private readonly SemaphoreSlim _buildLock = new(initialCount: 1); private CompilationTracker( ProjectState project, State state) { Contract.ThrowIfNull(project); this.ProjectState = project; _stateDoNotAccessDirectly = state; } /// <summary> /// Creates a tracker for the provided project. The tracker will be in the 'empty' state /// and will have no extra information beyond the project itself. /// </summary> public CompilationTracker(ProjectState project) : this(project, State.Empty) { } private State ReadState() => Volatile.Read(ref _stateDoNotAccessDirectly); private void WriteState(State state, SolutionServices solutionServices) { if (solutionServices.SupportsCachingRecoverableObjects) { // Allow the cache service to create a strong reference to the compilation. We'll get the "furthest along" compilation we have // and hold onto that. var compilationToCache = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull() ?? state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(); solutionServices.CacheService.CacheObjectIfCachingEnabledForKey(ProjectState.Id, state, compilationToCache); } Volatile.Write(ref _stateDoNotAccessDirectly, state); } public bool ContainsAssemblyOrModuleOrDynamic(ISymbol symbol, bool primary) { Debug.Assert(symbol.Kind == SymbolKind.Assembly || symbol.Kind == SymbolKind.NetModule || symbol.Kind == SymbolKind.DynamicType); var state = this.ReadState(); var unrootedSymbolSet = (state as FinalState)?.UnrootedSymbolSet; if (unrootedSymbolSet == null) { // this was not a tracker that has handed out a compilation (all compilations handed out must be // owned by a 'FinalState'). So this symbol could not be from us. return false; } return unrootedSymbolSet.Value.ContainsAssemblyOrModuleOrDynamic(symbol, primary); } /// <summary> /// Creates a new instance of the compilation info, retaining any already built /// compilation state as the now 'old' state /// </summary> public ICompilationTracker Fork( ProjectState newProject, CompilationAndGeneratorDriverTranslationAction? translate = null, CancellationToken cancellationToken = default) { var state = ReadState(); var baseCompilation = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken); if (baseCompilation != null) { var intermediateProjects = state is InProgressState inProgressState ? inProgressState.IntermediateProjects : ImmutableArray.Create<(ProjectState oldState, CompilationAndGeneratorDriverTranslationAction action)>(); if (translate is not null) { // We have a translation action; are we able to merge it with the prior one? var merged = false; if (intermediateProjects.Any()) { var (priorState, priorAction) = intermediateProjects.Last(); var mergedTranslation = translate.TryMergeWithPrior(priorAction); if (mergedTranslation != null) { // We can replace the prior action with this new one intermediateProjects = intermediateProjects.SetItem(intermediateProjects.Length - 1, (oldState: priorState, mergedTranslation)); merged = true; } } if (!merged) { // Just add it to the end intermediateProjects = intermediateProjects.Add((oldState: this.ProjectState, translate)); } } var newState = State.Create(baseCompilation, state.GeneratedDocuments, state.GeneratorDriver, state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken), intermediateProjects); return new CompilationTracker(newProject, newState); } var declarationOnlyCompilation = state.DeclarationOnlyCompilation; if (declarationOnlyCompilation != null) { if (translate != null) { var intermediateProjects = ImmutableArray.Create((this.ProjectState, translate)); return new CompilationTracker(newProject, new InProgressState(declarationOnlyCompilation, state.GeneratedDocuments, state.GeneratorDriver, compilationWithGeneratedDocuments: state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken), intermediateProjects)); } return new CompilationTracker(newProject, new LightDeclarationState(declarationOnlyCompilation, state.GeneratedDocuments, state.GeneratorDriver, generatedDocumentsAreFinal: false)); } // We have nothing. Just make a tracker that only points to the new project. We'll have // to rebuild its compilation from scratch if anyone asks for it. return new CompilationTracker(newProject); } public ICompilationTracker FreezePartialStateWithTree(SolutionState solution, DocumentState docState, SyntaxTree tree, CancellationToken cancellationToken) { GetPartialCompilationState( solution, docState.Id, out var inProgressProject, out var inProgressCompilation, out var sourceGeneratedDocuments, out var generatorDriver, out var metadataReferenceToProjectId, cancellationToken); if (!inProgressCompilation.SyntaxTrees.Contains(tree)) { var existingTree = inProgressCompilation.SyntaxTrees.FirstOrDefault(t => t.FilePath == tree.FilePath); if (existingTree != null) { inProgressCompilation = inProgressCompilation.ReplaceSyntaxTree(existingTree, tree); inProgressProject = inProgressProject.UpdateDocument(docState, textChanged: false, recalculateDependentVersions: false); } else { inProgressCompilation = inProgressCompilation.AddSyntaxTrees(tree); Debug.Assert(!inProgressProject.DocumentStates.Contains(docState.Id)); inProgressProject = inProgressProject.AddDocuments(ImmutableArray.Create(docState)); } } // The user is asking for an in progress snap. We don't want to create it and then // have the compilation immediately disappear. So we force it to stay around with a ConstantValueSource. // As a policy, all partial-state projects are said to have incomplete references, since the state has no guarantees. var finalState = FinalState.Create( new ConstantValueSource<Optional<Compilation>>(inProgressCompilation), new ConstantValueSource<Optional<Compilation>>(inProgressCompilation), inProgressCompilation, hasSuccessfullyLoaded: false, sourceGeneratedDocuments, generatorDriver, inProgressCompilation, this.ProjectState.Id, metadataReferenceToProjectId); return new CompilationTracker(inProgressProject, finalState); } /// <summary> /// Tries to get the latest snapshot of the compilation without waiting for it to be /// fully built. This method takes advantage of the progress side-effect produced during /// <see cref="BuildCompilationInfoAsync(SolutionState, CancellationToken)"/>. /// It will either return the already built compilation, any /// in-progress compilation or any known old compilation in that order of preference. /// The compilation state that is returned will have a compilation that is retained so /// that it cannot disappear. /// </summary> /// <param name="inProgressCompilation">The compilation to return. Contains any source generated documents that were available already added.</param> private void GetPartialCompilationState( SolutionState solution, DocumentId id, out ProjectState inProgressProject, out Compilation inProgressCompilation, out TextDocumentStates<SourceGeneratedDocumentState> sourceGeneratedDocuments, out GeneratorDriver? generatorDriver, out Dictionary<MetadataReference, ProjectId>? metadataReferenceToProjectId, CancellationToken cancellationToken) { var state = ReadState(); var compilationWithoutGeneratedDocuments = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken); // check whether we can bail out quickly for typing case var inProgressState = state as InProgressState; sourceGeneratedDocuments = state.GeneratedDocuments; generatorDriver = state.GeneratorDriver; // all changes left for this document is modifying the given document. // we can use current state as it is since we will replace the document with latest document anyway. if (inProgressState != null && compilationWithoutGeneratedDocuments != null && inProgressState.IntermediateProjects.All(t => IsTouchDocumentActionForDocument(t.action, id))) { inProgressProject = ProjectState; // We'll add in whatever generated documents we do have; these may be from a prior run prior to some changes // being made to the project, but it's the best we have so we'll use it. inProgressCompilation = compilationWithoutGeneratedDocuments.AddSyntaxTrees(sourceGeneratedDocuments.States.Values.Select(state => state.GetSyntaxTree(cancellationToken))); // This is likely a bug. It seems possible to pass out a partial compilation state that we don't // properly record assembly symbols for. metadataReferenceToProjectId = null; SolutionLogger.UseExistingPartialProjectState(); return; } inProgressProject = inProgressState != null ? inProgressState.IntermediateProjects.First().oldState : this.ProjectState; // if we already have a final compilation we are done. if (compilationWithoutGeneratedDocuments != null && state is FinalState finalState) { var finalCompilation = finalState.FinalCompilationWithGeneratedDocuments.GetValueOrNull(cancellationToken); if (finalCompilation != null) { inProgressCompilation = finalCompilation; // This should hopefully be safe to return as null. Because we already reached the 'FinalState' // before, we should have already recorded the assembly symbols for it. So not recording them // again is likely ok (as long as compilations continue to return the same IAssemblySymbols for // the same references across source edits). metadataReferenceToProjectId = null; SolutionLogger.UseExistingFullProjectState(); return; } } // 1) if we have an in-progress compilation use it. // 2) If we don't, then create a simple empty compilation/project. // 3) then, make sure that all it's p2p refs and whatnot are correct. if (compilationWithoutGeneratedDocuments == null) { inProgressProject = inProgressProject.RemoveAllDocuments(); inProgressCompilation = CreateEmptyCompilation(); } else { inProgressCompilation = compilationWithoutGeneratedDocuments; } inProgressCompilation = inProgressCompilation.AddSyntaxTrees(sourceGeneratedDocuments.States.Values.Select(state => state.GetSyntaxTree(cancellationToken))); // Now add in back a consistent set of project references. For project references // try to get either a CompilationReference or a SkeletonReference. This ensures // that the in-progress project only reports a reference to another project if it // could actually get a reference to that project's metadata. var metadataReferences = new List<MetadataReference>(); var newProjectReferences = new List<ProjectReference>(); metadataReferences.AddRange(this.ProjectState.MetadataReferences); metadataReferenceToProjectId = new Dictionary<MetadataReference, ProjectId>(); foreach (var projectReference in this.ProjectState.ProjectReferences) { var referencedProject = solution.GetProjectState(projectReference.ProjectId); if (referencedProject != null) { if (referencedProject.IsSubmission) { var previousScriptCompilation = solution.GetCompilationAsync(projectReference.ProjectId, cancellationToken).WaitAndGetResult(cancellationToken); // previous submission project must support compilation: RoslynDebug.Assert(previousScriptCompilation != null); inProgressCompilation = inProgressCompilation.WithScriptCompilationInfo(inProgressCompilation.ScriptCompilationInfo!.WithPreviousScriptCompilation(previousScriptCompilation)); } else { // get the latest metadata for the partial compilation of the referenced project. var metadata = solution.GetPartialMetadataReference(projectReference, this.ProjectState); if (metadata == null) { // if we failed to get the metadata, check to see if we previously had existing metadata and reuse it instead. var inProgressCompilationNotRef = inProgressCompilation; metadata = inProgressCompilationNotRef.ExternalReferences.FirstOrDefault( r => solution.GetProjectState(inProgressCompilationNotRef.GetAssemblyOrModuleSymbol(r) as IAssemblySymbol)?.Id == projectReference.ProjectId); } if (metadata != null) { newProjectReferences.Add(projectReference); metadataReferences.Add(metadata); metadataReferenceToProjectId.Add(metadata, projectReference.ProjectId); } } } } inProgressProject = inProgressProject.WithProjectReferences(newProjectReferences); if (!Enumerable.SequenceEqual(inProgressCompilation.ExternalReferences, metadataReferences)) { inProgressCompilation = inProgressCompilation.WithReferences(metadataReferences); } SolutionLogger.CreatePartialProjectState(); } private static bool IsTouchDocumentActionForDocument(CompilationAndGeneratorDriverTranslationAction action, DocumentId id) => action is CompilationAndGeneratorDriverTranslationAction.TouchDocumentAction touchDocumentAction && touchDocumentAction.DocumentId == id; /// <summary> /// Gets the final compilation if it is available. /// </summary> public bool TryGetCompilation([NotNullWhen(true)] out Compilation? compilation) { var state = ReadState(); if (state.FinalCompilationWithGeneratedDocuments != null && state.FinalCompilationWithGeneratedDocuments.TryGetValue(out var compilationOpt) && compilationOpt.HasValue) { compilation = compilationOpt.Value; return true; } compilation = null; return false; } public Task<Compilation> GetCompilationAsync(SolutionState solution, CancellationToken cancellationToken) { if (this.TryGetCompilation(out var compilation)) { // PERF: This is a hot code path and Task<TResult> isn't cheap, // so cache the completed tasks to reduce allocations. We also // need to avoid keeping a strong reference to the Compilation, // so use a ConditionalWeakTable. return SpecializedTasks.FromResult(compilation); } else { return GetCompilationSlowAsync(solution, cancellationToken); } } private async Task<Compilation> GetCompilationSlowAsync(SolutionState solution, CancellationToken cancellationToken) { var compilationInfo = await GetOrBuildCompilationInfoAsync(solution, lockGate: true, cancellationToken: cancellationToken).ConfigureAwait(false); return compilationInfo.Compilation; } private async Task<Compilation> GetOrBuildDeclarationCompilationAsync(SolutionServices solutionServices, CancellationToken cancellationToken) { try { cancellationToken.ThrowIfCancellationRequested(); using (await _buildLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { var state = ReadState(); // we are already in the final stage. just return it. var compilation = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken); if (compilation != null) { return compilation; } compilation = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken); if (compilation == null) { // let's see whether we have declaration only compilation if (state.DeclarationOnlyCompilation != null) { // okay, move to full declaration state. do this so that declaration only compilation never // realize symbols. var declarationOnlyCompilation = state.DeclarationOnlyCompilation.Clone(); WriteState(new FullDeclarationState(declarationOnlyCompilation, state.GeneratedDocuments, state.GeneratorDriver, state.GeneratedDocumentsAreFinal), solutionServices); return declarationOnlyCompilation; } // We've got nothing. Build it from scratch :( return await BuildDeclarationCompilationFromScratchAsync(solutionServices, cancellationToken).ConfigureAwait(false); } if (state is FullDeclarationState or FinalState) { // we have full declaration, just use it. return compilation; } (compilation, _, _) = await BuildDeclarationCompilationFromInProgressAsync(solutionServices, (InProgressState)state, compilation, cancellationToken).ConfigureAwait(false); // We must have an in progress compilation. Build off of that. return compilation; } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private async Task<CompilationInfo> GetOrBuildCompilationInfoAsync( SolutionState solution, bool lockGate, CancellationToken cancellationToken) { try { using (Logger.LogBlock(FunctionId.Workspace_Project_CompilationTracker_BuildCompilationAsync, s_logBuildCompilationAsync, ProjectState, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); var state = ReadState(); // Try to get the built compilation. If it exists, then we can just return that. var finalCompilation = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken); if (finalCompilation != null) { RoslynDebug.Assert(state.HasSuccessfullyLoaded.HasValue); return new CompilationInfo(finalCompilation, state.HasSuccessfullyLoaded.Value, state.GeneratedDocuments); } // Otherwise, we actually have to build it. Ensure that only one thread is trying to // build this compilation at a time. if (lockGate) { using (await _buildLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { return await BuildCompilationInfoAsync(solution, cancellationToken).ConfigureAwait(false); } } else { return await BuildCompilationInfoAsync(solution, cancellationToken).ConfigureAwait(false); } } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Builds the compilation matching the project state. In the process of building, also /// produce in progress snapshots that can be accessed from other threads. /// </summary> private Task<CompilationInfo> BuildCompilationInfoAsync( SolutionState solution, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var state = ReadState(); // if we already have a compilation, we must be already done! This can happen if two // threads were waiting to build, and we came in after the other succeeded. var compilation = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken); if (compilation != null) { RoslynDebug.Assert(state.HasSuccessfullyLoaded.HasValue); return Task.FromResult(new CompilationInfo(compilation, state.HasSuccessfullyLoaded.Value, state.GeneratedDocuments)); } compilation = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken); // If we have already reached FinalState in the past but the compilation was garbage collected, we still have the generated documents // so we can pass those to FinalizeCompilationAsync to avoid the recomputation. This is necessary for correctness as otherwise // we'd be reparsing trees which could result in generated documents changing identity. var authoritativeGeneratedDocuments = state.GeneratedDocumentsAreFinal ? state.GeneratedDocuments : (TextDocumentStates<SourceGeneratedDocumentState>?)null; var nonAuthoritativeGeneratedDocuments = state.GeneratedDocuments; var generatorDriver = state.GeneratorDriver; if (compilation == null) { // this can happen if compilation is already kicked out from the cache. // check whether the state we have support declaration only compilation if (state.DeclarationOnlyCompilation != null) { // we have declaration only compilation. build final one from it. return FinalizeCompilationAsync(solution, state.DeclarationOnlyCompilation, authoritativeGeneratedDocuments, nonAuthoritativeGeneratedDocuments, compilationWithStaleGeneratedTrees: null, generatorDriver, cancellationToken); } // We've got nothing. Build it from scratch :( return BuildCompilationInfoFromScratchAsync(solution, cancellationToken); } if (state is FullDeclarationState or FinalState) { // We have a declaration compilation, use it to reconstruct the final compilation return FinalizeCompilationAsync( solution, compilation, authoritativeGeneratedDocuments, nonAuthoritativeGeneratedDocuments, compilationWithStaleGeneratedTrees: null, generatorDriver, cancellationToken); } else { // We must have an in progress compilation. Build off of that. return BuildFinalStateFromInProgressStateAsync(solution, (InProgressState)state, compilation, cancellationToken); } } private async Task<CompilationInfo> BuildCompilationInfoFromScratchAsync( SolutionState solution, CancellationToken cancellationToken) { try { var compilation = await BuildDeclarationCompilationFromScratchAsync(solution.Services, cancellationToken).ConfigureAwait(false); return await FinalizeCompilationAsync( solution, compilation, authoritativeGeneratedDocuments: null, nonAuthoritativeGeneratedDocuments: TextDocumentStates<SourceGeneratedDocumentState>.Empty, compilationWithStaleGeneratedTrees: null, generatorDriver: null, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } [PerformanceSensitive( "https://github.com/dotnet/roslyn/issues/23582", Constraint = "Avoid calling " + nameof(Compilation.AddSyntaxTrees) + " in a loop due to allocation overhead.")] private async Task<Compilation> BuildDeclarationCompilationFromScratchAsync( SolutionServices solutionServices, CancellationToken cancellationToken) { try { var compilation = CreateEmptyCompilation(); var trees = ArrayBuilder<SyntaxTree>.GetInstance(ProjectState.DocumentStates.Count); foreach (var documentState in ProjectState.DocumentStates.GetStatesInCompilationOrder()) { cancellationToken.ThrowIfCancellationRequested(); // Include the tree even if the content of the document failed to load. trees.Add(await documentState.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false)); } compilation = compilation.AddSyntaxTrees(trees); trees.Free(); WriteState(new FullDeclarationState(compilation, TextDocumentStates<SourceGeneratedDocumentState>.Empty, generatorDriver: null, generatedDocumentsAreFinal: false), solutionServices); return compilation; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private Compilation CreateEmptyCompilation() { var compilationFactory = this.ProjectState.LanguageServices.GetRequiredService<ICompilationFactoryService>(); if (this.ProjectState.IsSubmission) { return compilationFactory.CreateSubmissionCompilation( this.ProjectState.AssemblyName, this.ProjectState.CompilationOptions!, this.ProjectState.HostObjectType); } else { return compilationFactory.CreateCompilation( this.ProjectState.AssemblyName, this.ProjectState.CompilationOptions!); } } private async Task<CompilationInfo> BuildFinalStateFromInProgressStateAsync( SolutionState solution, InProgressState state, Compilation inProgressCompilation, CancellationToken cancellationToken) { try { var (compilationWithoutGenerators, compilationWithGenerators, generatorDriver) = await BuildDeclarationCompilationFromInProgressAsync(solution.Services, state, inProgressCompilation, cancellationToken).ConfigureAwait(false); return await FinalizeCompilationAsync( solution, compilationWithoutGenerators, authoritativeGeneratedDocuments: null, nonAuthoritativeGeneratedDocuments: state.GeneratedDocuments, compilationWithGenerators, generatorDriver, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private async Task<(Compilation compilationWithoutGenerators, Compilation? compilationWithGenerators, GeneratorDriver? generatorDriver)> BuildDeclarationCompilationFromInProgressAsync( SolutionServices solutionServices, InProgressState state, Compilation compilationWithoutGenerators, CancellationToken cancellationToken) { try { var compilationWithGenerators = state.CompilationWithGeneratedDocuments; var generatorDriver = state.GeneratorDriver; // If compilationWithGenerators is the same as compilationWithoutGenerators, then it means a prior run of generators // didn't produce any files. In that case, we'll just make compilationWithGenerators null so we avoid doing any // transformations of it multiple times. Otherwise the transformations below and in FinalizeCompilationAsync will try // to update both at once, which is functionally fine but just unnecessary work. This function is always allowed to return // null for compilationWithGenerators in the end, so there's no harm there. if (compilationWithGenerators == compilationWithoutGenerators) { compilationWithGenerators = null; } var intermediateProjects = state.IntermediateProjects; while (intermediateProjects.Length > 0) { cancellationToken.ThrowIfCancellationRequested(); // We have a list of transformations to get to our final compilation; take the first transformation and apply it. var intermediateProject = intermediateProjects[0]; compilationWithoutGenerators = await intermediateProject.action.TransformCompilationAsync(compilationWithoutGenerators, cancellationToken).ConfigureAwait(false); if (compilationWithGenerators != null) { // Also transform the compilation that has generated files; we won't do that though if the transformation either would cause problems with // the generated documents, or if don't have any source generators in the first place. if (intermediateProject.action.CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput && intermediateProject.oldState.SourceGenerators.Any()) { compilationWithGenerators = await intermediateProject.action.TransformCompilationAsync(compilationWithGenerators, cancellationToken).ConfigureAwait(false); } else { compilationWithGenerators = null; } } if (generatorDriver != null) { generatorDriver = intermediateProject.action.TransformGeneratorDriver(generatorDriver); } // We have updated state, so store this new result; this allows us to drop the intermediate state we already processed // even if we were to get cancelled at a later point. intermediateProjects = intermediateProjects.RemoveAt(0); this.WriteState(State.Create(compilationWithoutGenerators, state.GeneratedDocuments, generatorDriver, compilationWithGenerators, intermediateProjects), solutionServices); } return (compilationWithoutGenerators, compilationWithGenerators, generatorDriver); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private readonly struct CompilationInfo { public Compilation Compilation { get; } public bool HasSuccessfullyLoaded { get; } public TextDocumentStates<SourceGeneratedDocumentState> GeneratedDocuments { get; } public CompilationInfo(Compilation compilation, bool hasSuccessfullyLoaded, TextDocumentStates<SourceGeneratedDocumentState> generatedDocuments) { Compilation = compilation; HasSuccessfullyLoaded = hasSuccessfullyLoaded; GeneratedDocuments = generatedDocuments; } } /// <summary> /// Add all appropriate references to the compilation and set it as our final compilation /// state. /// </summary> /// <param name="authoritativeGeneratedDocuments">The generated documents that can be used since they are already /// known to be correct for the given state. This would be non-null in cases where we had computed everything and /// ran generators, but then the compilation was garbage collected and are re-creating a compilation but we /// still had the prior generated result available.</param> /// <param name="nonAuthoritativeGeneratedDocuments">The generated documents from a previous pass which may /// or may not be correct for the current compilation. These states may be used to access cached results, if /// and when applicable for the current compilation.</param> /// <param name="compilationWithStaleGeneratedTrees">The compilation from a prior run that contains generated trees, which /// match the states included in <paramref name="nonAuthoritativeGeneratedDocuments"/>. If a generator run here produces /// the same set of generated documents as are in <paramref name="nonAuthoritativeGeneratedDocuments"/>, and we don't need to make any other /// changes to references, we can then use this compilation instead of re-adding source generated files again to the /// <paramref name="compilationWithoutGenerators"/>.</param> /// <param name="generatorDriver">The generator driver that can be reused for this finalization.</param> private async Task<CompilationInfo> FinalizeCompilationAsync( SolutionState solution, Compilation compilationWithoutGenerators, TextDocumentStates<SourceGeneratedDocumentState>? authoritativeGeneratedDocuments, TextDocumentStates<SourceGeneratedDocumentState> nonAuthoritativeGeneratedDocuments, Compilation? compilationWithStaleGeneratedTrees, GeneratorDriver? generatorDriver, CancellationToken cancellationToken) { try { // if HasAllInformation is false, then this project is always not completed. var hasSuccessfullyLoaded = this.ProjectState.HasAllInformation; var newReferences = new List<MetadataReference>(); var metadataReferenceToProjectId = new Dictionary<MetadataReference, ProjectId>(); newReferences.AddRange(this.ProjectState.MetadataReferences); foreach (var projectReference in this.ProjectState.ProjectReferences) { var referencedProject = solution.GetProjectState(projectReference.ProjectId); // Even though we're creating a final compilation (vs. an in progress compilation), // it's possible that the target project has been removed. if (referencedProject != null) { // If both projects are submissions, we'll count this as a previous submission link // instead of a regular metadata reference if (referencedProject.IsSubmission) { // if the referenced project is a submission project must be a submission as well: Debug.Assert(this.ProjectState.IsSubmission); // We now need to (potentially) update the prior submission compilation. That Compilation is held in the // ScriptCompilationInfo that we need to replace as a unit. var previousSubmissionCompilation = await solution.GetCompilationAsync(projectReference.ProjectId, cancellationToken).ConfigureAwait(false); if (compilationWithoutGenerators.ScriptCompilationInfo!.PreviousScriptCompilation != previousSubmissionCompilation) { compilationWithoutGenerators = compilationWithoutGenerators.WithScriptCompilationInfo( compilationWithoutGenerators.ScriptCompilationInfo!.WithPreviousScriptCompilation(previousSubmissionCompilation!)); compilationWithStaleGeneratedTrees = compilationWithStaleGeneratedTrees?.WithScriptCompilationInfo( compilationWithStaleGeneratedTrees.ScriptCompilationInfo!.WithPreviousScriptCompilation(previousSubmissionCompilation!)); } } else { var metadataReference = await solution.GetMetadataReferenceAsync( projectReference, this.ProjectState, cancellationToken).ConfigureAwait(false); // A reference can fail to be created if a skeleton assembly could not be constructed. if (metadataReference != null) { newReferences.Add(metadataReference); metadataReferenceToProjectId.Add(metadataReference, projectReference.ProjectId); } else { hasSuccessfullyLoaded = false; } } } } // Now that we know the set of references this compilation should have, update them if they're not already. // Generators cannot add references, so we can use the same set of references both for the compilation // that doesn't have generated files, and the one we're trying to reuse that has generated files. // Since we updated both of these compilations together in response to edits, we only have to check one // for a potential mismatch. if (!Enumerable.SequenceEqual(compilationWithoutGenerators.ExternalReferences, newReferences)) { compilationWithoutGenerators = compilationWithoutGenerators.WithReferences(newReferences); compilationWithStaleGeneratedTrees = compilationWithStaleGeneratedTrees?.WithReferences(newReferences); } // We will finalize the compilation by adding full contents here. // TODO: allow finalize compilation to incrementally update a prior version // https://github.com/dotnet/roslyn/issues/46418 Compilation compilationWithGenerators; TextDocumentStates<SourceGeneratedDocumentState> generatedDocuments; if (authoritativeGeneratedDocuments.HasValue) { generatedDocuments = authoritativeGeneratedDocuments.Value; compilationWithGenerators = compilationWithoutGenerators.AddSyntaxTrees( await generatedDocuments.States.Values.SelectAsArrayAsync(state => state.GetSyntaxTreeAsync(cancellationToken)).ConfigureAwait(false)); } else { using var generatedDocumentsBuilder = new TemporaryArray<SourceGeneratedDocumentState>(); if (ProjectState.SourceGenerators.Any()) { // If we don't already have a generator driver, we'll have to create one from scratch if (generatorDriver == null) { var additionalTexts = this.ProjectState.AdditionalDocumentStates.SelectAsArray(static documentState => documentState.AdditionalText); var compilationFactory = this.ProjectState.LanguageServices.GetRequiredService<ICompilationFactoryService>(); generatorDriver = compilationFactory.CreateGeneratorDriver( this.ProjectState.ParseOptions!, ProjectState.SourceGenerators, this.ProjectState.AnalyzerOptions.AnalyzerConfigOptionsProvider, additionalTexts); } generatorDriver = generatorDriver.RunGenerators(compilationWithoutGenerators, cancellationToken); var runResult = generatorDriver.GetRunResult(); // We may be able to reuse compilationWithStaleGeneratedTrees if the generated trees are identical. We will assign null // to compilationWithStaleGeneratedTrees if we at any point realize it can't be used. We'll first check the count of trees // if that changed then we absolutely can't reuse it. But if the counts match, we'll then see if each generated tree // content is identical to the prior generation run; if we find a match each time, then the set of the generated trees // and the prior generated trees are identical. if (compilationWithStaleGeneratedTrees != null) { if (nonAuthoritativeGeneratedDocuments.Count != runResult.Results.Sum(r => r.GeneratedSources.Length)) { compilationWithStaleGeneratedTrees = null; } } foreach (var generatorResult in runResult.Results) { foreach (var generatedSource in generatorResult.GeneratedSources) { var existing = FindExistingGeneratedDocumentState( nonAuthoritativeGeneratedDocuments, generatorResult.Generator, generatedSource.HintName); if (existing != null) { var newDocument = existing.WithUpdatedGeneratedContent( generatedSource.SourceText, this.ProjectState.ParseOptions!); generatedDocumentsBuilder.Add(newDocument); if (newDocument != existing) compilationWithStaleGeneratedTrees = null; } else { // NOTE: the use of generatedSource.SyntaxTree to fetch the path and options is OK, // since the tree is a lazy tree and that won't trigger the parse. var identity = SourceGeneratedDocumentIdentity.Generate( ProjectState.Id, generatedSource.HintName, generatorResult.Generator, generatedSource.SyntaxTree.FilePath); generatedDocumentsBuilder.Add( SourceGeneratedDocumentState.Create( identity, generatedSource.SourceText, generatedSource.SyntaxTree.Options, this.ProjectState.LanguageServices, solution.Services)); // The count of trees was the same, but something didn't match up. Since we're here, at least one tree // was added, and an equal number must have been removed. Rather than trying to incrementally update // this compilation, we'll just toss this and re-add all the trees. compilationWithStaleGeneratedTrees = null; } } } } // If we didn't null out this compilation, it means we can actually use it if (compilationWithStaleGeneratedTrees != null) { generatedDocuments = nonAuthoritativeGeneratedDocuments; compilationWithGenerators = compilationWithStaleGeneratedTrees; } else { generatedDocuments = new TextDocumentStates<SourceGeneratedDocumentState>(generatedDocumentsBuilder.ToImmutableAndClear()); compilationWithGenerators = compilationWithoutGenerators.AddSyntaxTrees( await generatedDocuments.States.Values.SelectAsArrayAsync(state => state.GetSyntaxTreeAsync(cancellationToken)).ConfigureAwait(false)); } } var finalState = FinalState.Create( State.CreateValueSource(compilationWithGenerators, solution.Services), State.CreateValueSource(compilationWithoutGenerators, solution.Services), compilationWithoutGenerators, hasSuccessfullyLoaded, generatedDocuments, generatorDriver, compilationWithGenerators, this.ProjectState.Id, metadataReferenceToProjectId); this.WriteState(finalState, solution.Services); return new CompilationInfo(compilationWithGenerators, hasSuccessfullyLoaded, generatedDocuments); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } // Local functions static SourceGeneratedDocumentState? FindExistingGeneratedDocumentState( TextDocumentStates<SourceGeneratedDocumentState> states, ISourceGenerator generator, string hintName) { var generatorAssemblyName = SourceGeneratedDocumentIdentity.GetGeneratorAssemblyName(generator); var generatorTypeName = SourceGeneratedDocumentIdentity.GetGeneratorTypeName(generator); foreach (var (_, state) in states.States) { if (state.SourceGeneratorAssemblyName != generatorAssemblyName) continue; if (state.SourceGeneratorTypeName != generatorTypeName) continue; if (state.HintName != hintName) continue; return state; } return null; } } public async Task<MetadataReference> GetMetadataReferenceAsync( SolutionState solution, ProjectState fromProject, ProjectReference projectReference, CancellationToken cancellationToken) { try { // if we already have the compilation and its right kind then use it. if (this.ProjectState.LanguageServices == fromProject.LanguageServices && this.TryGetCompilation(out var compilation)) { return compilation.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes); } // If same language then we can wrap the other project's compilation into a compilation reference if (this.ProjectState.LanguageServices == fromProject.LanguageServices) { // otherwise, base it off the compilation by building it first. compilation = await this.GetCompilationAsync(solution, cancellationToken).ConfigureAwait(false); return compilation.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes); } else { // otherwise get a metadata only image reference that is built by emitting the metadata from the referenced project's compilation and re-importing it. return await this.GetMetadataOnlyImageReferenceAsync(solution, projectReference, cancellationToken).ConfigureAwait(false); } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Attempts to get (without waiting) a metadata reference to a possibly in progress /// compilation. Only actual compilation references are returned. Could potentially /// return null if nothing can be provided. /// </summary> public CompilationReference? GetPartialMetadataReference(ProjectState fromProject, ProjectReference projectReference) { var state = ReadState(); // get compilation in any state it happens to be in right now. if (state.CompilationWithoutGeneratedDocuments != null && state.CompilationWithoutGeneratedDocuments.TryGetValue(out var compilationOpt) && compilationOpt.HasValue && ProjectState.LanguageServices == fromProject.LanguageServices) { // if we have a compilation and its the correct language, use a simple compilation reference return compilationOpt.Value.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes); } return null; } /// <summary> /// Gets a metadata reference to the metadata-only-image corresponding to the compilation. /// </summary> private async Task<MetadataReference> GetMetadataOnlyImageReferenceAsync( SolutionState solution, ProjectReference projectReference, CancellationToken cancellationToken) { try { using (Logger.LogBlock(FunctionId.Workspace_SkeletonAssembly_GetMetadataOnlyImage, cancellationToken)) { var version = await this.GetDependentSemanticVersionAsync(solution, cancellationToken).ConfigureAwait(false); // get or build compilation up to declaration state. this compilation will be used to provide live xml doc comment var declarationCompilation = await this.GetOrBuildDeclarationCompilationAsync(solution.Services, cancellationToken: cancellationToken).ConfigureAwait(false); solution.Workspace.LogTestMessage($"Looking for a cached skeleton assembly for {projectReference.ProjectId} before taking the lock..."); if (!MetadataOnlyReference.TryGetReference(solution, projectReference, declarationCompilation, version, out var reference)) { // using async build lock so we don't get multiple consumers attempting to build metadata-only images for the same compilation. using (await _buildLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { solution.Workspace.LogTestMessage($"Build lock taken for {ProjectState.Id}..."); // okay, we still don't have one. bring the compilation to final state since we are going to use it to create skeleton assembly var compilationInfo = await this.GetOrBuildCompilationInfoAsync(solution, lockGate: false, cancellationToken: cancellationToken).ConfigureAwait(false); reference = MetadataOnlyReference.GetOrBuildReference(solution, projectReference, compilationInfo.Compilation, version, cancellationToken); } } else { solution.Workspace.LogTestMessage($"Reusing the already cached skeleton assembly for {projectReference.ProjectId}"); } return reference; } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// check whether the compilation contains any declaration symbol from syntax trees with /// given name /// </summary> public bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(string name, SymbolFilter filter, CancellationToken cancellationToken) { // DO NOT expose declaration only compilation to outside since it can be held alive long time, we don't want to create any symbol from the declaration only compilation. var state = this.ReadState(); return state.DeclarationOnlyCompilation == null ? (bool?)null : state.DeclarationOnlyCompilation.ContainsSymbolsWithName(name, filter, cancellationToken); } /// <summary> /// check whether the compilation contains any declaration symbol from syntax trees with given name /// </summary> public bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken) { // DO NOT expose declaration only compilation to outside since it can be held alive long time, we don't want to create any symbol from the declaration only compilation. var state = this.ReadState(); return state.DeclarationOnlyCompilation == null ? (bool?)null : state.DeclarationOnlyCompilation.ContainsSymbolsWithName(predicate, filter, cancellationToken); } public Task<bool> HasSuccessfullyLoadedAsync(SolutionState solution, CancellationToken cancellationToken) { var state = this.ReadState(); if (state.HasSuccessfullyLoaded.HasValue) { return state.HasSuccessfullyLoaded.Value ? SpecializedTasks.True : SpecializedTasks.False; } else { return HasSuccessfullyLoadedSlowAsync(solution, cancellationToken); } } private async Task<bool> HasSuccessfullyLoadedSlowAsync(SolutionState solution, CancellationToken cancellationToken) { var compilationInfo = await GetOrBuildCompilationInfoAsync(solution, lockGate: true, cancellationToken: cancellationToken).ConfigureAwait(false); return compilationInfo.HasSuccessfullyLoaded; } public async ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(SolutionState solution, CancellationToken cancellationToken) { // If we don't have any generators, then we know we have no generated files, so we can skip the computation entirely. if (!this.ProjectState.SourceGenerators.Any()) { return TextDocumentStates<SourceGeneratedDocumentState>.Empty; } var compilationInfo = await GetOrBuildCompilationInfoAsync(solution, lockGate: true, cancellationToken: cancellationToken).ConfigureAwait(false); return compilationInfo.GeneratedDocuments; } public SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId) { var state = ReadState(); // If we are in FinalState, then we have correctly ran generators and then know the final contents of the // Compilation. The GeneratedDocuments can be filled for intermediate states, but those aren't guaranteed to be // correct and can be re-ran later. return state is FinalState finalState ? finalState.GeneratedDocuments.GetState(documentId) : null; } #region Versions // Dependent Versions are stored on compilation tracker so they are more likely to survive when unrelated solution branching occurs. private AsyncLazy<VersionStamp>? _lazyDependentVersion; private AsyncLazy<VersionStamp>? _lazyDependentSemanticVersion; public Task<VersionStamp> GetDependentVersionAsync(SolutionState solution, CancellationToken cancellationToken) { if (_lazyDependentVersion == null) { var tmp = solution; // temp. local to avoid a closure allocation for the fast path // note: solution is captured here, but it will go away once GetValueAsync executes. Interlocked.CompareExchange(ref _lazyDependentVersion, new AsyncLazy<VersionStamp>(c => ComputeDependentVersionAsync(tmp, c), cacheResult: true), null); } return _lazyDependentVersion.GetValueAsync(cancellationToken); } private async Task<VersionStamp> ComputeDependentVersionAsync(SolutionState solution, CancellationToken cancellationToken) { var projectState = this.ProjectState; var projVersion = projectState.Version; var docVersion = await projectState.GetLatestDocumentVersionAsync(cancellationToken).ConfigureAwait(false); var version = docVersion.GetNewerVersion(projVersion); foreach (var dependentProjectReference in projectState.ProjectReferences) { cancellationToken.ThrowIfCancellationRequested(); if (solution.ContainsProject(dependentProjectReference.ProjectId)) { var dependentProjectVersion = await solution.GetDependentVersionAsync(dependentProjectReference.ProjectId, cancellationToken).ConfigureAwait(false); version = dependentProjectVersion.GetNewerVersion(version); } } return version; } public Task<VersionStamp> GetDependentSemanticVersionAsync(SolutionState solution, CancellationToken cancellationToken) { if (_lazyDependentSemanticVersion == null) { var tmp = solution; // temp. local to avoid a closure allocation for the fast path // note: solution is captured here, but it will go away once GetValueAsync executes. Interlocked.CompareExchange(ref _lazyDependentSemanticVersion, new AsyncLazy<VersionStamp>(c => ComputeDependentSemanticVersionAsync(tmp, c), cacheResult: true), null); } return _lazyDependentSemanticVersion.GetValueAsync(cancellationToken); } private async Task<VersionStamp> ComputeDependentSemanticVersionAsync(SolutionState solution, CancellationToken cancellationToken) { var projectState = this.ProjectState; var version = await projectState.GetSemanticVersionAsync(cancellationToken).ConfigureAwait(false); foreach (var dependentProjectReference in projectState.ProjectReferences) { cancellationToken.ThrowIfCancellationRequested(); if (solution.ContainsProject(dependentProjectReference.ProjectId)) { var dependentProjectVersion = await solution.GetDependentSemanticVersionAsync(dependentProjectReference.ProjectId, cancellationToken).ConfigureAwait(false); version = dependentProjectVersion.GetNewerVersion(version); } } return version; } #endregion } } }
1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.GeneratedFileReplacingCompilationTracker.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 System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class SolutionState { /// <summary> /// An implementation of <see cref="ICompilationTracker"/> that takes a compilation from another compilation tracker and updates it /// to return a generated document with a specific content, regardless of what the generator actually produces. In other words, it says /// "take the compilation this other thing produced, and pretend the generator gave this content, even if it wouldn't." /// </summary> private class GeneratedFileReplacingCompilationTracker : ICompilationTracker { private readonly ICompilationTracker _underlyingTracker; private readonly SourceGeneratedDocumentState _replacedGeneratedDocumentState; /// <summary> /// The lazily-produced compilation that has the generated document updated. This is initialized by call to /// <see cref="GetCompilationAsync"/>. /// </summary> [DisallowNull] private Compilation? _compilationWithReplacement; public GeneratedFileReplacingCompilationTracker(ICompilationTracker underlyingTracker, SourceGeneratedDocumentState replacementDocumentState) { _underlyingTracker = underlyingTracker; _replacedGeneratedDocumentState = replacementDocumentState; } public bool HasCompilation => _underlyingTracker.HasCompilation; public ProjectState ProjectState => _underlyingTracker.ProjectState; public bool ContainsAssemblyOrModuleOrDynamic(ISymbol symbol, bool primary) { if (_compilationWithReplacement == null) { // We don't have a compilation yet, so this couldn't have came from us return false; } else { return UnrootedSymbolSet.Create(_compilationWithReplacement).ContainsAssemblyOrModuleOrDynamic(symbol, primary); } } public bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken) { // TODO: This only needs to be implemented if a feature that operates from a source generated file needs to search for declarations // with other names; those APIs are only used by certain code fixes which isn't a need for now. This will need to be fixed up when // we complete https://github.com/dotnet/roslyn/issues/49533. throw new NotImplementedException(); } public bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(string name, SymbolFilter filter, CancellationToken cancellationToken) { // TODO: This only needs to be implemented if a feature that operates from a source generated file needs to search for declarations // with other names; those APIs are only used by certain code fixes which isn't a need for now. This will need to be fixed up when // we complete https://github.com/dotnet/roslyn/issues/49533. throw new NotImplementedException(); } public ICompilationTracker Fork(ProjectState newProject, CompilationAndGeneratorDriverTranslationAction? translate = null, CancellationToken cancellationToken = default) { // TODO: This only needs to be implemented if a feature that operates from a source generated file then makes // further mutations to that project, which isn't needed for now. This will be need to be fixed up when we complete // https://github.com/dotnet/roslyn/issues/49533. throw new NotImplementedException(); } public ICompilationTracker FreezePartialStateWithTree(SolutionState solution, DocumentState docState, SyntaxTree tree, CancellationToken cancellationToken) { // Because we override SourceGeneratedDocument.WithFrozenPartialSemantics directly, we shouldn't be able to get here. throw ExceptionUtilities.Unreachable; } public async Task<Compilation> GetCompilationAsync(SolutionState solution, CancellationToken cancellationToken) { // Fast path if we've definitely already done this before if (_compilationWithReplacement != null) { return _compilationWithReplacement; } var underlyingCompilation = await _underlyingTracker.GetCompilationAsync(solution, cancellationToken).ConfigureAwait(false); var underlyingSourceGeneratedDocuments = await _underlyingTracker.GetSourceGeneratedDocumentStatesAsync(solution, cancellationToken).ConfigureAwait(false); underlyingSourceGeneratedDocuments.TryGetState(_replacedGeneratedDocumentState.Id, out var existingState); Compilation newCompilation; var newSyntaxTree = await _replacedGeneratedDocumentState.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); if (existingState != null) { // The generated file still exists in the underlying compilation, but the contents may not match the open file if the open file // is stale. Replace the syntax tree so we have a tree that matches the text. var existingSyntaxTree = await existingState.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); newCompilation = underlyingCompilation.ReplaceSyntaxTree(existingSyntaxTree, newSyntaxTree); } else { // The existing output no longer exists in the underlying compilation. This could happen if the user made // an edit which would cause this file to no longer exist, but they're still operating on an open representation // of that file. To ensure that this snapshot is still usable, we'll just add this document back in. This is not a // semantically correct operation, but working on stale snapshots never has that guarantee. newCompilation = underlyingCompilation.AddSyntaxTrees(newSyntaxTree); } Interlocked.CompareExchange(ref _compilationWithReplacement, newCompilation, null); return _compilationWithReplacement; } public Task<VersionStamp> GetDependentSemanticVersionAsync(SolutionState solution, CancellationToken cancellationToken) { return _underlyingTracker.GetDependentSemanticVersionAsync(solution, cancellationToken); } public Task<VersionStamp> GetDependentVersionAsync(SolutionState solution, CancellationToken cancellationToken) { return _underlyingTracker.GetDependentVersionAsync(solution, cancellationToken); } public async Task<MetadataReference> GetMetadataReferenceAsync(SolutionState solution, ProjectState fromProject, ProjectReference projectReference, CancellationToken cancellationToken) { var compilation = await GetCompilationAsync(solution, cancellationToken).ConfigureAwait(false); // If it's the same language we can just make a CompilationReference if (this.ProjectState.LanguageServices == fromProject.LanguageServices) { return compilation.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes); } else { var version = await GetDependentSemanticVersionAsync(solution, cancellationToken).ConfigureAwait(false); return MetadataOnlyReference.GetOrBuildReference(solution, projectReference, compilation, version, cancellationToken); } } public CompilationReference? GetPartialMetadataReference(ProjectState fromProject, ProjectReference projectReference) { // This method is used if you're forking a solution with partial semantics, and used to quickly produce references. // So this method should only be called if: // // 1. Project A has a open source generated document, and this CompilationTracker represents A // 2. Project B references that A, and is being frozen for partial semantics. // // We generally don't use partial semantics in a different project than the open file, so this isn't a scenario we need to support. throw new NotImplementedException(); } public async ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(SolutionState solution, CancellationToken cancellationToken) { var underlyingGeneratedDocumentStates = await _underlyingTracker.GetSourceGeneratedDocumentStatesAsync(solution, cancellationToken).ConfigureAwait(false); if (underlyingGeneratedDocumentStates.Contains(_replacedGeneratedDocumentState.Id)) { // The generated file still exists in the underlying compilation, but the contents may not match the open file if the open file // is stale. Replace the syntax tree so we have a tree that matches the text. return underlyingGeneratedDocumentStates.SetState(_replacedGeneratedDocumentState.Id, _replacedGeneratedDocumentState); } else { // The generated output no longer exists in the underlying compilation. This could happen if the user made // an edit which would cause this file to no longer exist, but they're still operating on an open representation // of that file. To ensure that this snapshot is still usable, we'll just add this document back in. This is not a // semantically correct operation, but working on stale snapshots never has that guarantee. return underlyingGeneratedDocumentStates.AddRange(ImmutableArray.Create(_replacedGeneratedDocumentState)); } } public Task<bool> HasSuccessfullyLoadedAsync(SolutionState solution, CancellationToken cancellationToken) { return _underlyingTracker.HasSuccessfullyLoadedAsync(solution, cancellationToken); } public bool TryGetCompilation([NotNullWhen(true)] out Compilation? compilation) { compilation = _compilationWithReplacement; return compilation != null; } public SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId) { if (documentId == _replacedGeneratedDocumentState.Id) { return _replacedGeneratedDocumentState; } else { return _underlyingTracker.TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentId); } } } } }
// Licensed to the .NET Foundation under one or more 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 System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class SolutionState { /// <summary> /// An implementation of <see cref="ICompilationTracker"/> that takes a compilation from another compilation tracker and updates it /// to return a generated document with a specific content, regardless of what the generator actually produces. In other words, it says /// "take the compilation this other thing produced, and pretend the generator gave this content, even if it wouldn't." /// </summary> private class GeneratedFileReplacingCompilationTracker : ICompilationTracker { private readonly ICompilationTracker _underlyingTracker; private readonly SourceGeneratedDocumentState _replacedGeneratedDocumentState; /// <summary> /// The lazily-produced compilation that has the generated document updated. This is initialized by call to /// <see cref="GetCompilationAsync"/>. /// </summary> [DisallowNull] private Compilation? _compilationWithReplacement; public GeneratedFileReplacingCompilationTracker(ICompilationTracker underlyingTracker, SourceGeneratedDocumentState replacementDocumentState) { _underlyingTracker = underlyingTracker; _replacedGeneratedDocumentState = replacementDocumentState; } public ProjectState ProjectState => _underlyingTracker.ProjectState; public bool ContainsAssemblyOrModuleOrDynamic(ISymbol symbol, bool primary) { if (_compilationWithReplacement == null) { // We don't have a compilation yet, so this couldn't have came from us return false; } else { return UnrootedSymbolSet.Create(_compilationWithReplacement).ContainsAssemblyOrModuleOrDynamic(symbol, primary); } } public bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken) { // TODO: This only needs to be implemented if a feature that operates from a source generated file needs to search for declarations // with other names; those APIs are only used by certain code fixes which isn't a need for now. This will need to be fixed up when // we complete https://github.com/dotnet/roslyn/issues/49533. throw new NotImplementedException(); } public bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(string name, SymbolFilter filter, CancellationToken cancellationToken) { // TODO: This only needs to be implemented if a feature that operates from a source generated file needs to search for declarations // with other names; those APIs are only used by certain code fixes which isn't a need for now. This will need to be fixed up when // we complete https://github.com/dotnet/roslyn/issues/49533. throw new NotImplementedException(); } public ICompilationTracker Fork(ProjectState newProject, CompilationAndGeneratorDriverTranslationAction? translate = null, CancellationToken cancellationToken = default) { // TODO: This only needs to be implemented if a feature that operates from a source generated file then makes // further mutations to that project, which isn't needed for now. This will be need to be fixed up when we complete // https://github.com/dotnet/roslyn/issues/49533. throw new NotImplementedException(); } public ICompilationTracker FreezePartialStateWithTree(SolutionState solution, DocumentState docState, SyntaxTree tree, CancellationToken cancellationToken) { // Because we override SourceGeneratedDocument.WithFrozenPartialSemantics directly, we shouldn't be able to get here. throw ExceptionUtilities.Unreachable; } public async Task<Compilation> GetCompilationAsync(SolutionState solution, CancellationToken cancellationToken) { // Fast path if we've definitely already done this before if (_compilationWithReplacement != null) { return _compilationWithReplacement; } var underlyingCompilation = await _underlyingTracker.GetCompilationAsync(solution, cancellationToken).ConfigureAwait(false); var underlyingSourceGeneratedDocuments = await _underlyingTracker.GetSourceGeneratedDocumentStatesAsync(solution, cancellationToken).ConfigureAwait(false); underlyingSourceGeneratedDocuments.TryGetState(_replacedGeneratedDocumentState.Id, out var existingState); Compilation newCompilation; var newSyntaxTree = await _replacedGeneratedDocumentState.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); if (existingState != null) { // The generated file still exists in the underlying compilation, but the contents may not match the open file if the open file // is stale. Replace the syntax tree so we have a tree that matches the text. var existingSyntaxTree = await existingState.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); newCompilation = underlyingCompilation.ReplaceSyntaxTree(existingSyntaxTree, newSyntaxTree); } else { // The existing output no longer exists in the underlying compilation. This could happen if the user made // an edit which would cause this file to no longer exist, but they're still operating on an open representation // of that file. To ensure that this snapshot is still usable, we'll just add this document back in. This is not a // semantically correct operation, but working on stale snapshots never has that guarantee. newCompilation = underlyingCompilation.AddSyntaxTrees(newSyntaxTree); } Interlocked.CompareExchange(ref _compilationWithReplacement, newCompilation, null); return _compilationWithReplacement; } public Task<VersionStamp> GetDependentSemanticVersionAsync(SolutionState solution, CancellationToken cancellationToken) { return _underlyingTracker.GetDependentSemanticVersionAsync(solution, cancellationToken); } public Task<VersionStamp> GetDependentVersionAsync(SolutionState solution, CancellationToken cancellationToken) { return _underlyingTracker.GetDependentVersionAsync(solution, cancellationToken); } public async Task<MetadataReference> GetMetadataReferenceAsync(SolutionState solution, ProjectState fromProject, ProjectReference projectReference, CancellationToken cancellationToken) { var compilation = await GetCompilationAsync(solution, cancellationToken).ConfigureAwait(false); // If it's the same language we can just make a CompilationReference if (this.ProjectState.LanguageServices == fromProject.LanguageServices) { return compilation.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes); } else { var version = await GetDependentSemanticVersionAsync(solution, cancellationToken).ConfigureAwait(false); return MetadataOnlyReference.GetOrBuildReference(solution, projectReference, compilation, version, cancellationToken); } } public CompilationReference? GetPartialMetadataReference(ProjectState fromProject, ProjectReference projectReference) { // This method is used if you're forking a solution with partial semantics, and used to quickly produce references. // So this method should only be called if: // // 1. Project A has a open source generated document, and this CompilationTracker represents A // 2. Project B references that A, and is being frozen for partial semantics. // // We generally don't use partial semantics in a different project than the open file, so this isn't a scenario we need to support. throw new NotImplementedException(); } public async ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(SolutionState solution, CancellationToken cancellationToken) { var underlyingGeneratedDocumentStates = await _underlyingTracker.GetSourceGeneratedDocumentStatesAsync(solution, cancellationToken).ConfigureAwait(false); if (underlyingGeneratedDocumentStates.Contains(_replacedGeneratedDocumentState.Id)) { // The generated file still exists in the underlying compilation, but the contents may not match the open file if the open file // is stale. Replace the syntax tree so we have a tree that matches the text. return underlyingGeneratedDocumentStates.SetState(_replacedGeneratedDocumentState.Id, _replacedGeneratedDocumentState); } else { // The generated output no longer exists in the underlying compilation. This could happen if the user made // an edit which would cause this file to no longer exist, but they're still operating on an open representation // of that file. To ensure that this snapshot is still usable, we'll just add this document back in. This is not a // semantically correct operation, but working on stale snapshots never has that guarantee. return underlyingGeneratedDocumentStates.AddRange(ImmutableArray.Create(_replacedGeneratedDocumentState)); } } public Task<bool> HasSuccessfullyLoadedAsync(SolutionState solution, CancellationToken cancellationToken) { return _underlyingTracker.HasSuccessfullyLoadedAsync(solution, cancellationToken); } public bool TryGetCompilation([NotNullWhen(true)] out Compilation? compilation) { compilation = _compilationWithReplacement; return compilation != null; } public SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId) { if (documentId == _replacedGeneratedDocumentState.Id) { return _replacedGeneratedDocumentState; } else { return _underlyingTracker.TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentId); } } } } }
1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.ICompilationTracker.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.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis { internal partial class SolutionState { private interface ICompilationTracker { /// <summary> /// Returns true if this tracker currently either points to a compilation, has an in-progress /// compilation being computed, or has a skeleton reference. Note: this is simply a weak /// statement about the tracker at this exact moment in time. Immediately after this returns /// the tracker might change and may no longer have a final compilation (for example, if the /// retainer let go of it) or might not have an in-progress compilation (for example, if the /// background compiler finished with it). /// /// Because of the above limitations, this should only be used by clients as a weak form of /// information about the tracker. For example, a client may see that a tracker has no /// compilation and may choose to throw it away knowing that it could be reconstructed at a /// later point if necessary. /// </summary> bool HasCompilation { get; } ProjectState ProjectState { get; } /// <summary> /// Returns <see langword="true"/> if this <see cref="Project"/>/<see cref="Compilation"/> could produce the /// given <paramref name="symbol"/>. The symbol must be a <see cref="IAssemblySymbol"/>, <see /// cref="IModuleSymbol"/> or <see cref="IDynamicTypeSymbol"/>. /// </summary> /// <remarks> /// If <paramref name="primary"/> is true, then <see cref="Compilation.References"/> will not be considered /// when answering this question. In other words, if <paramref name="symbol"/> is an <see /// cref="IAssemblySymbol"/> and <paramref name="primary"/> is <see langword="true"/> then this will only /// return true if the symbol is <see cref="Compilation.Assembly"/>. If <paramref name="primary"/> is /// false, then it can return true if <paramref name="symbol"/> is <see cref="Compilation.Assembly"/> or any /// of the symbols returned by <see cref="Compilation.GetAssemblyOrModuleSymbol(MetadataReference)"/> for /// any of the references of the <see cref="Compilation.References"/>. /// </remarks> bool ContainsAssemblyOrModuleOrDynamic(ISymbol symbol, bool primary); bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken); bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(string name, SymbolFilter filter, CancellationToken cancellationToken); ICompilationTracker Fork(ProjectState newProject, CompilationAndGeneratorDriverTranslationAction? translate = null, CancellationToken cancellationToken = default); ICompilationTracker FreezePartialStateWithTree(SolutionState solution, DocumentState docState, SyntaxTree tree, CancellationToken cancellationToken); Task<Compilation> GetCompilationAsync(SolutionState solution, CancellationToken cancellationToken); Task<VersionStamp> GetDependentSemanticVersionAsync(SolutionState solution, CancellationToken cancellationToken); Task<VersionStamp> GetDependentVersionAsync(SolutionState solution, CancellationToken cancellationToken); /// <summary> /// Get a metadata reference to this compilation info's compilation with respect to /// another project. For cross language references produce a skeletal assembly. If the /// compilation is not available, it is built. If a skeletal assembly reference is /// needed and does not exist, it is also built. /// </summary> Task<MetadataReference> GetMetadataReferenceAsync(SolutionState solution, ProjectState fromProject, ProjectReference projectReference, CancellationToken cancellationToken); CompilationReference? GetPartialMetadataReference(ProjectState fromProject, ProjectReference projectReference); ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(SolutionState solution, CancellationToken cancellationToken); Task<bool> HasSuccessfullyLoadedAsync(SolutionState solution, CancellationToken cancellationToken); bool TryGetCompilation([NotNullWhen(true)] out Compilation? compilation); SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId); } } }
// Licensed to the .NET Foundation under one or more 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.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis { internal partial class SolutionState { private interface ICompilationTracker { ProjectState ProjectState { get; } /// <summary> /// Returns <see langword="true"/> if this <see cref="Project"/>/<see cref="Compilation"/> could produce the /// given <paramref name="symbol"/>. The symbol must be a <see cref="IAssemblySymbol"/>, <see /// cref="IModuleSymbol"/> or <see cref="IDynamicTypeSymbol"/>. /// </summary> /// <remarks> /// If <paramref name="primary"/> is true, then <see cref="Compilation.References"/> will not be considered /// when answering this question. In other words, if <paramref name="symbol"/> is an <see /// cref="IAssemblySymbol"/> and <paramref name="primary"/> is <see langword="true"/> then this will only /// return true if the symbol is <see cref="Compilation.Assembly"/>. If <paramref name="primary"/> is /// false, then it can return true if <paramref name="symbol"/> is <see cref="Compilation.Assembly"/> or any /// of the symbols returned by <see cref="Compilation.GetAssemblyOrModuleSymbol(MetadataReference)"/> for /// any of the references of the <see cref="Compilation.References"/>. /// </remarks> bool ContainsAssemblyOrModuleOrDynamic(ISymbol symbol, bool primary); bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken); bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(string name, SymbolFilter filter, CancellationToken cancellationToken); ICompilationTracker Fork(ProjectState newProject, CompilationAndGeneratorDriverTranslationAction? translate = null, CancellationToken cancellationToken = default); ICompilationTracker FreezePartialStateWithTree(SolutionState solution, DocumentState docState, SyntaxTree tree, CancellationToken cancellationToken); Task<Compilation> GetCompilationAsync(SolutionState solution, CancellationToken cancellationToken); Task<VersionStamp> GetDependentSemanticVersionAsync(SolutionState solution, CancellationToken cancellationToken); Task<VersionStamp> GetDependentVersionAsync(SolutionState solution, CancellationToken cancellationToken); /// <summary> /// Get a metadata reference to this compilation info's compilation with respect to /// another project. For cross language references produce a skeletal assembly. If the /// compilation is not available, it is built. If a skeletal assembly reference is /// needed and does not exist, it is also built. /// </summary> Task<MetadataReference> GetMetadataReferenceAsync(SolutionState solution, ProjectState fromProject, ProjectReference projectReference, CancellationToken cancellationToken); CompilationReference? GetPartialMetadataReference(ProjectState fromProject, ProjectReference projectReference); ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(SolutionState solution, CancellationToken cancellationToken); Task<bool> HasSuccessfullyLoadedAsync(SolutionState solution, CancellationToken cancellationToken); bool TryGetCompilation([NotNullWhen(true)] out Compilation? compilation); SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId); } } }
1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.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.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Logging; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a set of projects and their source code documents. /// /// this is a green node of Solution like ProjectState/DocumentState are for /// Project and Document. /// </summary> internal partial class SolutionState { // branch id for this solution private readonly BranchId _branchId; // the version of the workspace this solution is from private readonly int _workspaceVersion; private readonly SolutionInfo.SolutionAttributes _solutionAttributes; private readonly SolutionServices _solutionServices; private readonly ImmutableDictionary<ProjectId, ProjectState> _projectIdToProjectStateMap; private readonly ImmutableHashSet<string> _remoteSupportedLanguages; private readonly ImmutableDictionary<string, ImmutableArray<DocumentId>> _filePathToDocumentIdsMap; private readonly ProjectDependencyGraph _dependencyGraph; public readonly IReadOnlyList<AnalyzerReference> AnalyzerReferences; // Values for all these are created on demand. private ImmutableDictionary<ProjectId, ICompilationTracker> _projectIdToTrackerMap; // Checksums for this solution state private readonly ValueSource<SolutionStateChecksums> _lazyChecksums; /// <summary> /// Mapping from project-id to the options and checksums needed to synchronize it (and the projects it depends on) over /// to an OOP host. Options are stored as well so that when we are attempting to match a request for a particular project-subset /// we can return the options specific to that project-subset (which may be different from the <see cref="Options"/> defined /// for the entire solution). Lock this specific field before reading/writing to it. /// </summary> private readonly Dictionary<ProjectId, (SerializableOptionSet options, ValueSource<SolutionStateChecksums> checksums)> _lazyProjectChecksums = new(); // holds on data calculated based on the AnalyzerReferences list private readonly Lazy<HostDiagnosticAnalyzers> _lazyAnalyzers; /// <summary> /// Cache we use to map between unrooted symbols (i.e. assembly, module and dynamic symbols) and the project /// they came from. That way if we are asked about many symbols from the same assembly/module we can answer the /// question quickly after computing for the first one. Created on demand. /// </summary> private ConditionalWeakTable<ISymbol, ProjectId?>? _unrootedSymbolToProjectId; private static readonly Func<ConditionalWeakTable<ISymbol, ProjectId?>> s_createTable = () => new ConditionalWeakTable<ISymbol, ProjectId?>(); private readonly SourceGeneratedDocumentState? _frozenSourceGeneratedDocumentState; private SolutionState( BranchId branchId, int workspaceVersion, SolutionServices solutionServices, SolutionInfo.SolutionAttributes solutionAttributes, IReadOnlyList<ProjectId> projectIds, SerializableOptionSet options, IReadOnlyList<AnalyzerReference> analyzerReferences, ImmutableDictionary<ProjectId, ProjectState> idToProjectStateMap, ImmutableHashSet<string> remoteSupportedLanguages, ImmutableDictionary<ProjectId, ICompilationTracker> projectIdToTrackerMap, ImmutableDictionary<string, ImmutableArray<DocumentId>> filePathToDocumentIdsMap, ProjectDependencyGraph dependencyGraph, Lazy<HostDiagnosticAnalyzers>? lazyAnalyzers, SourceGeneratedDocumentState? frozenSourceGeneratedDocument) { _branchId = branchId; _workspaceVersion = workspaceVersion; _solutionAttributes = solutionAttributes; _solutionServices = solutionServices; ProjectIds = projectIds; Options = options; AnalyzerReferences = analyzerReferences; _projectIdToProjectStateMap = idToProjectStateMap; _remoteSupportedLanguages = remoteSupportedLanguages; _projectIdToTrackerMap = projectIdToTrackerMap; _filePathToDocumentIdsMap = filePathToDocumentIdsMap; _dependencyGraph = dependencyGraph; _lazyAnalyzers = lazyAnalyzers ?? CreateLazyHostDiagnosticAnalyzers(analyzerReferences); _frozenSourceGeneratedDocumentState = frozenSourceGeneratedDocument; // when solution state is changed, we recalculate its checksum _lazyChecksums = new AsyncLazy<SolutionStateChecksums>( c => ComputeChecksumsAsync(projectsToInclude: null, Options, c), cacheResult: true); CheckInvariants(); // make sure we don't accidentally capture any state but the list of references: static Lazy<HostDiagnosticAnalyzers> CreateLazyHostDiagnosticAnalyzers(IReadOnlyList<AnalyzerReference> analyzerReferences) => new(() => new HostDiagnosticAnalyzers(analyzerReferences)); } public SolutionState( BranchId primaryBranchId, SolutionServices solutionServices, SolutionInfo.SolutionAttributes solutionAttributes, SerializableOptionSet options, IReadOnlyList<AnalyzerReference> analyzerReferences) : this( primaryBranchId, workspaceVersion: 0, solutionServices, solutionAttributes, projectIds: SpecializedCollections.EmptyBoxedImmutableArray<ProjectId>(), options, analyzerReferences, idToProjectStateMap: ImmutableDictionary<ProjectId, ProjectState>.Empty, remoteSupportedLanguages: ImmutableHashSet<string>.Empty, projectIdToTrackerMap: ImmutableDictionary<ProjectId, ICompilationTracker>.Empty, filePathToDocumentIdsMap: ImmutableDictionary.Create<string, ImmutableArray<DocumentId>>(StringComparer.OrdinalIgnoreCase), dependencyGraph: ProjectDependencyGraph.Empty, lazyAnalyzers: null, frozenSourceGeneratedDocument: null) { } public SolutionState WithNewWorkspace(Workspace workspace, int workspaceVersion) { var services = workspace != _solutionServices.Workspace ? new SolutionServices(workspace) : _solutionServices; // Note: this will potentially have problems if the workspace services are different, as some services // get locked-in by document states and project states when first constructed. return CreatePrimarySolution(branchId: workspace.PrimaryBranchId, workspaceVersion: workspaceVersion, services: services); } public HostDiagnosticAnalyzers Analyzers => _lazyAnalyzers.Value; public SolutionInfo.SolutionAttributes SolutionAttributes => _solutionAttributes; public SourceGeneratedDocumentState? FrozenSourceGeneratedDocumentState => _frozenSourceGeneratedDocumentState; public ImmutableDictionary<ProjectId, ProjectState> ProjectStates => _projectIdToProjectStateMap; public int WorkspaceVersion => _workspaceVersion; public SolutionServices Services => _solutionServices; public SerializableOptionSet Options { get; } /// <summary> /// branch id of this solution /// /// currently, it only supports one level of branching. there is a primary branch of a workspace and all other /// branches that are branched from the primary branch. /// /// one still can create multiple forked solutions from an already branched solution, but versions among those /// can't be reliably used and compared. /// /// version only has a meaning between primary solution and branched one or between solutions from same branch. /// </summary> public BranchId BranchId => _branchId; /// <summary> /// The Workspace this solution is associated with. /// </summary> public Workspace Workspace => _solutionServices.Workspace; /// <summary> /// The Id of the solution. Multiple solution instances may share the same Id. /// </summary> public SolutionId Id => _solutionAttributes.Id; /// <summary> /// The path to the solution file or null if there is no solution file. /// </summary> public string? FilePath => _solutionAttributes.FilePath; /// <summary> /// The solution version. This equates to the solution file's version. /// </summary> public VersionStamp Version => _solutionAttributes.Version; /// <summary> /// A list of all the ids for all the projects contained by the solution. /// </summary> public IReadOnlyList<ProjectId> ProjectIds { get; } // Only run this in debug builds; even the .Any() call across all projects can be expensive when there's a lot of them. [Conditional("DEBUG")] private void CheckInvariants() { Contract.ThrowIfFalse(_projectIdToProjectStateMap.Count == ProjectIds.Count); Contract.ThrowIfFalse(_projectIdToProjectStateMap.Count == _dependencyGraph.ProjectIds.Count); // An id shouldn't point at a tracker for a different project. Contract.ThrowIfTrue(_projectIdToTrackerMap.Any(kvp => kvp.Key != kvp.Value.ProjectState.Id)); // project ids must be the same: Debug.Assert(_projectIdToProjectStateMap.Keys.SetEquals(ProjectIds)); Debug.Assert(_projectIdToProjectStateMap.Keys.SetEquals(_dependencyGraph.ProjectIds)); Debug.Assert(_remoteSupportedLanguages.SetEquals(GetRemoteSupportedProjectLanguages(_projectIdToProjectStateMap))); } private SolutionState Branch( SolutionInfo.SolutionAttributes? solutionAttributes = null, IReadOnlyList<ProjectId>? projectIds = null, SerializableOptionSet? options = null, IReadOnlyList<AnalyzerReference>? analyzerReferences = null, ImmutableDictionary<ProjectId, ProjectState>? idToProjectStateMap = null, ImmutableHashSet<string>? remoteSupportedProjectLanguages = null, ImmutableDictionary<ProjectId, ICompilationTracker>? projectIdToTrackerMap = null, ImmutableDictionary<string, ImmutableArray<DocumentId>>? filePathToDocumentIdsMap = null, ProjectDependencyGraph? dependencyGraph = null, Optional<SourceGeneratedDocumentState?> frozenSourceGeneratedDocument = default) { var branchId = GetBranchId(); if (idToProjectStateMap is not null) { Contract.ThrowIfNull(remoteSupportedProjectLanguages); } solutionAttributes ??= _solutionAttributes; projectIds ??= ProjectIds; idToProjectStateMap ??= _projectIdToProjectStateMap; remoteSupportedProjectLanguages ??= _remoteSupportedLanguages; Debug.Assert(remoteSupportedProjectLanguages.SetEquals(GetRemoteSupportedProjectLanguages(idToProjectStateMap))); options ??= Options.WithLanguages(remoteSupportedProjectLanguages); analyzerReferences ??= AnalyzerReferences; projectIdToTrackerMap ??= _projectIdToTrackerMap; filePathToDocumentIdsMap ??= _filePathToDocumentIdsMap; dependencyGraph ??= _dependencyGraph; var newFrozenSourceGeneratedDocumentState = frozenSourceGeneratedDocument.HasValue ? frozenSourceGeneratedDocument.Value : _frozenSourceGeneratedDocumentState; var analyzerReferencesEqual = AnalyzerReferences.SequenceEqual(analyzerReferences); if (branchId == _branchId && solutionAttributes == _solutionAttributes && projectIds == ProjectIds && options == Options && analyzerReferencesEqual && idToProjectStateMap == _projectIdToProjectStateMap && projectIdToTrackerMap == _projectIdToTrackerMap && filePathToDocumentIdsMap == _filePathToDocumentIdsMap && dependencyGraph == _dependencyGraph && newFrozenSourceGeneratedDocumentState == _frozenSourceGeneratedDocumentState) { return this; } return new SolutionState( branchId, _workspaceVersion, _solutionServices, solutionAttributes, projectIds, options, analyzerReferences, idToProjectStateMap, remoteSupportedProjectLanguages, projectIdToTrackerMap, filePathToDocumentIdsMap, dependencyGraph, analyzerReferencesEqual ? _lazyAnalyzers : null, newFrozenSourceGeneratedDocumentState); } private SolutionState CreatePrimarySolution( BranchId branchId, int workspaceVersion, SolutionServices services) { if (branchId == _branchId && workspaceVersion == _workspaceVersion && services == _solutionServices) { return this; } return new SolutionState( branchId, workspaceVersion, services, _solutionAttributes, ProjectIds, Options, AnalyzerReferences, _projectIdToProjectStateMap, _remoteSupportedLanguages, _projectIdToTrackerMap, _filePathToDocumentIdsMap, _dependencyGraph, _lazyAnalyzers, frozenSourceGeneratedDocument: null); } private BranchId GetBranchId() { // currently we only support one level branching. // my reasonings are // 1. it seems there is no-one who needs sub branches. // 2. this lets us to branch without explicit branch API return _branchId == Workspace.PrimaryBranchId ? BranchId.GetNextId() : _branchId; } /// <summary> /// The version of the most recently modified project. /// </summary> public VersionStamp GetLatestProjectVersion() { // this may produce a version that is out of sync with the actual Document versions. var latestVersion = VersionStamp.Default; foreach (var project in this.ProjectStates.Values) { latestVersion = project.Version.GetNewerVersion(latestVersion); } return latestVersion; } /// <summary> /// True if the solution contains a project with the specified project ID. /// </summary> public bool ContainsProject([NotNullWhen(returnValue: true)] ProjectId? projectId) => projectId != null && _projectIdToProjectStateMap.ContainsKey(projectId); /// <summary> /// True if the solution contains the document in one of its projects /// </summary> public bool ContainsDocument([NotNullWhen(returnValue: true)] DocumentId? documentId) { return documentId != null && this.ContainsProject(documentId.ProjectId) && this.GetProjectState(documentId.ProjectId)!.DocumentStates.Contains(documentId); } /// <summary> /// True if the solution contains the additional document in one of its projects /// </summary> public bool ContainsAdditionalDocument([NotNullWhen(returnValue: true)] DocumentId? documentId) { return documentId != null && this.ContainsProject(documentId.ProjectId) && this.GetProjectState(documentId.ProjectId)!.AdditionalDocumentStates.Contains(documentId); } /// <summary> /// True if the solution contains the analyzer config document in one of its projects /// </summary> public bool ContainsAnalyzerConfigDocument([NotNullWhen(returnValue: true)] DocumentId? documentId) { return documentId != null && this.ContainsProject(documentId.ProjectId) && this.GetProjectState(documentId.ProjectId)!.AnalyzerConfigDocumentStates.Contains(documentId); } private DocumentState GetRequiredDocumentState(DocumentId documentId) => GetRequiredProjectState(documentId.ProjectId).DocumentStates.GetRequiredState(documentId); private AdditionalDocumentState GetRequiredAdditionalDocumentState(DocumentId documentId) => GetRequiredProjectState(documentId.ProjectId).AdditionalDocumentStates.GetRequiredState(documentId); private AnalyzerConfigDocumentState GetRequiredAnalyzerConfigDocumentState(DocumentId documentId) => GetRequiredProjectState(documentId.ProjectId).AnalyzerConfigDocumentStates.GetRequiredState(documentId); internal DocumentState? GetDocumentState(SyntaxTree? syntaxTree, ProjectId? projectId) { if (syntaxTree != null) { // is this tree known to be associated with a document? var documentId = DocumentState.GetDocumentIdForTree(syntaxTree); if (documentId != null && (projectId == null || documentId.ProjectId == projectId)) { // does this solution even have the document? var projectState = GetProjectState(documentId.ProjectId); if (projectState != null) { var document = projectState.DocumentStates.GetState(documentId); if (document != null) { // does this document really have the syntax tree? if (document.TryGetSyntaxTree(out var documentTree) && documentTree == syntaxTree) { return document; } } else { var generatedDocument = TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentId); if (generatedDocument != null) { // does this document really have the syntax tree? if (generatedDocument.TryGetSyntaxTree(out var documentTree) && documentTree == syntaxTree) { return generatedDocument; } } } } } } return null; } public Task<VersionStamp> GetDependentVersionAsync(ProjectId projectId, CancellationToken cancellationToken) => this.GetCompilationTracker(projectId).GetDependentVersionAsync(this, cancellationToken); public Task<VersionStamp> GetDependentSemanticVersionAsync(ProjectId projectId, CancellationToken cancellationToken) => this.GetCompilationTracker(projectId).GetDependentSemanticVersionAsync(this, cancellationToken); public ProjectState? GetProjectState(ProjectId projectId) { _projectIdToProjectStateMap.TryGetValue(projectId, out var state); return state; } public ProjectState GetRequiredProjectState(ProjectId projectId) { var result = GetProjectState(projectId); Contract.ThrowIfNull(result); return result; } /// <summary> /// Gets the <see cref="Project"/> associated with an assembly symbol. /// </summary> public ProjectState? GetProjectState(IAssemblySymbol? assemblySymbol) { if (assemblySymbol == null) return null; s_assemblyOrModuleSymbolToProjectMap.TryGetValue(assemblySymbol, out var id); return id == null ? null : this.GetProjectState(id); } private bool TryGetCompilationTracker(ProjectId projectId, [NotNullWhen(returnValue: true)] out ICompilationTracker? tracker) => _projectIdToTrackerMap.TryGetValue(projectId, out tracker); private static readonly Func<ProjectId, SolutionState, CompilationTracker> s_createCompilationTrackerFunction = CreateCompilationTracker; private static CompilationTracker CreateCompilationTracker(ProjectId projectId, SolutionState solution) { var projectState = solution.GetProjectState(projectId); Contract.ThrowIfNull(projectState); return new CompilationTracker(projectState); } private ICompilationTracker GetCompilationTracker(ProjectId projectId) { if (!_projectIdToTrackerMap.TryGetValue(projectId, out var tracker)) { tracker = ImmutableInterlocked.GetOrAdd(ref _projectIdToTrackerMap, projectId, s_createCompilationTrackerFunction, this); } return tracker; } private SolutionState AddProject(ProjectId projectId, ProjectState projectState) { // changed project list so, increment version. var newSolutionAttributes = _solutionAttributes.With(version: Version.GetNewerVersion()); var newProjectIds = ProjectIds.ToImmutableArray().Add(projectId); var newStateMap = _projectIdToProjectStateMap.Add(projectId, projectState); var newLanguages = RemoteSupportedLanguages.IsSupported(projectState.Language) ? _remoteSupportedLanguages.Add(projectState.Language) : _remoteSupportedLanguages; var newDependencyGraph = _dependencyGraph .WithAdditionalProject(projectId) .WithAdditionalProjectReferences(projectId, projectState.ProjectReferences); // It's possible that another project already in newStateMap has a reference to this project that we're adding, since we allow // dangling references like that. If so, we'll need to link those in too. foreach (var newState in newStateMap) { foreach (var projectReference in newState.Value.ProjectReferences) { if (projectReference.ProjectId == projectId) { newDependencyGraph = newDependencyGraph.WithAdditionalProjectReferences( newState.Key, SpecializedCollections.SingletonReadOnlyList(projectReference)); break; } } } var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph); var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithAddedDocuments(GetDocumentStates(newStateMap[projectId])); return Branch( solutionAttributes: newSolutionAttributes, projectIds: newProjectIds, idToProjectStateMap: newStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newTrackerMap, filePathToDocumentIdsMap: newFilePathToDocumentIdsMap, dependencyGraph: newDependencyGraph); } /// <summary> /// Create a new solution instance that includes a project with the specified project information. /// </summary> public SolutionState AddProject(ProjectInfo projectInfo) { if (projectInfo == null) { throw new ArgumentNullException(nameof(projectInfo)); } var projectId = projectInfo.Id; var language = projectInfo.Language; if (language == null) { throw new ArgumentNullException(nameof(language)); } var displayName = projectInfo.Name; if (displayName == null) { throw new ArgumentNullException(nameof(displayName)); } CheckNotContainsProject(projectId); var languageServices = this.Workspace.Services.GetLanguageServices(language); if (languageServices == null) { throw new ArgumentException(string.Format(WorkspacesResources.The_language_0_is_not_supported, language)); } var newProject = new ProjectState(projectInfo, languageServices, _solutionServices); return this.AddProject(newProject.Id, newProject); } private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithAddedDocuments(IEnumerable<TextDocumentState> documentStates) { var builder = _filePathToDocumentIdsMap.ToBuilder(); foreach (var documentState in documentStates) { var filePath = documentState.FilePath; if (RoslynString.IsNullOrEmpty(filePath)) { continue; } builder.MultiAdd(filePath, documentState.Id); } return builder.ToImmutable(); } private static IEnumerable<TextDocumentState> GetDocumentStates(ProjectState projectState) => projectState.DocumentStates.States.Values .Concat<TextDocumentState>(projectState.AdditionalDocumentStates.States.Values) .Concat(projectState.AnalyzerConfigDocumentStates.States.Values); /// <summary> /// Create a new solution instance without the project specified. /// </summary> public SolutionState RemoveProject(ProjectId projectId) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } CheckContainsProject(projectId); // changed project list so, increment version. var newSolutionAttributes = _solutionAttributes.With(version: this.Version.GetNewerVersion()); var newProjectIds = ProjectIds.ToImmutableArray().Remove(projectId); var newStateMap = _projectIdToProjectStateMap.Remove(projectId); // Remote supported languages only changes if the removed project is the last project of a supported language. var newLanguages = _remoteSupportedLanguages; if (_projectIdToProjectStateMap.TryGetValue(projectId, out var projectState) && RemoteSupportedLanguages.IsSupported(projectState.Language)) { var stillSupportsLanguage = false; foreach (var (id, state) in _projectIdToProjectStateMap) { if (id == projectId) continue; if (state.Language == projectState.Language) { stillSupportsLanguage = true; break; } } if (!stillSupportsLanguage) { newLanguages = newLanguages.Remove(projectState.Language); } } var newDependencyGraph = _dependencyGraph.WithProjectRemoved(projectId); var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph); var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithRemovedDocuments(GetDocumentStates(_projectIdToProjectStateMap[projectId])); return this.Branch( solutionAttributes: newSolutionAttributes, projectIds: newProjectIds, idToProjectStateMap: newStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newTrackerMap.Remove(projectId), filePathToDocumentIdsMap: newFilePathToDocumentIdsMap, dependencyGraph: newDependencyGraph); } private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithRemovedDocuments(IEnumerable<TextDocumentState> documentStates) { var builder = _filePathToDocumentIdsMap.ToBuilder(); foreach (var documentState in documentStates) { var filePath = documentState.FilePath; if (RoslynString.IsNullOrEmpty(filePath)) { continue; } if (!builder.TryGetValue(filePath, out var documentIdsWithPath) || !documentIdsWithPath.Contains(documentState.Id)) { throw new ArgumentException($"The given documentId was not found in '{nameof(_filePathToDocumentIdsMap)}'."); } builder.MultiRemove(filePath, documentState.Id); } return builder.ToImmutable(); } private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithFilePath(DocumentId documentId, string? oldFilePath, string? newFilePath) { if (oldFilePath == newFilePath) { return _filePathToDocumentIdsMap; } var builder = _filePathToDocumentIdsMap.ToBuilder(); if (!RoslynString.IsNullOrEmpty(oldFilePath)) { builder.MultiRemove(oldFilePath, documentId); } if (!RoslynString.IsNullOrEmpty(newFilePath)) { builder.MultiAdd(newFilePath, documentId); } return builder.ToImmutable(); } /// <summary> /// Creates a new solution instance with the project specified updated to have the new /// assembly name. /// </summary> public SolutionState WithProjectAssemblyName(ProjectId projectId, string assemblyName) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithAssemblyName(assemblyName); if (oldProject == newProject) { return this; } return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectAssemblyNameAction(assemblyName)); } /// <summary> /// Creates a new solution instance with the project specified updated to have the output file path. /// </summary> public SolutionState WithProjectOutputFilePath(ProjectId projectId, string? outputFilePath) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithOutputFilePath(outputFilePath); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the output file path. /// </summary> public SolutionState WithProjectOutputRefFilePath(ProjectId projectId, string? outputRefFilePath) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithOutputRefFilePath(outputRefFilePath); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the compiler output file path. /// </summary> public SolutionState WithProjectCompilationOutputInfo(ProjectId projectId, in CompilationOutputInfo info) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithCompilationOutputInfo(info); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the default namespace. /// </summary> public SolutionState WithProjectDefaultNamespace(ProjectId projectId, string? defaultNamespace) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithDefaultNamespace(defaultNamespace); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the name. /// </summary> public SolutionState WithProjectName(ProjectId projectId, string name) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithName(name); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the project file path. /// </summary> public SolutionState WithProjectFilePath(ProjectId projectId, string? filePath) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithFilePath(filePath); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified compilation options. /// </summary> public SolutionState WithProjectCompilationOptions(ProjectId projectId, CompilationOptions options) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithCompilationOptions(options); if (oldProject == newProject) { return this; } return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: false)); } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified parse options. /// </summary> public SolutionState WithProjectParseOptions(ProjectId projectId, ParseOptions options) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithParseOptions(options); if (oldProject == newProject) { return this; } if (Workspace.PartialSemanticsEnabled) { // don't fork tracker with queued action since access via partial semantics can become inconsistent (throw). // Since changing options is rare event, it is okay to start compilation building from scratch. return ForkProject(newProject, forkTracker: false); } else { return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ReplaceAllSyntaxTreesAction(newProject, isParseOptionChange: true)); } } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified hasAllInformation. /// </summary> public SolutionState WithHasAllInformation(ProjectId projectId, bool hasAllInformation) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithHasAllInformation(hasAllInformation); if (oldProject == newProject) { return this; } // fork without any change on compilation. return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified runAnalyzers. /// </summary> public SolutionState WithRunAnalyzers(ProjectId projectId, bool runAnalyzers) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithRunAnalyzers(runAnalyzers); if (oldProject == newProject) { return this; } // fork without any change on compilation. return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to include /// the specified project references. /// </summary> public SolutionState AddProjectReferences(ProjectId projectId, IReadOnlyCollection<ProjectReference> projectReferences) { if (projectReferences.Count == 0) { return this; } var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.ProjectReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(projectReferences); var newProject = oldProject.WithProjectReferences(newReferences); var newDependencyGraph = _dependencyGraph.WithAdditionalProjectReferences(projectId, projectReferences); return ForkProject(newProject, newDependencyGraph: newDependencyGraph); } /// <summary> /// Create a new solution instance with the project specified updated to no longer /// include the specified project reference. /// </summary> public SolutionState RemoveProjectReference(ProjectId projectId, ProjectReference projectReference) { var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.ProjectReferences.ToImmutableArray(); // Note: uses ProjectReference equality to compare references. var newReferences = oldReferences.Remove(projectReference); if (oldReferences == newReferences) { return this; } var newProject = oldProject.WithProjectReferences(newReferences); ProjectDependencyGraph newDependencyGraph; if (newProject.ContainsReferenceToProject(projectReference.ProjectId) || !_projectIdToProjectStateMap.ContainsKey(projectReference.ProjectId)) { // Two cases: // 1) The project contained multiple non-equivalent references to the project, // and not all of them were removed. The dependency graph doesn't change. // Note that there might be two references to the same project, one with // extern alias and the other without. These are not considered duplicates. // 2) The referenced project is not part of the solution and hence not included // in the dependency graph. newDependencyGraph = _dependencyGraph; } else { newDependencyGraph = _dependencyGraph.WithProjectReferenceRemoved(projectId, projectReference.ProjectId); } return ForkProject(newProject, newDependencyGraph: newDependencyGraph); } /// <summary> /// Create a new solution instance with the project specified updated to contain /// the specified list of project references. /// </summary> public SolutionState WithProjectReferences(ProjectId projectId, IReadOnlyList<ProjectReference> projectReferences) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithProjectReferences(projectReferences); if (oldProject == newProject) { return this; } var newDependencyGraph = _dependencyGraph.WithProjectReferences(projectId, projectReferences); return ForkProject(newProject, newDependencyGraph: newDependencyGraph); } /// <summary> /// Creates a new solution instance with the project documents in the order by the specified document ids. /// The specified document ids must be the same as what is already in the project; no adding or removing is allowed. /// </summary> public SolutionState WithProjectDocumentsOrder(ProjectId projectId, ImmutableList<DocumentId> documentIds) { var oldProject = GetRequiredProjectState(projectId); if (documentIds.Count != oldProject.DocumentStates.Count) { throw new ArgumentException($"The specified documents do not equal the project document count.", nameof(documentIds)); } foreach (var id in documentIds) { if (!oldProject.DocumentStates.Contains(id)) { throw new InvalidOperationException($"The document '{id}' does not exist in the project."); } } var newProject = oldProject.UpdateDocumentsOrder(documentIds); if (oldProject == newProject) { return this; } return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ReplaceAllSyntaxTreesAction(newProject, isParseOptionChange: false)); } /// <summary> /// Create a new solution instance with the project specified updated to include the /// specified metadata references. /// </summary> public SolutionState AddMetadataReferences(ProjectId projectId, IReadOnlyCollection<MetadataReference> metadataReferences) { if (metadataReferences.Count == 0) { return this; } var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.MetadataReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(metadataReferences); return ForkProject(oldProject.WithMetadataReferences(newReferences)); } /// <summary> /// Create a new solution instance with the project specified updated to no longer include /// the specified metadata reference. /// </summary> public SolutionState RemoveMetadataReference(ProjectId projectId, MetadataReference metadataReference) { var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.MetadataReferences.ToImmutableArray(); var newReferences = oldReferences.Remove(metadataReference); if (oldReferences == newReferences) { return this; } return ForkProject(oldProject.WithMetadataReferences(newReferences)); } /// <summary> /// Create a new solution instance with the project specified updated to include only the /// specified metadata references. /// </summary> public SolutionState WithProjectMetadataReferences(ProjectId projectId, IReadOnlyList<MetadataReference> metadataReferences) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithMetadataReferences(metadataReferences); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to include the /// specified analyzer references. /// </summary> public SolutionState AddAnalyzerReferences(ProjectId projectId, ImmutableArray<AnalyzerReference> analyzerReferences) { if (analyzerReferences.Length == 0) { return this; } var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(analyzerReferences); return ForkProject( oldProject.WithAnalyzerReferences(newReferences), new CompilationAndGeneratorDriverTranslationAction.AddAnalyzerReferencesAction(analyzerReferences, oldProject.Language)); } /// <summary> /// Create a new solution instance with the project specified updated to no longer include /// the specified analyzer reference. /// </summary> public SolutionState RemoveAnalyzerReference(ProjectId projectId, AnalyzerReference analyzerReference) { var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.Remove(analyzerReference); if (oldReferences == newReferences) { return this; } return ForkProject( oldProject.WithAnalyzerReferences(newReferences), new CompilationAndGeneratorDriverTranslationAction.RemoveAnalyzerReferencesAction(ImmutableArray.Create(analyzerReference), oldProject.Language)); } /// <summary> /// Create a new solution instance with the project specified updated to include only the /// specified analyzer references. /// </summary> public SolutionState WithProjectAnalyzerReferences(ProjectId projectId, IEnumerable<AnalyzerReference> analyzerReferences) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithAnalyzerReferences(analyzerReferences); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the corresponding projects updated to include new /// documents defined by the document info. /// </summary> public SolutionState AddDocuments(ImmutableArray<DocumentInfo> documentInfos) { return AddDocumentsToMultipleProjects(documentInfos, (documentInfo, project) => project.CreateDocument(documentInfo, project.ParseOptions), (oldProject, documents) => (oldProject.AddDocuments(documents), new CompilationAndGeneratorDriverTranslationAction.AddDocumentsAction(documents))); } /// <summary> /// Core helper that takes a set of <see cref="DocumentInfo" />s and does the application of the appropriate documents to each project. /// </summary> /// <param name="documentInfos">The set of documents to add.</param> /// <param name="addDocumentsToProjectState">Returns the new <see cref="ProjectState"/> with the documents added, and the <see cref="CompilationAndGeneratorDriverTranslationAction"/> needed as well.</param> /// <returns></returns> private SolutionState AddDocumentsToMultipleProjects<T>( ImmutableArray<DocumentInfo> documentInfos, Func<DocumentInfo, ProjectState, T> createDocumentState, Func<ProjectState, ImmutableArray<T>, (ProjectState newState, CompilationAndGeneratorDriverTranslationAction translationAction)> addDocumentsToProjectState) where T : TextDocumentState { if (documentInfos.IsDefault) { throw new ArgumentNullException(nameof(documentInfos)); } if (documentInfos.IsEmpty) { return this; } // The documents might be contributing to multiple different projects; split them by project and then we'll process // project-at-a-time. var documentInfosByProjectId = documentInfos.ToLookup(d => d.Id.ProjectId); var newSolutionState = this; foreach (var documentInfosInProject in documentInfosByProjectId) { CheckContainsProject(documentInfosInProject.Key); var oldProjectState = this.GetProjectState(documentInfosInProject.Key)!; var newDocumentStatesForProjectBuilder = ArrayBuilder<T>.GetInstance(); foreach (var documentInfo in documentInfosInProject) { newDocumentStatesForProjectBuilder.Add(createDocumentState(documentInfo, oldProjectState)); } var newDocumentStatesForProject = newDocumentStatesForProjectBuilder.ToImmutableAndFree(); var (newProjectState, compilationTranslationAction) = addDocumentsToProjectState(oldProjectState, newDocumentStatesForProject); newSolutionState = newSolutionState.ForkProject(newProjectState, compilationTranslationAction, newFilePathToDocumentIdsMap: CreateFilePathToDocumentIdsMapWithAddedDocuments(newDocumentStatesForProject)); } return newSolutionState; } public SolutionState AddAdditionalDocuments(ImmutableArray<DocumentInfo> documentInfos) { return AddDocumentsToMultipleProjects(documentInfos, (documentInfo, project) => new AdditionalDocumentState(documentInfo, _solutionServices), (projectState, documents) => (projectState.AddAdditionalDocuments(documents), new CompilationAndGeneratorDriverTranslationAction.AddAdditionalDocumentsAction(documents))); } public SolutionState AddAnalyzerConfigDocuments(ImmutableArray<DocumentInfo> documentInfos) { // Adding a new analyzer config potentially modifies the compilation options return AddDocumentsToMultipleProjects(documentInfos, (documentInfo, project) => new AnalyzerConfigDocumentState(documentInfo, _solutionServices), (oldProject, documents) => { var newProject = oldProject.AddAnalyzerConfigDocuments(documents); return (newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true)); }); } public SolutionState RemoveAnalyzerConfigDocuments(ImmutableArray<DocumentId> documentIds) { return RemoveDocumentsFromMultipleProjects(documentIds, (projectState, documentId) => projectState.AnalyzerConfigDocumentStates.GetRequiredState(documentId), (oldProject, documentIds, _) => { var newProject = oldProject.RemoveAnalyzerConfigDocuments(documentIds); return (newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true)); }); } /// <summary> /// Creates a new solution instance that no longer includes the specified document. /// </summary> public SolutionState RemoveDocuments(ImmutableArray<DocumentId> documentIds) { return RemoveDocumentsFromMultipleProjects(documentIds, (projectState, documentId) => projectState.DocumentStates.GetRequiredState(documentId), (projectState, documentIds, documentStates) => (projectState.RemoveDocuments(documentIds), new CompilationAndGeneratorDriverTranslationAction.RemoveDocumentsAction(documentStates))); } private SolutionState RemoveDocumentsFromMultipleProjects<T>( ImmutableArray<DocumentId> documentIds, Func<ProjectState, DocumentId, T> getExistingTextDocumentState, Func<ProjectState, ImmutableArray<DocumentId>, ImmutableArray<T>, (ProjectState newState, CompilationAndGeneratorDriverTranslationAction translationAction)> removeDocumentsFromProjectState) where T : TextDocumentState { if (documentIds.IsEmpty) { return this; } // The documents might be contributing to multiple different projects; split them by project and then we'll process // project-at-a-time. var documentIdsByProjectId = documentIds.ToLookup(id => id.ProjectId); var newSolutionState = this; foreach (var documentIdsInProject in documentIdsByProjectId) { var oldProjectState = this.GetProjectState(documentIdsInProject.Key); if (oldProjectState == null) { throw new InvalidOperationException(string.Format(WorkspacesResources._0_is_not_part_of_the_workspace, documentIdsInProject.Key)); } var removedDocumentStatesBuilder = ArrayBuilder<T>.GetInstance(); foreach (var documentId in documentIdsInProject) { removedDocumentStatesBuilder.Add(getExistingTextDocumentState(oldProjectState, documentId)); } var removedDocumentStatesForProject = removedDocumentStatesBuilder.ToImmutableAndFree(); var (newProjectState, compilationTranslationAction) = removeDocumentsFromProjectState(oldProjectState, documentIdsInProject.ToImmutableArray(), removedDocumentStatesForProject); newSolutionState = newSolutionState.ForkProject(newProjectState, compilationTranslationAction, newFilePathToDocumentIdsMap: CreateFilePathToDocumentIdsMapWithRemovedDocuments(removedDocumentStatesForProject)); } return newSolutionState; } /// <summary> /// Creates a new solution instance that no longer includes the specified additional documents. /// </summary> public SolutionState RemoveAdditionalDocuments(ImmutableArray<DocumentId> documentIds) { return RemoveDocumentsFromMultipleProjects(documentIds, (projectState, documentId) => projectState.AdditionalDocumentStates.GetRequiredState(documentId), (projectState, documentIds, documentStates) => (projectState.RemoveAdditionalDocuments(documentIds), new CompilationAndGeneratorDriverTranslationAction.RemoveAdditionalDocumentsAction(documentStates))); } /// <summary> /// Creates a new solution instance with the document specified updated to have the specified name. /// </summary> public SolutionState WithDocumentName(DocumentId documentId, string name) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.Attributes.Name == name) { return this; } return UpdateDocumentState(oldDocument.UpdateName(name)); } /// <summary> /// Creates a new solution instance with the document specified updated to be contained in /// the sequence of logical folders. /// </summary> public SolutionState WithDocumentFolders(DocumentId documentId, IReadOnlyList<string> folders) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.Folders.SequenceEqual(folders)) { return this; } return UpdateDocumentState(oldDocument.UpdateFolders(folders)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the specified file path. /// </summary> public SolutionState WithDocumentFilePath(DocumentId documentId, string? filePath) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.FilePath == filePath) { return this; } return UpdateDocumentState(oldDocument.UpdateFilePath(filePath)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the text /// specified. /// </summary> public SolutionState WithDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.TryGetText(out var oldText) && text == oldText) { return this; } return UpdateDocumentState(oldDocument.UpdateText(text, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the additional document specified updated to have the text /// specified. /// </summary> public SolutionState WithAdditionalDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAdditionalDocumentState(documentId); if (oldDocument.TryGetText(out var oldText) && text == oldText) { return this; } return UpdateAdditionalDocumentState(oldDocument.UpdateText(text, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the document specified updated to have the text /// specified. /// </summary> public SolutionState WithAnalyzerConfigDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId); if (oldDocument.TryGetText(out var oldText) && text == oldText) { return this; } return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(text, mode)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the text /// and version specified. /// </summary> public SolutionState WithDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion) { return this; } return UpdateDocumentState(oldDocument.UpdateText(textAndVersion, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the additional document specified updated to have the text /// and version specified. /// </summary> public SolutionState WithAdditionalDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAdditionalDocumentState(documentId); if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion) { return this; } return UpdateAdditionalDocumentState(oldDocument.UpdateText(textAndVersion, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the analyzer config document specified updated to have the text /// and version specified. /// </summary> public SolutionState WithAnalyzerConfigDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId); if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion) { return this; } return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(textAndVersion, mode)); } /// <summary> /// Creates a new solution instance with the document specified updated to have a syntax tree /// rooted by the specified syntax node. /// </summary> public SolutionState WithDocumentSyntaxRoot(DocumentId documentId, SyntaxNode root, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.TryGetSyntaxTree(out var oldTree) && oldTree.TryGetRoot(out var oldRoot) && oldRoot == root) { return this; } return UpdateDocumentState(oldDocument.UpdateTree(root, mode), textChanged: true); } private static async Task<Compilation> UpdateDocumentInCompilationAsync( Compilation compilation, DocumentState oldDocument, DocumentState newDocument, CancellationToken cancellationToken) { return compilation.ReplaceSyntaxTree( await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false), await newDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the source /// code kind specified. /// </summary> public SolutionState WithDocumentSourceCodeKind(DocumentId documentId, SourceCodeKind sourceCodeKind) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.SourceCodeKind == sourceCodeKind) { return this; } return UpdateDocumentState(oldDocument.UpdateSourceCodeKind(sourceCodeKind), textChanged: true); } public SolutionState UpdateDocumentTextLoader(DocumentId documentId, TextLoader loader, SourceText? text, PreservationMode mode) { var oldDocument = GetRequiredDocumentState(documentId); // Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with // old content. Also this should make sure we don't re-use latest doc version with data associated with opened document. return UpdateDocumentState(oldDocument.UpdateText(loader, text, mode), textChanged: true, recalculateDependentVersions: true); } /// <summary> /// Creates a new solution instance with the additional document specified updated to have the text /// supplied by the text loader. /// </summary> public SolutionState UpdateAdditionalDocumentTextLoader(DocumentId documentId, TextLoader loader, PreservationMode mode) { var oldDocument = GetRequiredAdditionalDocumentState(documentId); // Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with // old content. Also this should make sure we don't re-use latest doc version with data associated with opened document. return UpdateAdditionalDocumentState(oldDocument.UpdateText(loader, mode), textChanged: true, recalculateDependentVersions: true); } /// <summary> /// Creates a new solution instance with the analyzer config document specified updated to have the text /// supplied by the text loader. /// </summary> public SolutionState UpdateAnalyzerConfigDocumentTextLoader(DocumentId documentId, TextLoader loader, PreservationMode mode) { var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId); // Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with // old content. Also this should make sure we don't re-use latest doc version with data associated with opened document. return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(loader, mode)); } private SolutionState UpdateDocumentState(DocumentState newDocument, bool textChanged = false, bool recalculateDependentVersions = false) { var oldProject = GetProjectState(newDocument.Id.ProjectId)!; var newProject = oldProject.UpdateDocument(newDocument, textChanged, recalculateDependentVersions); // This method shouldn't have been called if the document has not changed. Debug.Assert(oldProject != newProject); var oldDocument = oldProject.DocumentStates.GetRequiredState(newDocument.Id); var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithFilePath(newDocument.Id, oldDocument.FilePath, newDocument.FilePath); return ForkProject( newProject, new CompilationAndGeneratorDriverTranslationAction.TouchDocumentAction(oldDocument, newDocument), newFilePathToDocumentIdsMap: newFilePathToDocumentIdsMap); } private SolutionState UpdateAdditionalDocumentState(AdditionalDocumentState newDocument, bool textChanged = false, bool recalculateDependentVersions = false) { var oldProject = GetProjectState(newDocument.Id.ProjectId)!; var newProject = oldProject.UpdateAdditionalDocument(newDocument, textChanged, recalculateDependentVersions); // This method shouldn't have been called if the document has not changed. Debug.Assert(oldProject != newProject); var oldDocument = oldProject.AdditionalDocumentStates.GetRequiredState(newDocument.Id); return ForkProject( newProject, translate: new CompilationAndGeneratorDriverTranslationAction.TouchAdditionalDocumentAction(oldDocument, newDocument)); } private SolutionState UpdateAnalyzerConfigDocumentState(AnalyzerConfigDocumentState newDocument) { var oldProject = GetProjectState(newDocument.Id.ProjectId)!; var newProject = oldProject.UpdateAnalyzerConfigDocument(newDocument); // This method shouldn't have been called if the document has not changed. Debug.Assert(oldProject != newProject); return ForkProject(newProject, newProject.CompilationOptions != null ? new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true) : null); } /// <summary> /// Creates a new snapshot with an updated project and an action that will produce a new /// compilation matching the new project out of an old compilation. All dependent projects /// are fixed-up if the change to the new project affects its public metadata, and old /// dependent compilations are forgotten. /// </summary> private SolutionState ForkProject( ProjectState newProjectState, CompilationAndGeneratorDriverTranslationAction? translate = null, ProjectDependencyGraph? newDependencyGraph = null, ImmutableDictionary<string, ImmutableArray<DocumentId>>? newFilePathToDocumentIdsMap = null, bool forkTracker = true) { var projectId = newProjectState.Id; var newStateMap = _projectIdToProjectStateMap.SetItem(projectId, newProjectState); // Remote supported languages can only change if the project changes language. This is an unexpected edge // case, so it's not optimized for incremental updates. var newLanguages = !_projectIdToProjectStateMap.TryGetValue(projectId, out var projectState) || projectState.Language != newProjectState.Language ? GetRemoteSupportedProjectLanguages(newStateMap) : _remoteSupportedLanguages; newDependencyGraph ??= _dependencyGraph; var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph); // If we have a tracker for this project, then fork it as well (along with the // translation action and store it in the tracker map. if (newTrackerMap.TryGetValue(projectId, out var tracker)) { newTrackerMap = newTrackerMap.Remove(projectId); if (forkTracker) { newTrackerMap = newTrackerMap.Add(projectId, tracker.Fork(newProjectState, translate)); } } return this.Branch( idToProjectStateMap: newStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newTrackerMap, dependencyGraph: newDependencyGraph, filePathToDocumentIdsMap: newFilePathToDocumentIdsMap ?? _filePathToDocumentIdsMap); } /// <summary> /// Gets the set of <see cref="DocumentId"/>s in this <see cref="Solution"/> with a /// <see cref="TextDocument.FilePath"/> that matches the given file path. /// </summary> public ImmutableArray<DocumentId> GetDocumentIdsWithFilePath(string? filePath) { if (string.IsNullOrEmpty(filePath)) { return ImmutableArray<DocumentId>.Empty; } return _filePathToDocumentIdsMap.TryGetValue(filePath!, out var documentIds) ? documentIds : ImmutableArray<DocumentId>.Empty; } private static ProjectDependencyGraph CreateDependencyGraph( IReadOnlyList<ProjectId> projectIds, ImmutableDictionary<ProjectId, ProjectState> projectStates) { var map = projectStates.Values.Select(state => new KeyValuePair<ProjectId, ImmutableHashSet<ProjectId>>( state.Id, state.ProjectReferences.Where(pr => projectStates.ContainsKey(pr.ProjectId)).Select(pr => pr.ProjectId).ToImmutableHashSet())) .ToImmutableDictionary(); return new ProjectDependencyGraph(projectIds.ToImmutableHashSet(), map); } private ImmutableDictionary<ProjectId, ICompilationTracker> CreateCompilationTrackerMap(ProjectId changedProjectId, ProjectDependencyGraph dependencyGraph) { var builder = ImmutableDictionary.CreateBuilder<ProjectId, ICompilationTracker>(); IEnumerable<ProjectId>? dependencies = null; foreach (var (id, tracker) in _projectIdToTrackerMap) { if (!tracker.HasCompilation) { continue; } builder.Add(id, CanReuse(id) ? tracker : tracker.Fork(tracker.ProjectState)); } return builder.ToImmutable(); // Returns true if 'tracker' can be reused for project 'id' bool CanReuse(ProjectId id) { if (id == changedProjectId) { return true; } // Check the dependency graph to see if project 'id' directly or transitively depends on 'projectId'. // If the information is not available, do not compute it. var forwardDependencies = dependencyGraph.TryGetProjectsThatThisProjectTransitivelyDependsOn(id); if (forwardDependencies is object && !forwardDependencies.Contains(changedProjectId)) { return true; } // Compute the set of all projects that depend on 'projectId'. This information answers the same // question as the previous check, but involves at most one transitive computation within the // dependency graph. dependencies ??= dependencyGraph.GetProjectsThatTransitivelyDependOnThisProject(changedProjectId); return !dependencies.Contains(id); } } public SolutionState WithOptions(SerializableOptionSet options) => Branch(options: options); public SolutionState AddAnalyzerReferences(IReadOnlyCollection<AnalyzerReference> analyzerReferences) { if (analyzerReferences.Count == 0) { return this; } var oldReferences = AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(analyzerReferences); return Branch(analyzerReferences: newReferences); } public SolutionState RemoveAnalyzerReference(AnalyzerReference analyzerReference) { var oldReferences = AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.Remove(analyzerReference); if (oldReferences == newReferences) { return this; } return Branch(analyzerReferences: newReferences); } public SolutionState WithAnalyzerReferences(IReadOnlyList<AnalyzerReference> analyzerReferences) { if (analyzerReferences == AnalyzerReferences) { return this; } return Branch(analyzerReferences: analyzerReferences); } // this lock guards all the mutable fields (do not share lock with derived classes) private NonReentrantLock? _stateLockBackingField; private NonReentrantLock StateLock { get { // TODO: why did I need to do a nullable suppression here? return LazyInitializer.EnsureInitialized(ref _stateLockBackingField, NonReentrantLock.Factory)!; } } private WeakReference<SolutionState>? _latestSolutionWithPartialCompilation; private DateTime _timeOfLatestSolutionWithPartialCompilation; private DocumentId? _documentIdOfLatestSolutionWithPartialCompilation; /// <summary> /// Creates a branch of the solution that has its compilations frozen in whatever state they are in at the time, assuming a background compiler is /// busy building this compilations. /// /// A compilation for the project containing the specified document id will be guaranteed to exist with at least the syntax tree for the document. /// /// This not intended to be the public API, use Document.WithFrozenPartialSemantics() instead. /// </summary> public SolutionState WithFrozenPartialCompilationIncludingSpecificDocument(DocumentId documentId, CancellationToken cancellationToken) { try { var doc = this.GetRequiredDocumentState(documentId); var tree = doc.GetSyntaxTree(cancellationToken); using (this.StateLock.DisposableWait(cancellationToken)) { // in progress solutions are disabled for some testing if (this.Workspace is Workspace ws && ws.TestHookPartialSolutionsDisabled) { return this; } SolutionState? currentPartialSolution = null; if (_latestSolutionWithPartialCompilation != null) { _latestSolutionWithPartialCompilation.TryGetTarget(out currentPartialSolution); } var reuseExistingPartialSolution = currentPartialSolution != null && (DateTime.UtcNow - _timeOfLatestSolutionWithPartialCompilation).TotalSeconds < 0.1 && _documentIdOfLatestSolutionWithPartialCompilation == documentId; if (reuseExistingPartialSolution) { SolutionLogger.UseExistingPartialSolution(); return currentPartialSolution!; } // if we don't have one or it is stale, create a new partial solution var tracker = this.GetCompilationTracker(documentId.ProjectId); var newTracker = tracker.FreezePartialStateWithTree(this, doc, tree, cancellationToken); var newIdToProjectStateMap = _projectIdToProjectStateMap.SetItem(documentId.ProjectId, newTracker.ProjectState); var newLanguages = _remoteSupportedLanguages; var newIdToTrackerMap = _projectIdToTrackerMap.SetItem(documentId.ProjectId, newTracker); currentPartialSolution = this.Branch( idToProjectStateMap: newIdToProjectStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newIdToTrackerMap, dependencyGraph: CreateDependencyGraph(ProjectIds, newIdToProjectStateMap)); _latestSolutionWithPartialCompilation = new WeakReference<SolutionState>(currentPartialSolution); _timeOfLatestSolutionWithPartialCompilation = DateTime.UtcNow; _documentIdOfLatestSolutionWithPartialCompilation = documentId; SolutionLogger.CreatePartialSolution(); return currentPartialSolution; } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Creates a new solution instance with all the documents specified updated to have the same specified text. /// </summary> public SolutionState WithDocumentText(IEnumerable<DocumentId?> documentIds, SourceText text, PreservationMode mode) { var solution = this; foreach (var documentId in documentIds) { if (documentId == null) { continue; } var doc = GetProjectState(documentId.ProjectId)?.DocumentStates.GetState(documentId); if (doc != null) { if (!doc.TryGetText(out var existingText) || existingText != text) { solution = solution.WithDocumentText(documentId, text, mode); } } } return solution; } public bool TryGetCompilation(ProjectId projectId, [NotNullWhen(returnValue: true)] out Compilation? compilation) { CheckContainsProject(projectId); compilation = null; return this.TryGetCompilationTracker(projectId, out var tracker) && tracker.TryGetCompilation(out compilation); } /// <summary> /// Returns the compilation for the specified <see cref="ProjectId"/>. Can return <see langword="null"/> when the project /// does not support compilations. /// </summary> /// <remarks> /// The compilation is guaranteed to have a syntax tree for each document of the project. /// </remarks> private Task<Compilation?> GetCompilationAsync(ProjectId projectId, CancellationToken cancellationToken) { // TODO: figure out where this is called and why the nullable suppression is required return GetCompilationAsync(GetProjectState(projectId)!, cancellationToken); } /// <summary> /// Returns the compilation for the specified <see cref="ProjectState"/>. Can return <see langword="null"/> when the project /// does not support compilations. /// </summary> /// <remarks> /// The compilation is guaranteed to have a syntax tree for each document of the project. /// </remarks> public Task<Compilation?> GetCompilationAsync(ProjectState project, CancellationToken cancellationToken) { return project.SupportsCompilation ? GetCompilationTracker(project.Id).GetCompilationAsync(this, cancellationToken).AsNullable() : SpecializedTasks.Null<Compilation>(); } /// <summary> /// Return reference completeness for the given project and all projects this references. /// </summary> public Task<bool> HasSuccessfullyLoadedAsync(ProjectState project, CancellationToken cancellationToken) { // return HasAllInformation when compilation is not supported. // regardless whether project support compilation or not, if projectInfo is not complete, we can't guarantee its reference completeness return project.SupportsCompilation ? this.GetCompilationTracker(project.Id).HasSuccessfullyLoadedAsync(this, cancellationToken) : project.HasAllInformation ? SpecializedTasks.True : SpecializedTasks.False; } /// <summary> /// Returns the generated document states for source generated documents. /// </summary> public ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(ProjectState project, CancellationToken cancellationToken) { return project.SupportsCompilation ? GetCompilationTracker(project.Id).GetSourceGeneratedDocumentStatesAsync(this, cancellationToken) : new(TextDocumentStates<SourceGeneratedDocumentState>.Empty); } /// <summary> /// Returns the <see cref="SourceGeneratedDocumentState"/> for a source generated document that has already been generated and observed. /// </summary> /// <remarks> /// This is only safe to call if you already have seen the SyntaxTree or equivalent that indicates the document state has already been /// generated. This method exists to implement <see cref="Solution.GetDocument(SyntaxTree?)"/> and is best avoided unless you're doing something /// similarly tricky like that. /// </remarks> public SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId) { return GetCompilationTracker(documentId.ProjectId).TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentId); } /// <summary> /// Returns a new SolutionState that will always produce a specific output for a generated file. This is used only in the /// implementation of <see cref="TextExtensions.GetOpenDocumentInCurrentContextWithChanges"/> where if a user has a source /// generated file open, we need to make sure everything lines up. /// </summary> public SolutionState WithFrozenSourceGeneratedDocument(SourceGeneratedDocumentIdentity documentIdentity, SourceText sourceText) { // We won't support freezing multiple source generated documents at once. Although nothing in the implementation // of this method would have problems, this simplifies the handling of serializing this solution to out-of-proc. // Since we only produce these snapshots from an open document, there should be no way to observe this, so this assertion // also serves as a good check on the system. If down the road we need to support this, we can remove this check and // update the out-of-process serialization logic accordingly. Contract.ThrowIfTrue(_frozenSourceGeneratedDocumentState != null, "We shouldn't be calling WithFrozenSourceGeneratedDocument on a solution with a frozen source generated document."); var existingGeneratedState = TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentIdentity.DocumentId); SourceGeneratedDocumentState newGeneratedState; if (existingGeneratedState != null) { newGeneratedState = existingGeneratedState.WithUpdatedGeneratedContent(sourceText, existingGeneratedState.ParseOptions); // If the content already matched, we can just reuse the existing state if (newGeneratedState == existingGeneratedState) { return this; } } else { var projectState = GetRequiredProjectState(documentIdentity.DocumentId.ProjectId); newGeneratedState = SourceGeneratedDocumentState.Create( documentIdentity, sourceText, projectState.ParseOptions!, projectState.LanguageServices, _solutionServices); } var projectId = documentIdentity.DocumentId.ProjectId; var newTrackerMap = CreateCompilationTrackerMap(projectId, _dependencyGraph); // We want to create a new snapshot with a new compilation tracker that will do this replacement. // If we already have an existing tracker we'll just wrap that (so we also are reusing any underlying // computations). If we don't have one, we'll create one and then wrap it. if (!newTrackerMap.TryGetValue(projectId, out var existingTracker)) { existingTracker = CreateCompilationTracker(projectId, this); } newTrackerMap = newTrackerMap.SetItem( projectId, new GeneratedFileReplacingCompilationTracker(existingTracker, newGeneratedState)); return this.Branch( projectIdToTrackerMap: newTrackerMap, frozenSourceGeneratedDocument: newGeneratedState); } /// <summary> /// Symbols need to be either <see cref="IAssemblySymbol"/> or <see cref="IModuleSymbol"/>. /// </summary> private static readonly ConditionalWeakTable<ISymbol, ProjectId> s_assemblyOrModuleSymbolToProjectMap = new(); /// <summary> /// Get a metadata reference for the project's compilation /// </summary> public Task<MetadataReference> GetMetadataReferenceAsync(ProjectReference projectReference, ProjectState fromProject, CancellationToken cancellationToken) { try { // Get the compilation state for this project. If it's not already created, then this // will create it. Then force that state to completion and get a metadata reference to it. var tracker = this.GetCompilationTracker(projectReference.ProjectId); return tracker.GetMetadataReferenceAsync(this, fromProject, projectReference, cancellationToken); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Attempt to get the best readily available compilation for the project. It may be a /// partially built compilation. /// </summary> private MetadataReference? GetPartialMetadataReference( ProjectReference projectReference, ProjectState fromProject) { // Try to get the compilation state for this project. If it doesn't exist, don't do any // more work. if (!_projectIdToTrackerMap.TryGetValue(projectReference.ProjectId, out var state)) { return null; } return state.GetPartialMetadataReference(fromProject, projectReference); } public async Task<bool> ContainsSymbolsWithNameAsync(ProjectId id, string name, SymbolFilter filter, CancellationToken cancellationToken) { var result = GetCompilationTracker(id).ContainsSymbolsWithNameFromDeclarationOnlyCompilation(name, filter, cancellationToken); if (result.HasValue) { return result.Value; } // it looks like declaration compilation doesn't exist yet. we have to build full compilation var compilation = await GetCompilationAsync(id, cancellationToken).ConfigureAwait(false); if (compilation == null) { // some projects don't support compilations (e.g., TypeScript) so there's nothing to check return false; } return compilation.ContainsSymbolsWithName(name, filter, cancellationToken); } public async Task<bool> ContainsSymbolsWithNameAsync(ProjectId id, Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken) { var result = GetCompilationTracker(id).ContainsSymbolsWithNameFromDeclarationOnlyCompilation(predicate, filter, cancellationToken); if (result.HasValue) { return result.Value; } // it looks like declaration compilation doesn't exist yet. we have to build full compilation var compilation = await GetCompilationAsync(id, cancellationToken).ConfigureAwait(false); if (compilation == null) { // some projects don't support compilations (e.g., TypeScript) so there's nothing to check return false; } return compilation.ContainsSymbolsWithName(predicate, filter, cancellationToken); } /// <summary> /// Gets a <see cref="ProjectDependencyGraph"/> that details the dependencies between projects for this solution. /// </summary> public ProjectDependencyGraph GetProjectDependencyGraph() => _dependencyGraph; private void CheckNotContainsProject(ProjectId projectId) { if (this.ContainsProject(projectId)) { throw new InvalidOperationException(WorkspacesResources.The_solution_already_contains_the_specified_project); } } private void CheckContainsProject(ProjectId projectId) { if (!this.ContainsProject(projectId)) { throw new InvalidOperationException(WorkspacesResources.The_solution_does_not_contain_the_specified_project); } } internal bool ContainsProjectReference(ProjectId projectId, ProjectReference projectReference) => GetRequiredProjectState(projectId).ProjectReferences.Contains(projectReference); internal bool ContainsMetadataReference(ProjectId projectId, MetadataReference metadataReference) => GetRequiredProjectState(projectId).MetadataReferences.Contains(metadataReference); internal bool ContainsAnalyzerReference(ProjectId projectId, AnalyzerReference analyzerReference) => GetRequiredProjectState(projectId).AnalyzerReferences.Contains(analyzerReference); internal bool ContainsTransitiveReference(ProjectId fromProjectId, ProjectId toProjectId) => _dependencyGraph.GetProjectsThatThisProjectTransitivelyDependsOn(fromProjectId).Contains(toProjectId); internal ImmutableHashSet<string> GetRemoteSupportedProjectLanguages() => _remoteSupportedLanguages; private static ImmutableHashSet<string> GetRemoteSupportedProjectLanguages(ImmutableDictionary<ProjectId, ProjectState> projectStates) { var builder = ImmutableHashSet.CreateBuilder<string>(); foreach (var projectState in projectStates) { if (RemoteSupportedLanguages.IsSupported(projectState.Value.Language)) { builder.Add(projectState.Value.Language); } } return builder.ToImmutable(); } } }
// Licensed to the .NET Foundation under one or more 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.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Logging; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a set of projects and their source code documents. /// /// this is a green node of Solution like ProjectState/DocumentState are for /// Project and Document. /// </summary> internal partial class SolutionState { // branch id for this solution private readonly BranchId _branchId; // the version of the workspace this solution is from private readonly int _workspaceVersion; private readonly SolutionInfo.SolutionAttributes _solutionAttributes; private readonly SolutionServices _solutionServices; private readonly ImmutableDictionary<ProjectId, ProjectState> _projectIdToProjectStateMap; private readonly ImmutableHashSet<string> _remoteSupportedLanguages; private readonly ImmutableDictionary<string, ImmutableArray<DocumentId>> _filePathToDocumentIdsMap; private readonly ProjectDependencyGraph _dependencyGraph; public readonly IReadOnlyList<AnalyzerReference> AnalyzerReferences; // Values for all these are created on demand. private ImmutableDictionary<ProjectId, ICompilationTracker> _projectIdToTrackerMap; // Checksums for this solution state private readonly ValueSource<SolutionStateChecksums> _lazyChecksums; /// <summary> /// Mapping from project-id to the options and checksums needed to synchronize it (and the projects it depends on) over /// to an OOP host. Options are stored as well so that when we are attempting to match a request for a particular project-subset /// we can return the options specific to that project-subset (which may be different from the <see cref="Options"/> defined /// for the entire solution). Lock this specific field before reading/writing to it. /// </summary> private readonly Dictionary<ProjectId, (SerializableOptionSet options, ValueSource<SolutionStateChecksums> checksums)> _lazyProjectChecksums = new(); // holds on data calculated based on the AnalyzerReferences list private readonly Lazy<HostDiagnosticAnalyzers> _lazyAnalyzers; /// <summary> /// Cache we use to map between unrooted symbols (i.e. assembly, module and dynamic symbols) and the project /// they came from. That way if we are asked about many symbols from the same assembly/module we can answer the /// question quickly after computing for the first one. Created on demand. /// </summary> private ConditionalWeakTable<ISymbol, ProjectId?>? _unrootedSymbolToProjectId; private static readonly Func<ConditionalWeakTable<ISymbol, ProjectId?>> s_createTable = () => new ConditionalWeakTable<ISymbol, ProjectId?>(); private readonly SourceGeneratedDocumentState? _frozenSourceGeneratedDocumentState; private SolutionState( BranchId branchId, int workspaceVersion, SolutionServices solutionServices, SolutionInfo.SolutionAttributes solutionAttributes, IReadOnlyList<ProjectId> projectIds, SerializableOptionSet options, IReadOnlyList<AnalyzerReference> analyzerReferences, ImmutableDictionary<ProjectId, ProjectState> idToProjectStateMap, ImmutableHashSet<string> remoteSupportedLanguages, ImmutableDictionary<ProjectId, ICompilationTracker> projectIdToTrackerMap, ImmutableDictionary<string, ImmutableArray<DocumentId>> filePathToDocumentIdsMap, ProjectDependencyGraph dependencyGraph, Lazy<HostDiagnosticAnalyzers>? lazyAnalyzers, SourceGeneratedDocumentState? frozenSourceGeneratedDocument) { _branchId = branchId; _workspaceVersion = workspaceVersion; _solutionAttributes = solutionAttributes; _solutionServices = solutionServices; ProjectIds = projectIds; Options = options; AnalyzerReferences = analyzerReferences; _projectIdToProjectStateMap = idToProjectStateMap; _remoteSupportedLanguages = remoteSupportedLanguages; _projectIdToTrackerMap = projectIdToTrackerMap; _filePathToDocumentIdsMap = filePathToDocumentIdsMap; _dependencyGraph = dependencyGraph; _lazyAnalyzers = lazyAnalyzers ?? CreateLazyHostDiagnosticAnalyzers(analyzerReferences); _frozenSourceGeneratedDocumentState = frozenSourceGeneratedDocument; // when solution state is changed, we recalculate its checksum _lazyChecksums = new AsyncLazy<SolutionStateChecksums>( c => ComputeChecksumsAsync(projectsToInclude: null, Options, c), cacheResult: true); CheckInvariants(); // make sure we don't accidentally capture any state but the list of references: static Lazy<HostDiagnosticAnalyzers> CreateLazyHostDiagnosticAnalyzers(IReadOnlyList<AnalyzerReference> analyzerReferences) => new(() => new HostDiagnosticAnalyzers(analyzerReferences)); } public SolutionState( BranchId primaryBranchId, SolutionServices solutionServices, SolutionInfo.SolutionAttributes solutionAttributes, SerializableOptionSet options, IReadOnlyList<AnalyzerReference> analyzerReferences) : this( primaryBranchId, workspaceVersion: 0, solutionServices, solutionAttributes, projectIds: SpecializedCollections.EmptyBoxedImmutableArray<ProjectId>(), options, analyzerReferences, idToProjectStateMap: ImmutableDictionary<ProjectId, ProjectState>.Empty, remoteSupportedLanguages: ImmutableHashSet<string>.Empty, projectIdToTrackerMap: ImmutableDictionary<ProjectId, ICompilationTracker>.Empty, filePathToDocumentIdsMap: ImmutableDictionary.Create<string, ImmutableArray<DocumentId>>(StringComparer.OrdinalIgnoreCase), dependencyGraph: ProjectDependencyGraph.Empty, lazyAnalyzers: null, frozenSourceGeneratedDocument: null) { } public SolutionState WithNewWorkspace(Workspace workspace, int workspaceVersion) { var services = workspace != _solutionServices.Workspace ? new SolutionServices(workspace) : _solutionServices; // Note: this will potentially have problems if the workspace services are different, as some services // get locked-in by document states and project states when first constructed. return CreatePrimarySolution(branchId: workspace.PrimaryBranchId, workspaceVersion: workspaceVersion, services: services); } public HostDiagnosticAnalyzers Analyzers => _lazyAnalyzers.Value; public SolutionInfo.SolutionAttributes SolutionAttributes => _solutionAttributes; public SourceGeneratedDocumentState? FrozenSourceGeneratedDocumentState => _frozenSourceGeneratedDocumentState; public ImmutableDictionary<ProjectId, ProjectState> ProjectStates => _projectIdToProjectStateMap; public int WorkspaceVersion => _workspaceVersion; public SolutionServices Services => _solutionServices; public SerializableOptionSet Options { get; } /// <summary> /// branch id of this solution /// /// currently, it only supports one level of branching. there is a primary branch of a workspace and all other /// branches that are branched from the primary branch. /// /// one still can create multiple forked solutions from an already branched solution, but versions among those /// can't be reliably used and compared. /// /// version only has a meaning between primary solution and branched one or between solutions from same branch. /// </summary> public BranchId BranchId => _branchId; /// <summary> /// The Workspace this solution is associated with. /// </summary> public Workspace Workspace => _solutionServices.Workspace; /// <summary> /// The Id of the solution. Multiple solution instances may share the same Id. /// </summary> public SolutionId Id => _solutionAttributes.Id; /// <summary> /// The path to the solution file or null if there is no solution file. /// </summary> public string? FilePath => _solutionAttributes.FilePath; /// <summary> /// The solution version. This equates to the solution file's version. /// </summary> public VersionStamp Version => _solutionAttributes.Version; /// <summary> /// A list of all the ids for all the projects contained by the solution. /// </summary> public IReadOnlyList<ProjectId> ProjectIds { get; } // Only run this in debug builds; even the .Any() call across all projects can be expensive when there's a lot of them. [Conditional("DEBUG")] private void CheckInvariants() { Contract.ThrowIfFalse(_projectIdToProjectStateMap.Count == ProjectIds.Count); Contract.ThrowIfFalse(_projectIdToProjectStateMap.Count == _dependencyGraph.ProjectIds.Count); // An id shouldn't point at a tracker for a different project. Contract.ThrowIfTrue(_projectIdToTrackerMap.Any(kvp => kvp.Key != kvp.Value.ProjectState.Id)); // project ids must be the same: Debug.Assert(_projectIdToProjectStateMap.Keys.SetEquals(ProjectIds)); Debug.Assert(_projectIdToProjectStateMap.Keys.SetEquals(_dependencyGraph.ProjectIds)); Debug.Assert(_remoteSupportedLanguages.SetEquals(GetRemoteSupportedProjectLanguages(_projectIdToProjectStateMap))); } private SolutionState Branch( SolutionInfo.SolutionAttributes? solutionAttributes = null, IReadOnlyList<ProjectId>? projectIds = null, SerializableOptionSet? options = null, IReadOnlyList<AnalyzerReference>? analyzerReferences = null, ImmutableDictionary<ProjectId, ProjectState>? idToProjectStateMap = null, ImmutableHashSet<string>? remoteSupportedProjectLanguages = null, ImmutableDictionary<ProjectId, ICompilationTracker>? projectIdToTrackerMap = null, ImmutableDictionary<string, ImmutableArray<DocumentId>>? filePathToDocumentIdsMap = null, ProjectDependencyGraph? dependencyGraph = null, Optional<SourceGeneratedDocumentState?> frozenSourceGeneratedDocument = default) { var branchId = GetBranchId(); if (idToProjectStateMap is not null) { Contract.ThrowIfNull(remoteSupportedProjectLanguages); } solutionAttributes ??= _solutionAttributes; projectIds ??= ProjectIds; idToProjectStateMap ??= _projectIdToProjectStateMap; remoteSupportedProjectLanguages ??= _remoteSupportedLanguages; Debug.Assert(remoteSupportedProjectLanguages.SetEquals(GetRemoteSupportedProjectLanguages(idToProjectStateMap))); options ??= Options.WithLanguages(remoteSupportedProjectLanguages); analyzerReferences ??= AnalyzerReferences; projectIdToTrackerMap ??= _projectIdToTrackerMap; filePathToDocumentIdsMap ??= _filePathToDocumentIdsMap; dependencyGraph ??= _dependencyGraph; var newFrozenSourceGeneratedDocumentState = frozenSourceGeneratedDocument.HasValue ? frozenSourceGeneratedDocument.Value : _frozenSourceGeneratedDocumentState; var analyzerReferencesEqual = AnalyzerReferences.SequenceEqual(analyzerReferences); if (branchId == _branchId && solutionAttributes == _solutionAttributes && projectIds == ProjectIds && options == Options && analyzerReferencesEqual && idToProjectStateMap == _projectIdToProjectStateMap && projectIdToTrackerMap == _projectIdToTrackerMap && filePathToDocumentIdsMap == _filePathToDocumentIdsMap && dependencyGraph == _dependencyGraph && newFrozenSourceGeneratedDocumentState == _frozenSourceGeneratedDocumentState) { return this; } return new SolutionState( branchId, _workspaceVersion, _solutionServices, solutionAttributes, projectIds, options, analyzerReferences, idToProjectStateMap, remoteSupportedProjectLanguages, projectIdToTrackerMap, filePathToDocumentIdsMap, dependencyGraph, analyzerReferencesEqual ? _lazyAnalyzers : null, newFrozenSourceGeneratedDocumentState); } private SolutionState CreatePrimarySolution( BranchId branchId, int workspaceVersion, SolutionServices services) { if (branchId == _branchId && workspaceVersion == _workspaceVersion && services == _solutionServices) { return this; } return new SolutionState( branchId, workspaceVersion, services, _solutionAttributes, ProjectIds, Options, AnalyzerReferences, _projectIdToProjectStateMap, _remoteSupportedLanguages, _projectIdToTrackerMap, _filePathToDocumentIdsMap, _dependencyGraph, _lazyAnalyzers, frozenSourceGeneratedDocument: null); } private BranchId GetBranchId() { // currently we only support one level branching. // my reasonings are // 1. it seems there is no-one who needs sub branches. // 2. this lets us to branch without explicit branch API return _branchId == Workspace.PrimaryBranchId ? BranchId.GetNextId() : _branchId; } /// <summary> /// The version of the most recently modified project. /// </summary> public VersionStamp GetLatestProjectVersion() { // this may produce a version that is out of sync with the actual Document versions. var latestVersion = VersionStamp.Default; foreach (var project in this.ProjectStates.Values) { latestVersion = project.Version.GetNewerVersion(latestVersion); } return latestVersion; } /// <summary> /// True if the solution contains a project with the specified project ID. /// </summary> public bool ContainsProject([NotNullWhen(returnValue: true)] ProjectId? projectId) => projectId != null && _projectIdToProjectStateMap.ContainsKey(projectId); /// <summary> /// True if the solution contains the document in one of its projects /// </summary> public bool ContainsDocument([NotNullWhen(returnValue: true)] DocumentId? documentId) { return documentId != null && this.ContainsProject(documentId.ProjectId) && this.GetProjectState(documentId.ProjectId)!.DocumentStates.Contains(documentId); } /// <summary> /// True if the solution contains the additional document in one of its projects /// </summary> public bool ContainsAdditionalDocument([NotNullWhen(returnValue: true)] DocumentId? documentId) { return documentId != null && this.ContainsProject(documentId.ProjectId) && this.GetProjectState(documentId.ProjectId)!.AdditionalDocumentStates.Contains(documentId); } /// <summary> /// True if the solution contains the analyzer config document in one of its projects /// </summary> public bool ContainsAnalyzerConfigDocument([NotNullWhen(returnValue: true)] DocumentId? documentId) { return documentId != null && this.ContainsProject(documentId.ProjectId) && this.GetProjectState(documentId.ProjectId)!.AnalyzerConfigDocumentStates.Contains(documentId); } private DocumentState GetRequiredDocumentState(DocumentId documentId) => GetRequiredProjectState(documentId.ProjectId).DocumentStates.GetRequiredState(documentId); private AdditionalDocumentState GetRequiredAdditionalDocumentState(DocumentId documentId) => GetRequiredProjectState(documentId.ProjectId).AdditionalDocumentStates.GetRequiredState(documentId); private AnalyzerConfigDocumentState GetRequiredAnalyzerConfigDocumentState(DocumentId documentId) => GetRequiredProjectState(documentId.ProjectId).AnalyzerConfigDocumentStates.GetRequiredState(documentId); internal DocumentState? GetDocumentState(SyntaxTree? syntaxTree, ProjectId? projectId) { if (syntaxTree != null) { // is this tree known to be associated with a document? var documentId = DocumentState.GetDocumentIdForTree(syntaxTree); if (documentId != null && (projectId == null || documentId.ProjectId == projectId)) { // does this solution even have the document? var projectState = GetProjectState(documentId.ProjectId); if (projectState != null) { var document = projectState.DocumentStates.GetState(documentId); if (document != null) { // does this document really have the syntax tree? if (document.TryGetSyntaxTree(out var documentTree) && documentTree == syntaxTree) { return document; } } else { var generatedDocument = TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentId); if (generatedDocument != null) { // does this document really have the syntax tree? if (generatedDocument.TryGetSyntaxTree(out var documentTree) && documentTree == syntaxTree) { return generatedDocument; } } } } } } return null; } public Task<VersionStamp> GetDependentVersionAsync(ProjectId projectId, CancellationToken cancellationToken) => this.GetCompilationTracker(projectId).GetDependentVersionAsync(this, cancellationToken); public Task<VersionStamp> GetDependentSemanticVersionAsync(ProjectId projectId, CancellationToken cancellationToken) => this.GetCompilationTracker(projectId).GetDependentSemanticVersionAsync(this, cancellationToken); public ProjectState? GetProjectState(ProjectId projectId) { _projectIdToProjectStateMap.TryGetValue(projectId, out var state); return state; } public ProjectState GetRequiredProjectState(ProjectId projectId) { var result = GetProjectState(projectId); Contract.ThrowIfNull(result); return result; } /// <summary> /// Gets the <see cref="Project"/> associated with an assembly symbol. /// </summary> public ProjectState? GetProjectState(IAssemblySymbol? assemblySymbol) { if (assemblySymbol == null) return null; s_assemblyOrModuleSymbolToProjectMap.TryGetValue(assemblySymbol, out var id); return id == null ? null : this.GetProjectState(id); } private bool TryGetCompilationTracker(ProjectId projectId, [NotNullWhen(returnValue: true)] out ICompilationTracker? tracker) => _projectIdToTrackerMap.TryGetValue(projectId, out tracker); private static readonly Func<ProjectId, SolutionState, CompilationTracker> s_createCompilationTrackerFunction = CreateCompilationTracker; private static CompilationTracker CreateCompilationTracker(ProjectId projectId, SolutionState solution) { var projectState = solution.GetProjectState(projectId); Contract.ThrowIfNull(projectState); return new CompilationTracker(projectState); } private ICompilationTracker GetCompilationTracker(ProjectId projectId) { if (!_projectIdToTrackerMap.TryGetValue(projectId, out var tracker)) { tracker = ImmutableInterlocked.GetOrAdd(ref _projectIdToTrackerMap, projectId, s_createCompilationTrackerFunction, this); } return tracker; } private SolutionState AddProject(ProjectId projectId, ProjectState projectState) { // changed project list so, increment version. var newSolutionAttributes = _solutionAttributes.With(version: Version.GetNewerVersion()); var newProjectIds = ProjectIds.ToImmutableArray().Add(projectId); var newStateMap = _projectIdToProjectStateMap.Add(projectId, projectState); var newLanguages = RemoteSupportedLanguages.IsSupported(projectState.Language) ? _remoteSupportedLanguages.Add(projectState.Language) : _remoteSupportedLanguages; var newDependencyGraph = _dependencyGraph .WithAdditionalProject(projectId) .WithAdditionalProjectReferences(projectId, projectState.ProjectReferences); // It's possible that another project already in newStateMap has a reference to this project that we're adding, since we allow // dangling references like that. If so, we'll need to link those in too. foreach (var newState in newStateMap) { foreach (var projectReference in newState.Value.ProjectReferences) { if (projectReference.ProjectId == projectId) { newDependencyGraph = newDependencyGraph.WithAdditionalProjectReferences( newState.Key, SpecializedCollections.SingletonReadOnlyList(projectReference)); break; } } } var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph); var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithAddedDocuments(GetDocumentStates(newStateMap[projectId])); return Branch( solutionAttributes: newSolutionAttributes, projectIds: newProjectIds, idToProjectStateMap: newStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newTrackerMap, filePathToDocumentIdsMap: newFilePathToDocumentIdsMap, dependencyGraph: newDependencyGraph); } /// <summary> /// Create a new solution instance that includes a project with the specified project information. /// </summary> public SolutionState AddProject(ProjectInfo projectInfo) { if (projectInfo == null) { throw new ArgumentNullException(nameof(projectInfo)); } var projectId = projectInfo.Id; var language = projectInfo.Language; if (language == null) { throw new ArgumentNullException(nameof(language)); } var displayName = projectInfo.Name; if (displayName == null) { throw new ArgumentNullException(nameof(displayName)); } CheckNotContainsProject(projectId); var languageServices = this.Workspace.Services.GetLanguageServices(language); if (languageServices == null) { throw new ArgumentException(string.Format(WorkspacesResources.The_language_0_is_not_supported, language)); } var newProject = new ProjectState(projectInfo, languageServices, _solutionServices); return this.AddProject(newProject.Id, newProject); } private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithAddedDocuments(IEnumerable<TextDocumentState> documentStates) { var builder = _filePathToDocumentIdsMap.ToBuilder(); foreach (var documentState in documentStates) { var filePath = documentState.FilePath; if (RoslynString.IsNullOrEmpty(filePath)) { continue; } builder.MultiAdd(filePath, documentState.Id); } return builder.ToImmutable(); } private static IEnumerable<TextDocumentState> GetDocumentStates(ProjectState projectState) => projectState.DocumentStates.States.Values .Concat<TextDocumentState>(projectState.AdditionalDocumentStates.States.Values) .Concat(projectState.AnalyzerConfigDocumentStates.States.Values); /// <summary> /// Create a new solution instance without the project specified. /// </summary> public SolutionState RemoveProject(ProjectId projectId) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } CheckContainsProject(projectId); // changed project list so, increment version. var newSolutionAttributes = _solutionAttributes.With(version: this.Version.GetNewerVersion()); var newProjectIds = ProjectIds.ToImmutableArray().Remove(projectId); var newStateMap = _projectIdToProjectStateMap.Remove(projectId); // Remote supported languages only changes if the removed project is the last project of a supported language. var newLanguages = _remoteSupportedLanguages; if (_projectIdToProjectStateMap.TryGetValue(projectId, out var projectState) && RemoteSupportedLanguages.IsSupported(projectState.Language)) { var stillSupportsLanguage = false; foreach (var (id, state) in _projectIdToProjectStateMap) { if (id == projectId) continue; if (state.Language == projectState.Language) { stillSupportsLanguage = true; break; } } if (!stillSupportsLanguage) { newLanguages = newLanguages.Remove(projectState.Language); } } var newDependencyGraph = _dependencyGraph.WithProjectRemoved(projectId); var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph); var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithRemovedDocuments(GetDocumentStates(_projectIdToProjectStateMap[projectId])); return this.Branch( solutionAttributes: newSolutionAttributes, projectIds: newProjectIds, idToProjectStateMap: newStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newTrackerMap.Remove(projectId), filePathToDocumentIdsMap: newFilePathToDocumentIdsMap, dependencyGraph: newDependencyGraph); } private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithRemovedDocuments(IEnumerable<TextDocumentState> documentStates) { var builder = _filePathToDocumentIdsMap.ToBuilder(); foreach (var documentState in documentStates) { var filePath = documentState.FilePath; if (RoslynString.IsNullOrEmpty(filePath)) { continue; } if (!builder.TryGetValue(filePath, out var documentIdsWithPath) || !documentIdsWithPath.Contains(documentState.Id)) { throw new ArgumentException($"The given documentId was not found in '{nameof(_filePathToDocumentIdsMap)}'."); } builder.MultiRemove(filePath, documentState.Id); } return builder.ToImmutable(); } private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithFilePath(DocumentId documentId, string? oldFilePath, string? newFilePath) { if (oldFilePath == newFilePath) { return _filePathToDocumentIdsMap; } var builder = _filePathToDocumentIdsMap.ToBuilder(); if (!RoslynString.IsNullOrEmpty(oldFilePath)) { builder.MultiRemove(oldFilePath, documentId); } if (!RoslynString.IsNullOrEmpty(newFilePath)) { builder.MultiAdd(newFilePath, documentId); } return builder.ToImmutable(); } /// <summary> /// Creates a new solution instance with the project specified updated to have the new /// assembly name. /// </summary> public SolutionState WithProjectAssemblyName(ProjectId projectId, string assemblyName) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithAssemblyName(assemblyName); if (oldProject == newProject) { return this; } return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectAssemblyNameAction(assemblyName)); } /// <summary> /// Creates a new solution instance with the project specified updated to have the output file path. /// </summary> public SolutionState WithProjectOutputFilePath(ProjectId projectId, string? outputFilePath) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithOutputFilePath(outputFilePath); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the output file path. /// </summary> public SolutionState WithProjectOutputRefFilePath(ProjectId projectId, string? outputRefFilePath) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithOutputRefFilePath(outputRefFilePath); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the compiler output file path. /// </summary> public SolutionState WithProjectCompilationOutputInfo(ProjectId projectId, in CompilationOutputInfo info) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithCompilationOutputInfo(info); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the default namespace. /// </summary> public SolutionState WithProjectDefaultNamespace(ProjectId projectId, string? defaultNamespace) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithDefaultNamespace(defaultNamespace); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the name. /// </summary> public SolutionState WithProjectName(ProjectId projectId, string name) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithName(name); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the project file path. /// </summary> public SolutionState WithProjectFilePath(ProjectId projectId, string? filePath) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithFilePath(filePath); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified compilation options. /// </summary> public SolutionState WithProjectCompilationOptions(ProjectId projectId, CompilationOptions options) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithCompilationOptions(options); if (oldProject == newProject) { return this; } return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: false)); } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified parse options. /// </summary> public SolutionState WithProjectParseOptions(ProjectId projectId, ParseOptions options) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithParseOptions(options); if (oldProject == newProject) { return this; } if (Workspace.PartialSemanticsEnabled) { // don't fork tracker with queued action since access via partial semantics can become inconsistent (throw). // Since changing options is rare event, it is okay to start compilation building from scratch. return ForkProject(newProject, forkTracker: false); } else { return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ReplaceAllSyntaxTreesAction(newProject, isParseOptionChange: true)); } } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified hasAllInformation. /// </summary> public SolutionState WithHasAllInformation(ProjectId projectId, bool hasAllInformation) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithHasAllInformation(hasAllInformation); if (oldProject == newProject) { return this; } // fork without any change on compilation. return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified runAnalyzers. /// </summary> public SolutionState WithRunAnalyzers(ProjectId projectId, bool runAnalyzers) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithRunAnalyzers(runAnalyzers); if (oldProject == newProject) { return this; } // fork without any change on compilation. return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to include /// the specified project references. /// </summary> public SolutionState AddProjectReferences(ProjectId projectId, IReadOnlyCollection<ProjectReference> projectReferences) { if (projectReferences.Count == 0) { return this; } var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.ProjectReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(projectReferences); var newProject = oldProject.WithProjectReferences(newReferences); var newDependencyGraph = _dependencyGraph.WithAdditionalProjectReferences(projectId, projectReferences); return ForkProject(newProject, newDependencyGraph: newDependencyGraph); } /// <summary> /// Create a new solution instance with the project specified updated to no longer /// include the specified project reference. /// </summary> public SolutionState RemoveProjectReference(ProjectId projectId, ProjectReference projectReference) { var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.ProjectReferences.ToImmutableArray(); // Note: uses ProjectReference equality to compare references. var newReferences = oldReferences.Remove(projectReference); if (oldReferences == newReferences) { return this; } var newProject = oldProject.WithProjectReferences(newReferences); ProjectDependencyGraph newDependencyGraph; if (newProject.ContainsReferenceToProject(projectReference.ProjectId) || !_projectIdToProjectStateMap.ContainsKey(projectReference.ProjectId)) { // Two cases: // 1) The project contained multiple non-equivalent references to the project, // and not all of them were removed. The dependency graph doesn't change. // Note that there might be two references to the same project, one with // extern alias and the other without. These are not considered duplicates. // 2) The referenced project is not part of the solution and hence not included // in the dependency graph. newDependencyGraph = _dependencyGraph; } else { newDependencyGraph = _dependencyGraph.WithProjectReferenceRemoved(projectId, projectReference.ProjectId); } return ForkProject(newProject, newDependencyGraph: newDependencyGraph); } /// <summary> /// Create a new solution instance with the project specified updated to contain /// the specified list of project references. /// </summary> public SolutionState WithProjectReferences(ProjectId projectId, IReadOnlyList<ProjectReference> projectReferences) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithProjectReferences(projectReferences); if (oldProject == newProject) { return this; } var newDependencyGraph = _dependencyGraph.WithProjectReferences(projectId, projectReferences); return ForkProject(newProject, newDependencyGraph: newDependencyGraph); } /// <summary> /// Creates a new solution instance with the project documents in the order by the specified document ids. /// The specified document ids must be the same as what is already in the project; no adding or removing is allowed. /// </summary> public SolutionState WithProjectDocumentsOrder(ProjectId projectId, ImmutableList<DocumentId> documentIds) { var oldProject = GetRequiredProjectState(projectId); if (documentIds.Count != oldProject.DocumentStates.Count) { throw new ArgumentException($"The specified documents do not equal the project document count.", nameof(documentIds)); } foreach (var id in documentIds) { if (!oldProject.DocumentStates.Contains(id)) { throw new InvalidOperationException($"The document '{id}' does not exist in the project."); } } var newProject = oldProject.UpdateDocumentsOrder(documentIds); if (oldProject == newProject) { return this; } return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ReplaceAllSyntaxTreesAction(newProject, isParseOptionChange: false)); } /// <summary> /// Create a new solution instance with the project specified updated to include the /// specified metadata references. /// </summary> public SolutionState AddMetadataReferences(ProjectId projectId, IReadOnlyCollection<MetadataReference> metadataReferences) { if (metadataReferences.Count == 0) { return this; } var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.MetadataReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(metadataReferences); return ForkProject(oldProject.WithMetadataReferences(newReferences)); } /// <summary> /// Create a new solution instance with the project specified updated to no longer include /// the specified metadata reference. /// </summary> public SolutionState RemoveMetadataReference(ProjectId projectId, MetadataReference metadataReference) { var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.MetadataReferences.ToImmutableArray(); var newReferences = oldReferences.Remove(metadataReference); if (oldReferences == newReferences) { return this; } return ForkProject(oldProject.WithMetadataReferences(newReferences)); } /// <summary> /// Create a new solution instance with the project specified updated to include only the /// specified metadata references. /// </summary> public SolutionState WithProjectMetadataReferences(ProjectId projectId, IReadOnlyList<MetadataReference> metadataReferences) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithMetadataReferences(metadataReferences); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to include the /// specified analyzer references. /// </summary> public SolutionState AddAnalyzerReferences(ProjectId projectId, ImmutableArray<AnalyzerReference> analyzerReferences) { if (analyzerReferences.Length == 0) { return this; } var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(analyzerReferences); return ForkProject( oldProject.WithAnalyzerReferences(newReferences), new CompilationAndGeneratorDriverTranslationAction.AddAnalyzerReferencesAction(analyzerReferences, oldProject.Language)); } /// <summary> /// Create a new solution instance with the project specified updated to no longer include /// the specified analyzer reference. /// </summary> public SolutionState RemoveAnalyzerReference(ProjectId projectId, AnalyzerReference analyzerReference) { var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.Remove(analyzerReference); if (oldReferences == newReferences) { return this; } return ForkProject( oldProject.WithAnalyzerReferences(newReferences), new CompilationAndGeneratorDriverTranslationAction.RemoveAnalyzerReferencesAction(ImmutableArray.Create(analyzerReference), oldProject.Language)); } /// <summary> /// Create a new solution instance with the project specified updated to include only the /// specified analyzer references. /// </summary> public SolutionState WithProjectAnalyzerReferences(ProjectId projectId, IEnumerable<AnalyzerReference> analyzerReferences) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithAnalyzerReferences(analyzerReferences); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the corresponding projects updated to include new /// documents defined by the document info. /// </summary> public SolutionState AddDocuments(ImmutableArray<DocumentInfo> documentInfos) { return AddDocumentsToMultipleProjects(documentInfos, (documentInfo, project) => project.CreateDocument(documentInfo, project.ParseOptions), (oldProject, documents) => (oldProject.AddDocuments(documents), new CompilationAndGeneratorDriverTranslationAction.AddDocumentsAction(documents))); } /// <summary> /// Core helper that takes a set of <see cref="DocumentInfo" />s and does the application of the appropriate documents to each project. /// </summary> /// <param name="documentInfos">The set of documents to add.</param> /// <param name="addDocumentsToProjectState">Returns the new <see cref="ProjectState"/> with the documents added, and the <see cref="CompilationAndGeneratorDriverTranslationAction"/> needed as well.</param> /// <returns></returns> private SolutionState AddDocumentsToMultipleProjects<T>( ImmutableArray<DocumentInfo> documentInfos, Func<DocumentInfo, ProjectState, T> createDocumentState, Func<ProjectState, ImmutableArray<T>, (ProjectState newState, CompilationAndGeneratorDriverTranslationAction translationAction)> addDocumentsToProjectState) where T : TextDocumentState { if (documentInfos.IsDefault) { throw new ArgumentNullException(nameof(documentInfos)); } if (documentInfos.IsEmpty) { return this; } // The documents might be contributing to multiple different projects; split them by project and then we'll process // project-at-a-time. var documentInfosByProjectId = documentInfos.ToLookup(d => d.Id.ProjectId); var newSolutionState = this; foreach (var documentInfosInProject in documentInfosByProjectId) { CheckContainsProject(documentInfosInProject.Key); var oldProjectState = this.GetProjectState(documentInfosInProject.Key)!; var newDocumentStatesForProjectBuilder = ArrayBuilder<T>.GetInstance(); foreach (var documentInfo in documentInfosInProject) { newDocumentStatesForProjectBuilder.Add(createDocumentState(documentInfo, oldProjectState)); } var newDocumentStatesForProject = newDocumentStatesForProjectBuilder.ToImmutableAndFree(); var (newProjectState, compilationTranslationAction) = addDocumentsToProjectState(oldProjectState, newDocumentStatesForProject); newSolutionState = newSolutionState.ForkProject(newProjectState, compilationTranslationAction, newFilePathToDocumentIdsMap: CreateFilePathToDocumentIdsMapWithAddedDocuments(newDocumentStatesForProject)); } return newSolutionState; } public SolutionState AddAdditionalDocuments(ImmutableArray<DocumentInfo> documentInfos) { return AddDocumentsToMultipleProjects(documentInfos, (documentInfo, project) => new AdditionalDocumentState(documentInfo, _solutionServices), (projectState, documents) => (projectState.AddAdditionalDocuments(documents), new CompilationAndGeneratorDriverTranslationAction.AddAdditionalDocumentsAction(documents))); } public SolutionState AddAnalyzerConfigDocuments(ImmutableArray<DocumentInfo> documentInfos) { // Adding a new analyzer config potentially modifies the compilation options return AddDocumentsToMultipleProjects(documentInfos, (documentInfo, project) => new AnalyzerConfigDocumentState(documentInfo, _solutionServices), (oldProject, documents) => { var newProject = oldProject.AddAnalyzerConfigDocuments(documents); return (newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true)); }); } public SolutionState RemoveAnalyzerConfigDocuments(ImmutableArray<DocumentId> documentIds) { return RemoveDocumentsFromMultipleProjects(documentIds, (projectState, documentId) => projectState.AnalyzerConfigDocumentStates.GetRequiredState(documentId), (oldProject, documentIds, _) => { var newProject = oldProject.RemoveAnalyzerConfigDocuments(documentIds); return (newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true)); }); } /// <summary> /// Creates a new solution instance that no longer includes the specified document. /// </summary> public SolutionState RemoveDocuments(ImmutableArray<DocumentId> documentIds) { return RemoveDocumentsFromMultipleProjects(documentIds, (projectState, documentId) => projectState.DocumentStates.GetRequiredState(documentId), (projectState, documentIds, documentStates) => (projectState.RemoveDocuments(documentIds), new CompilationAndGeneratorDriverTranslationAction.RemoveDocumentsAction(documentStates))); } private SolutionState RemoveDocumentsFromMultipleProjects<T>( ImmutableArray<DocumentId> documentIds, Func<ProjectState, DocumentId, T> getExistingTextDocumentState, Func<ProjectState, ImmutableArray<DocumentId>, ImmutableArray<T>, (ProjectState newState, CompilationAndGeneratorDriverTranslationAction translationAction)> removeDocumentsFromProjectState) where T : TextDocumentState { if (documentIds.IsEmpty) { return this; } // The documents might be contributing to multiple different projects; split them by project and then we'll process // project-at-a-time. var documentIdsByProjectId = documentIds.ToLookup(id => id.ProjectId); var newSolutionState = this; foreach (var documentIdsInProject in documentIdsByProjectId) { var oldProjectState = this.GetProjectState(documentIdsInProject.Key); if (oldProjectState == null) { throw new InvalidOperationException(string.Format(WorkspacesResources._0_is_not_part_of_the_workspace, documentIdsInProject.Key)); } var removedDocumentStatesBuilder = ArrayBuilder<T>.GetInstance(); foreach (var documentId in documentIdsInProject) { removedDocumentStatesBuilder.Add(getExistingTextDocumentState(oldProjectState, documentId)); } var removedDocumentStatesForProject = removedDocumentStatesBuilder.ToImmutableAndFree(); var (newProjectState, compilationTranslationAction) = removeDocumentsFromProjectState(oldProjectState, documentIdsInProject.ToImmutableArray(), removedDocumentStatesForProject); newSolutionState = newSolutionState.ForkProject(newProjectState, compilationTranslationAction, newFilePathToDocumentIdsMap: CreateFilePathToDocumentIdsMapWithRemovedDocuments(removedDocumentStatesForProject)); } return newSolutionState; } /// <summary> /// Creates a new solution instance that no longer includes the specified additional documents. /// </summary> public SolutionState RemoveAdditionalDocuments(ImmutableArray<DocumentId> documentIds) { return RemoveDocumentsFromMultipleProjects(documentIds, (projectState, documentId) => projectState.AdditionalDocumentStates.GetRequiredState(documentId), (projectState, documentIds, documentStates) => (projectState.RemoveAdditionalDocuments(documentIds), new CompilationAndGeneratorDriverTranslationAction.RemoveAdditionalDocumentsAction(documentStates))); } /// <summary> /// Creates a new solution instance with the document specified updated to have the specified name. /// </summary> public SolutionState WithDocumentName(DocumentId documentId, string name) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.Attributes.Name == name) { return this; } return UpdateDocumentState(oldDocument.UpdateName(name)); } /// <summary> /// Creates a new solution instance with the document specified updated to be contained in /// the sequence of logical folders. /// </summary> public SolutionState WithDocumentFolders(DocumentId documentId, IReadOnlyList<string> folders) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.Folders.SequenceEqual(folders)) { return this; } return UpdateDocumentState(oldDocument.UpdateFolders(folders)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the specified file path. /// </summary> public SolutionState WithDocumentFilePath(DocumentId documentId, string? filePath) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.FilePath == filePath) { return this; } return UpdateDocumentState(oldDocument.UpdateFilePath(filePath)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the text /// specified. /// </summary> public SolutionState WithDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.TryGetText(out var oldText) && text == oldText) { return this; } return UpdateDocumentState(oldDocument.UpdateText(text, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the additional document specified updated to have the text /// specified. /// </summary> public SolutionState WithAdditionalDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAdditionalDocumentState(documentId); if (oldDocument.TryGetText(out var oldText) && text == oldText) { return this; } return UpdateAdditionalDocumentState(oldDocument.UpdateText(text, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the document specified updated to have the text /// specified. /// </summary> public SolutionState WithAnalyzerConfigDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId); if (oldDocument.TryGetText(out var oldText) && text == oldText) { return this; } return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(text, mode)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the text /// and version specified. /// </summary> public SolutionState WithDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion) { return this; } return UpdateDocumentState(oldDocument.UpdateText(textAndVersion, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the additional document specified updated to have the text /// and version specified. /// </summary> public SolutionState WithAdditionalDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAdditionalDocumentState(documentId); if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion) { return this; } return UpdateAdditionalDocumentState(oldDocument.UpdateText(textAndVersion, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the analyzer config document specified updated to have the text /// and version specified. /// </summary> public SolutionState WithAnalyzerConfigDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId); if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion) { return this; } return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(textAndVersion, mode)); } /// <summary> /// Creates a new solution instance with the document specified updated to have a syntax tree /// rooted by the specified syntax node. /// </summary> public SolutionState WithDocumentSyntaxRoot(DocumentId documentId, SyntaxNode root, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.TryGetSyntaxTree(out var oldTree) && oldTree.TryGetRoot(out var oldRoot) && oldRoot == root) { return this; } return UpdateDocumentState(oldDocument.UpdateTree(root, mode), textChanged: true); } private static async Task<Compilation> UpdateDocumentInCompilationAsync( Compilation compilation, DocumentState oldDocument, DocumentState newDocument, CancellationToken cancellationToken) { return compilation.ReplaceSyntaxTree( await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false), await newDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the source /// code kind specified. /// </summary> public SolutionState WithDocumentSourceCodeKind(DocumentId documentId, SourceCodeKind sourceCodeKind) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.SourceCodeKind == sourceCodeKind) { return this; } return UpdateDocumentState(oldDocument.UpdateSourceCodeKind(sourceCodeKind), textChanged: true); } public SolutionState UpdateDocumentTextLoader(DocumentId documentId, TextLoader loader, SourceText? text, PreservationMode mode) { var oldDocument = GetRequiredDocumentState(documentId); // Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with // old content. Also this should make sure we don't re-use latest doc version with data associated with opened document. return UpdateDocumentState(oldDocument.UpdateText(loader, text, mode), textChanged: true, recalculateDependentVersions: true); } /// <summary> /// Creates a new solution instance with the additional document specified updated to have the text /// supplied by the text loader. /// </summary> public SolutionState UpdateAdditionalDocumentTextLoader(DocumentId documentId, TextLoader loader, PreservationMode mode) { var oldDocument = GetRequiredAdditionalDocumentState(documentId); // Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with // old content. Also this should make sure we don't re-use latest doc version with data associated with opened document. return UpdateAdditionalDocumentState(oldDocument.UpdateText(loader, mode), textChanged: true, recalculateDependentVersions: true); } /// <summary> /// Creates a new solution instance with the analyzer config document specified updated to have the text /// supplied by the text loader. /// </summary> public SolutionState UpdateAnalyzerConfigDocumentTextLoader(DocumentId documentId, TextLoader loader, PreservationMode mode) { var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId); // Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with // old content. Also this should make sure we don't re-use latest doc version with data associated with opened document. return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(loader, mode)); } private SolutionState UpdateDocumentState(DocumentState newDocument, bool textChanged = false, bool recalculateDependentVersions = false) { var oldProject = GetProjectState(newDocument.Id.ProjectId)!; var newProject = oldProject.UpdateDocument(newDocument, textChanged, recalculateDependentVersions); // This method shouldn't have been called if the document has not changed. Debug.Assert(oldProject != newProject); var oldDocument = oldProject.DocumentStates.GetRequiredState(newDocument.Id); var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithFilePath(newDocument.Id, oldDocument.FilePath, newDocument.FilePath); return ForkProject( newProject, new CompilationAndGeneratorDriverTranslationAction.TouchDocumentAction(oldDocument, newDocument), newFilePathToDocumentIdsMap: newFilePathToDocumentIdsMap); } private SolutionState UpdateAdditionalDocumentState(AdditionalDocumentState newDocument, bool textChanged = false, bool recalculateDependentVersions = false) { var oldProject = GetProjectState(newDocument.Id.ProjectId)!; var newProject = oldProject.UpdateAdditionalDocument(newDocument, textChanged, recalculateDependentVersions); // This method shouldn't have been called if the document has not changed. Debug.Assert(oldProject != newProject); var oldDocument = oldProject.AdditionalDocumentStates.GetRequiredState(newDocument.Id); return ForkProject( newProject, translate: new CompilationAndGeneratorDriverTranslationAction.TouchAdditionalDocumentAction(oldDocument, newDocument)); } private SolutionState UpdateAnalyzerConfigDocumentState(AnalyzerConfigDocumentState newDocument) { var oldProject = GetProjectState(newDocument.Id.ProjectId)!; var newProject = oldProject.UpdateAnalyzerConfigDocument(newDocument); // This method shouldn't have been called if the document has not changed. Debug.Assert(oldProject != newProject); return ForkProject(newProject, newProject.CompilationOptions != null ? new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true) : null); } /// <summary> /// Creates a new snapshot with an updated project and an action that will produce a new /// compilation matching the new project out of an old compilation. All dependent projects /// are fixed-up if the change to the new project affects its public metadata, and old /// dependent compilations are forgotten. /// </summary> private SolutionState ForkProject( ProjectState newProjectState, CompilationAndGeneratorDriverTranslationAction? translate = null, ProjectDependencyGraph? newDependencyGraph = null, ImmutableDictionary<string, ImmutableArray<DocumentId>>? newFilePathToDocumentIdsMap = null, bool forkTracker = true) { var projectId = newProjectState.Id; var newStateMap = _projectIdToProjectStateMap.SetItem(projectId, newProjectState); // Remote supported languages can only change if the project changes language. This is an unexpected edge // case, so it's not optimized for incremental updates. var newLanguages = !_projectIdToProjectStateMap.TryGetValue(projectId, out var projectState) || projectState.Language != newProjectState.Language ? GetRemoteSupportedProjectLanguages(newStateMap) : _remoteSupportedLanguages; newDependencyGraph ??= _dependencyGraph; var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph); // If we have a tracker for this project, then fork it as well (along with the // translation action and store it in the tracker map. if (newTrackerMap.TryGetValue(projectId, out var tracker)) { newTrackerMap = newTrackerMap.Remove(projectId); if (forkTracker) { newTrackerMap = newTrackerMap.Add(projectId, tracker.Fork(newProjectState, translate)); } } return this.Branch( idToProjectStateMap: newStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newTrackerMap, dependencyGraph: newDependencyGraph, filePathToDocumentIdsMap: newFilePathToDocumentIdsMap ?? _filePathToDocumentIdsMap); } /// <summary> /// Gets the set of <see cref="DocumentId"/>s in this <see cref="Solution"/> with a /// <see cref="TextDocument.FilePath"/> that matches the given file path. /// </summary> public ImmutableArray<DocumentId> GetDocumentIdsWithFilePath(string? filePath) { if (string.IsNullOrEmpty(filePath)) { return ImmutableArray<DocumentId>.Empty; } return _filePathToDocumentIdsMap.TryGetValue(filePath!, out var documentIds) ? documentIds : ImmutableArray<DocumentId>.Empty; } private static ProjectDependencyGraph CreateDependencyGraph( IReadOnlyList<ProjectId> projectIds, ImmutableDictionary<ProjectId, ProjectState> projectStates) { var map = projectStates.Values.Select(state => new KeyValuePair<ProjectId, ImmutableHashSet<ProjectId>>( state.Id, state.ProjectReferences.Where(pr => projectStates.ContainsKey(pr.ProjectId)).Select(pr => pr.ProjectId).ToImmutableHashSet())) .ToImmutableDictionary(); return new ProjectDependencyGraph(projectIds.ToImmutableHashSet(), map); } private ImmutableDictionary<ProjectId, ICompilationTracker> CreateCompilationTrackerMap(ProjectId changedProjectId, ProjectDependencyGraph dependencyGraph) { var builder = ImmutableDictionary.CreateBuilder<ProjectId, ICompilationTracker>(); IEnumerable<ProjectId>? dependencies = null; foreach (var (id, tracker) in _projectIdToTrackerMap) builder.Add(id, CanReuse(id) ? tracker : tracker.Fork(tracker.ProjectState)); return builder.ToImmutable(); // Returns true if 'tracker' can be reused for project 'id' bool CanReuse(ProjectId id) { if (id == changedProjectId) { return true; } // Check the dependency graph to see if project 'id' directly or transitively depends on 'projectId'. // If the information is not available, do not compute it. var forwardDependencies = dependencyGraph.TryGetProjectsThatThisProjectTransitivelyDependsOn(id); if (forwardDependencies is object && !forwardDependencies.Contains(changedProjectId)) { return true; } // Compute the set of all projects that depend on 'projectId'. This information answers the same // question as the previous check, but involves at most one transitive computation within the // dependency graph. dependencies ??= dependencyGraph.GetProjectsThatTransitivelyDependOnThisProject(changedProjectId); return !dependencies.Contains(id); } } public SolutionState WithOptions(SerializableOptionSet options) => Branch(options: options); public SolutionState AddAnalyzerReferences(IReadOnlyCollection<AnalyzerReference> analyzerReferences) { if (analyzerReferences.Count == 0) { return this; } var oldReferences = AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(analyzerReferences); return Branch(analyzerReferences: newReferences); } public SolutionState RemoveAnalyzerReference(AnalyzerReference analyzerReference) { var oldReferences = AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.Remove(analyzerReference); if (oldReferences == newReferences) { return this; } return Branch(analyzerReferences: newReferences); } public SolutionState WithAnalyzerReferences(IReadOnlyList<AnalyzerReference> analyzerReferences) { if (analyzerReferences == AnalyzerReferences) { return this; } return Branch(analyzerReferences: analyzerReferences); } // this lock guards all the mutable fields (do not share lock with derived classes) private NonReentrantLock? _stateLockBackingField; private NonReentrantLock StateLock { get { // TODO: why did I need to do a nullable suppression here? return LazyInitializer.EnsureInitialized(ref _stateLockBackingField, NonReentrantLock.Factory)!; } } private WeakReference<SolutionState>? _latestSolutionWithPartialCompilation; private DateTime _timeOfLatestSolutionWithPartialCompilation; private DocumentId? _documentIdOfLatestSolutionWithPartialCompilation; /// <summary> /// Creates a branch of the solution that has its compilations frozen in whatever state they are in at the time, assuming a background compiler is /// busy building this compilations. /// /// A compilation for the project containing the specified document id will be guaranteed to exist with at least the syntax tree for the document. /// /// This not intended to be the public API, use Document.WithFrozenPartialSemantics() instead. /// </summary> public SolutionState WithFrozenPartialCompilationIncludingSpecificDocument(DocumentId documentId, CancellationToken cancellationToken) { try { var doc = this.GetRequiredDocumentState(documentId); var tree = doc.GetSyntaxTree(cancellationToken); using (this.StateLock.DisposableWait(cancellationToken)) { // in progress solutions are disabled for some testing if (this.Workspace is Workspace ws && ws.TestHookPartialSolutionsDisabled) { return this; } SolutionState? currentPartialSolution = null; if (_latestSolutionWithPartialCompilation != null) { _latestSolutionWithPartialCompilation.TryGetTarget(out currentPartialSolution); } var reuseExistingPartialSolution = currentPartialSolution != null && (DateTime.UtcNow - _timeOfLatestSolutionWithPartialCompilation).TotalSeconds < 0.1 && _documentIdOfLatestSolutionWithPartialCompilation == documentId; if (reuseExistingPartialSolution) { SolutionLogger.UseExistingPartialSolution(); return currentPartialSolution!; } // if we don't have one or it is stale, create a new partial solution var tracker = this.GetCompilationTracker(documentId.ProjectId); var newTracker = tracker.FreezePartialStateWithTree(this, doc, tree, cancellationToken); var newIdToProjectStateMap = _projectIdToProjectStateMap.SetItem(documentId.ProjectId, newTracker.ProjectState); var newLanguages = _remoteSupportedLanguages; var newIdToTrackerMap = _projectIdToTrackerMap.SetItem(documentId.ProjectId, newTracker); currentPartialSolution = this.Branch( idToProjectStateMap: newIdToProjectStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newIdToTrackerMap, dependencyGraph: CreateDependencyGraph(ProjectIds, newIdToProjectStateMap)); _latestSolutionWithPartialCompilation = new WeakReference<SolutionState>(currentPartialSolution); _timeOfLatestSolutionWithPartialCompilation = DateTime.UtcNow; _documentIdOfLatestSolutionWithPartialCompilation = documentId; SolutionLogger.CreatePartialSolution(); return currentPartialSolution; } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Creates a new solution instance with all the documents specified updated to have the same specified text. /// </summary> public SolutionState WithDocumentText(IEnumerable<DocumentId?> documentIds, SourceText text, PreservationMode mode) { var solution = this; foreach (var documentId in documentIds) { if (documentId == null) { continue; } var doc = GetProjectState(documentId.ProjectId)?.DocumentStates.GetState(documentId); if (doc != null) { if (!doc.TryGetText(out var existingText) || existingText != text) { solution = solution.WithDocumentText(documentId, text, mode); } } } return solution; } public bool TryGetCompilation(ProjectId projectId, [NotNullWhen(returnValue: true)] out Compilation? compilation) { CheckContainsProject(projectId); compilation = null; return this.TryGetCompilationTracker(projectId, out var tracker) && tracker.TryGetCompilation(out compilation); } /// <summary> /// Returns the compilation for the specified <see cref="ProjectId"/>. Can return <see langword="null"/> when the project /// does not support compilations. /// </summary> /// <remarks> /// The compilation is guaranteed to have a syntax tree for each document of the project. /// </remarks> private Task<Compilation?> GetCompilationAsync(ProjectId projectId, CancellationToken cancellationToken) { // TODO: figure out where this is called and why the nullable suppression is required return GetCompilationAsync(GetProjectState(projectId)!, cancellationToken); } /// <summary> /// Returns the compilation for the specified <see cref="ProjectState"/>. Can return <see langword="null"/> when the project /// does not support compilations. /// </summary> /// <remarks> /// The compilation is guaranteed to have a syntax tree for each document of the project. /// </remarks> public Task<Compilation?> GetCompilationAsync(ProjectState project, CancellationToken cancellationToken) { return project.SupportsCompilation ? GetCompilationTracker(project.Id).GetCompilationAsync(this, cancellationToken).AsNullable() : SpecializedTasks.Null<Compilation>(); } /// <summary> /// Return reference completeness for the given project and all projects this references. /// </summary> public Task<bool> HasSuccessfullyLoadedAsync(ProjectState project, CancellationToken cancellationToken) { // return HasAllInformation when compilation is not supported. // regardless whether project support compilation or not, if projectInfo is not complete, we can't guarantee its reference completeness return project.SupportsCompilation ? this.GetCompilationTracker(project.Id).HasSuccessfullyLoadedAsync(this, cancellationToken) : project.HasAllInformation ? SpecializedTasks.True : SpecializedTasks.False; } /// <summary> /// Returns the generated document states for source generated documents. /// </summary> public ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(ProjectState project, CancellationToken cancellationToken) { return project.SupportsCompilation ? GetCompilationTracker(project.Id).GetSourceGeneratedDocumentStatesAsync(this, cancellationToken) : new(TextDocumentStates<SourceGeneratedDocumentState>.Empty); } /// <summary> /// Returns the <see cref="SourceGeneratedDocumentState"/> for a source generated document that has already been generated and observed. /// </summary> /// <remarks> /// This is only safe to call if you already have seen the SyntaxTree or equivalent that indicates the document state has already been /// generated. This method exists to implement <see cref="Solution.GetDocument(SyntaxTree?)"/> and is best avoided unless you're doing something /// similarly tricky like that. /// </remarks> public SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId) { return GetCompilationTracker(documentId.ProjectId).TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentId); } /// <summary> /// Returns a new SolutionState that will always produce a specific output for a generated file. This is used only in the /// implementation of <see cref="TextExtensions.GetOpenDocumentInCurrentContextWithChanges"/> where if a user has a source /// generated file open, we need to make sure everything lines up. /// </summary> public SolutionState WithFrozenSourceGeneratedDocument(SourceGeneratedDocumentIdentity documentIdentity, SourceText sourceText) { // We won't support freezing multiple source generated documents at once. Although nothing in the implementation // of this method would have problems, this simplifies the handling of serializing this solution to out-of-proc. // Since we only produce these snapshots from an open document, there should be no way to observe this, so this assertion // also serves as a good check on the system. If down the road we need to support this, we can remove this check and // update the out-of-process serialization logic accordingly. Contract.ThrowIfTrue(_frozenSourceGeneratedDocumentState != null, "We shouldn't be calling WithFrozenSourceGeneratedDocument on a solution with a frozen source generated document."); var existingGeneratedState = TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentIdentity.DocumentId); SourceGeneratedDocumentState newGeneratedState; if (existingGeneratedState != null) { newGeneratedState = existingGeneratedState.WithUpdatedGeneratedContent(sourceText, existingGeneratedState.ParseOptions); // If the content already matched, we can just reuse the existing state if (newGeneratedState == existingGeneratedState) { return this; } } else { var projectState = GetRequiredProjectState(documentIdentity.DocumentId.ProjectId); newGeneratedState = SourceGeneratedDocumentState.Create( documentIdentity, sourceText, projectState.ParseOptions!, projectState.LanguageServices, _solutionServices); } var projectId = documentIdentity.DocumentId.ProjectId; var newTrackerMap = CreateCompilationTrackerMap(projectId, _dependencyGraph); // We want to create a new snapshot with a new compilation tracker that will do this replacement. // If we already have an existing tracker we'll just wrap that (so we also are reusing any underlying // computations). If we don't have one, we'll create one and then wrap it. if (!newTrackerMap.TryGetValue(projectId, out var existingTracker)) { existingTracker = CreateCompilationTracker(projectId, this); } newTrackerMap = newTrackerMap.SetItem( projectId, new GeneratedFileReplacingCompilationTracker(existingTracker, newGeneratedState)); return this.Branch( projectIdToTrackerMap: newTrackerMap, frozenSourceGeneratedDocument: newGeneratedState); } /// <summary> /// Symbols need to be either <see cref="IAssemblySymbol"/> or <see cref="IModuleSymbol"/>. /// </summary> private static readonly ConditionalWeakTable<ISymbol, ProjectId> s_assemblyOrModuleSymbolToProjectMap = new(); /// <summary> /// Get a metadata reference for the project's compilation /// </summary> public Task<MetadataReference> GetMetadataReferenceAsync(ProjectReference projectReference, ProjectState fromProject, CancellationToken cancellationToken) { try { // Get the compilation state for this project. If it's not already created, then this // will create it. Then force that state to completion and get a metadata reference to it. var tracker = this.GetCompilationTracker(projectReference.ProjectId); return tracker.GetMetadataReferenceAsync(this, fromProject, projectReference, cancellationToken); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Attempt to get the best readily available compilation for the project. It may be a /// partially built compilation. /// </summary> private MetadataReference? GetPartialMetadataReference( ProjectReference projectReference, ProjectState fromProject) { // Try to get the compilation state for this project. If it doesn't exist, don't do any // more work. if (!_projectIdToTrackerMap.TryGetValue(projectReference.ProjectId, out var state)) { return null; } return state.GetPartialMetadataReference(fromProject, projectReference); } public async Task<bool> ContainsSymbolsWithNameAsync(ProjectId id, string name, SymbolFilter filter, CancellationToken cancellationToken) { var result = GetCompilationTracker(id).ContainsSymbolsWithNameFromDeclarationOnlyCompilation(name, filter, cancellationToken); if (result.HasValue) { return result.Value; } // it looks like declaration compilation doesn't exist yet. we have to build full compilation var compilation = await GetCompilationAsync(id, cancellationToken).ConfigureAwait(false); if (compilation == null) { // some projects don't support compilations (e.g., TypeScript) so there's nothing to check return false; } return compilation.ContainsSymbolsWithName(name, filter, cancellationToken); } public async Task<bool> ContainsSymbolsWithNameAsync(ProjectId id, Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken) { var result = GetCompilationTracker(id).ContainsSymbolsWithNameFromDeclarationOnlyCompilation(predicate, filter, cancellationToken); if (result.HasValue) { return result.Value; } // it looks like declaration compilation doesn't exist yet. we have to build full compilation var compilation = await GetCompilationAsync(id, cancellationToken).ConfigureAwait(false); if (compilation == null) { // some projects don't support compilations (e.g., TypeScript) so there's nothing to check return false; } return compilation.ContainsSymbolsWithName(predicate, filter, cancellationToken); } /// <summary> /// Gets a <see cref="ProjectDependencyGraph"/> that details the dependencies between projects for this solution. /// </summary> public ProjectDependencyGraph GetProjectDependencyGraph() => _dependencyGraph; private void CheckNotContainsProject(ProjectId projectId) { if (this.ContainsProject(projectId)) { throw new InvalidOperationException(WorkspacesResources.The_solution_already_contains_the_specified_project); } } private void CheckContainsProject(ProjectId projectId) { if (!this.ContainsProject(projectId)) { throw new InvalidOperationException(WorkspacesResources.The_solution_does_not_contain_the_specified_project); } } internal bool ContainsProjectReference(ProjectId projectId, ProjectReference projectReference) => GetRequiredProjectState(projectId).ProjectReferences.Contains(projectReference); internal bool ContainsMetadataReference(ProjectId projectId, MetadataReference metadataReference) => GetRequiredProjectState(projectId).MetadataReferences.Contains(metadataReference); internal bool ContainsAnalyzerReference(ProjectId projectId, AnalyzerReference analyzerReference) => GetRequiredProjectState(projectId).AnalyzerReferences.Contains(analyzerReference); internal bool ContainsTransitiveReference(ProjectId fromProjectId, ProjectId toProjectId) => _dependencyGraph.GetProjectsThatThisProjectTransitivelyDependsOn(fromProjectId).Contains(toProjectId); internal ImmutableHashSet<string> GetRemoteSupportedProjectLanguages() => _remoteSupportedLanguages; private static ImmutableHashSet<string> GetRemoteSupportedProjectLanguages(ImmutableDictionary<ProjectId, ProjectState> projectStates) { var builder = ImmutableHashSet.CreateBuilder<string>(); foreach (var projectState in projectStates) { if (RemoteSupportedLanguages.IsSupported(projectState.Value.Language)) { builder.Add(projectState.Value.Language); } } return builder.ToImmutable(); } } }
1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/EditorFeatures/Core/Extensibility/BraceMatching/ExportBraceMatcherAttribute.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; namespace Microsoft.CodeAnalysis.Editor { [MetadataAttribute] [AttributeUsage(AttributeTargets.Class)] internal class ExportBraceMatcherAttribute : ExportAttribute { public string Language { get; } public ExportBraceMatcherAttribute(string language) : base(typeof(IBraceMatcher)) { this.Language = language ?? throw new ArgumentNullException(nameof(language)); } } }
// Licensed to the .NET Foundation under one or more 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; namespace Microsoft.CodeAnalysis.Editor { [MetadataAttribute] [AttributeUsage(AttributeTargets.Class)] internal class ExportBraceMatcherAttribute : ExportAttribute { public string Language { get; } public ExportBraceMatcherAttribute(string language) : base(typeof(IBraceMatcher)) { this.Language = language ?? throw new ArgumentNullException(nameof(language)); } } }
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioWorkspaceImpl.AddDocumentUndoUnit.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; using Microsoft.CodeAnalysis.Text; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal partial class VisualStudioWorkspaceImpl { private class AddDocumentUndoUnit : AbstractAddDocumentUndoUnit { public AddDocumentUndoUnit( VisualStudioWorkspaceImpl workspace, DocumentInfo docInfo, SourceText text) : base(workspace, docInfo, text) { } protected override Project AddDocument(Project fromProject) => fromProject.AddDocument(DocumentInfo.Name, Text, DocumentInfo.Folders, DocumentInfo.FilePath).Project; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal partial class VisualStudioWorkspaceImpl { private class AddDocumentUndoUnit : AbstractAddDocumentUndoUnit { public AddDocumentUndoUnit( VisualStudioWorkspaceImpl workspace, DocumentInfo docInfo, SourceText text) : base(workspace, docInfo, text) { } protected override Project AddDocument(Project fromProject) => fromProject.AddDocument(DocumentInfo.Name, Text, DocumentInfo.Folders, DocumentInfo.FilePath).Project; } } }
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/VisualStudio/Core/Def/EditorConfigSettings/IWpfSettingsEditorViewModel.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.Editor; using Microsoft.VisualStudio.Shell.TableControl; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings { internal interface IWpfSettingsEditorViewModel : ISettingsEditorViewModel { IWpfTableControl4 GetTableControl(); void 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. using Microsoft.CodeAnalysis.Editor; using Microsoft.VisualStudio.Shell.TableControl; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings { internal interface IWpfSettingsEditorViewModel : ISettingsEditorViewModel { IWpfTableControl4 GetTableControl(); void ShutDown(); } }
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/EditorFeatures/CSharp/EventHookup/EventHookupCommandHandler_TabKeyCommand.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 System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.EventHookup { internal partial class EventHookupCommandHandler : IChainedCommandHandler<TabKeyCommandArgs> { public void ExecuteCommand(TabKeyCommandArgs args, Action nextHandler, CommandExecutionContext context) { AssertIsForeground(); if (!args.SubjectBuffer.GetFeatureOnOffOption(InternalFeatureOnOffOptions.EventHookup)) { nextHandler(); return; } if (EventHookupSessionManager.CurrentSession == null) { nextHandler(); return; } // Handling tab is currently uncancellable. HandleTabWorker(args.TextView, args.SubjectBuffer, nextHandler, CancellationToken.None); } public CommandState GetCommandState(TabKeyCommandArgs args, Func<CommandState> nextHandler) { AssertIsForeground(); if (EventHookupSessionManager.CurrentSession != null) { return CommandState.Available; } else { return nextHandler(); } } private void HandleTabWorker(ITextView textView, ITextBuffer subjectBuffer, Action nextHandler, CancellationToken cancellationToken) { AssertIsForeground(); // For test purposes only! if (EventHookupSessionManager.CurrentSession.TESTSessionHookupMutex != null) { try { EventHookupSessionManager.CurrentSession.TESTSessionHookupMutex.ReleaseMutex(); } catch (ApplicationException) { } } // Blocking wait (if necessary) to determine whether to consume the tab and // generate the event handler. EventHookupSessionManager.CurrentSession.GetEventNameTask.Wait(cancellationToken); string eventHandlerMethodName = null; if (EventHookupSessionManager.CurrentSession.GetEventNameTask.Status == TaskStatus.RanToCompletion) { eventHandlerMethodName = EventHookupSessionManager.CurrentSession.GetEventNameTask.WaitAndGetResult(cancellationToken); } if (eventHandlerMethodName == null || EventHookupSessionManager.CurrentSession.TextView != textView) { nextHandler(); EventHookupSessionManager.CancelAndDismissExistingSessions(); return; } // This tab means we should generate the event handler method. Begin the code // generation process. GenerateAndAddEventHandler(textView, subjectBuffer, eventHandlerMethodName, nextHandler, cancellationToken); } private void GenerateAndAddEventHandler(ITextView textView, ITextBuffer subjectBuffer, string eventHandlerMethodName, Action nextHandler, CancellationToken cancellationToken) { AssertIsForeground(); using (Logger.LogBlock(FunctionId.EventHookup_Generate_Handler, cancellationToken)) { EventHookupSessionManager.CancelAndDismissExistingSessions(); var workspace = textView.TextSnapshot.TextBuffer.GetWorkspace(); if (workspace == null) { nextHandler(); EventHookupSessionManager.CancelAndDismissExistingSessions(); return; } var document = textView.TextSnapshot.GetOpenDocumentInCurrentContextWithChanges(); Contract.ThrowIfNull(document, "Event Hookup could not find the document for the IBufferView."); var position = textView.GetCaretPoint(subjectBuffer).Value.Position; var solutionWithEventHandler = CreateSolutionWithEventHandler( document, eventHandlerMethodName, position, out var plusEqualTokenEndPosition, cancellationToken); Contract.ThrowIfNull(solutionWithEventHandler, "Event Hookup could not create solution with event handler."); // The new solution is created, so start user observable changes Contract.ThrowIfFalse(workspace.TryApplyChanges(solutionWithEventHandler), "Event Hookup could not update the solution."); // The += token will not move during this process, so it is safe to use that // position as a location from which to find the identifier we're renaming. BeginInlineRename(textView, plusEqualTokenEndPosition, cancellationToken); } } private Solution CreateSolutionWithEventHandler( Document document, string eventHandlerMethodName, int position, out int plusEqualTokenEndPosition, CancellationToken cancellationToken) { AssertIsForeground(); // Mark the += token with an annotation so we can find it after formatting var plusEqualsTokenAnnotation = new SyntaxAnnotation(); var documentWithNameAndAnnotationsAdded = AddMethodNameAndAnnotationsToSolution(document, eventHandlerMethodName, position, plusEqualsTokenAnnotation, cancellationToken); var semanticDocument = SemanticDocument.CreateAsync(documentWithNameAndAnnotationsAdded, cancellationToken).WaitAndGetResult(cancellationToken); var updatedRoot = AddGeneratedHandlerMethodToSolution(semanticDocument, eventHandlerMethodName, plusEqualsTokenAnnotation, cancellationToken); if (updatedRoot == null) { plusEqualTokenEndPosition = 0; return null; } var simplifiedDocument = Simplifier.ReduceAsync(documentWithNameAndAnnotationsAdded.WithSyntaxRoot(updatedRoot), Simplifier.Annotation, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken); var formattedDocument = Formatter.FormatAsync(simplifiedDocument, Formatter.Annotation, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken); var newRoot = formattedDocument.GetSyntaxRootSynchronously(cancellationToken); plusEqualTokenEndPosition = newRoot.GetAnnotatedNodesAndTokens(plusEqualsTokenAnnotation) .Single().Span.End; return document.Project.Solution.WithDocumentText( formattedDocument.Id, formattedDocument.GetTextSynchronously(cancellationToken)); } private static Document AddMethodNameAndAnnotationsToSolution( Document document, string eventHandlerMethodName, int position, SyntaxAnnotation plusEqualsTokenAnnotation, CancellationToken cancellationToken) { // First find the event hookup to determine if we are in a static context. var root = document.GetSyntaxRootSynchronously(cancellationToken); var plusEqualsToken = root.FindTokenOnLeftOfPosition(position); var eventHookupExpression = plusEqualsToken.GetAncestor<AssignmentExpressionSyntax>(); var textToInsert = eventHandlerMethodName + ";"; if (!eventHookupExpression.IsInStaticContext()) { // This will be simplified later if it's not needed. textToInsert = "this." + textToInsert; } // Next, perform a textual insertion of the event handler method name. var textChange = new TextChange(new TextSpan(position, 0), textToInsert); var newText = document.GetTextSynchronously(cancellationToken).WithChanges(textChange); var documentWithNameAdded = document.WithText(newText); // Now find the event hookup again to add the appropriate annotations. root = documentWithNameAdded.GetSyntaxRootSynchronously(cancellationToken); plusEqualsToken = root.FindTokenOnLeftOfPosition(position); eventHookupExpression = plusEqualsToken.GetAncestor<AssignmentExpressionSyntax>(); var updatedEventHookupExpression = eventHookupExpression .ReplaceToken(plusEqualsToken, plusEqualsToken.WithAdditionalAnnotations(plusEqualsTokenAnnotation)) .WithRight(eventHookupExpression.Right.WithAdditionalAnnotations(Simplifier.Annotation)) .WithAdditionalAnnotations(Formatter.Annotation); var rootWithUpdatedEventHookupExpression = root.ReplaceNode(eventHookupExpression, updatedEventHookupExpression); return documentWithNameAdded.WithSyntaxRoot(rootWithUpdatedEventHookupExpression); } private static SyntaxNode AddGeneratedHandlerMethodToSolution( SemanticDocument document, string eventHandlerMethodName, SyntaxAnnotation plusEqualsTokenAnnotation, CancellationToken cancellationToken) { var root = document.Root as SyntaxNode; var eventHookupExpression = root.GetAnnotatedNodesAndTokens(plusEqualsTokenAnnotation).Single().AsToken().GetAncestor<AssignmentExpressionSyntax>(); var generatedMethodSymbol = GetMethodSymbol(document, eventHandlerMethodName, eventHookupExpression, cancellationToken); if (generatedMethodSymbol == null) { return null; } var typeDecl = eventHookupExpression.GetAncestor<TypeDeclarationSyntax>(); var typeDeclWithMethodAdded = CodeGenerator.AddMethodDeclaration(typeDecl, generatedMethodSymbol, document.Project.Solution.Workspace, new CodeGenerationOptions(afterThisLocation: eventHookupExpression.GetLocation())); return root.ReplaceNode(typeDecl, typeDeclWithMethodAdded); } private static IMethodSymbol GetMethodSymbol( SemanticDocument semanticDocument, string eventHandlerMethodName, AssignmentExpressionSyntax eventHookupExpression, CancellationToken cancellationToken) { var semanticModel = semanticDocument.SemanticModel as SemanticModel; var symbolInfo = semanticModel.GetSymbolInfo(eventHookupExpression.Left, cancellationToken); var symbol = symbolInfo.Symbol; if (symbol == null || symbol.Kind != SymbolKind.Event) { return null; } var typeInference = semanticDocument.Document.GetLanguageService<ITypeInferenceService>(); var delegateType = typeInference.InferDelegateType(semanticModel, eventHookupExpression.Right, cancellationToken); if (delegateType == null || delegateType.DelegateInvokeMethod == null) { return null; } var syntaxFactory = semanticDocument.Document.GetLanguageService<SyntaxGenerator>(); var delegateInvokeMethod = delegateType.DelegateInvokeMethod.RemoveInaccessibleAttributesAndAttributesOfTypes(semanticDocument.SemanticModel.Compilation.Assembly); return CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: default, accessibility: Accessibility.Private, modifiers: new DeclarationModifiers(isStatic: eventHookupExpression.IsInStaticContext()), returnType: delegateInvokeMethod.ReturnType, refKind: delegateInvokeMethod.RefKind, explicitInterfaceImplementations: default, name: eventHandlerMethodName, typeParameters: default, parameters: delegateInvokeMethod.Parameters, statements: ImmutableArray.Create( CodeGenerationHelpers.GenerateThrowStatement(syntaxFactory, semanticDocument, "System.NotImplementedException"))); } private void BeginInlineRename(ITextView textView, int plusEqualTokenEndPosition, CancellationToken cancellationToken) { AssertIsForeground(); if (_inlineRenameService.ActiveSession == null) { var document = textView.TextSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null) { // In the middle of a user action, cannot cancel. var root = document.GetSyntaxRootSynchronously(cancellationToken); var token = root.FindTokenOnRightOfPosition(plusEqualTokenEndPosition); var editSpan = token.Span; var memberAccessExpression = token.GetAncestor<MemberAccessExpressionSyntax>(); if (memberAccessExpression != null) { // the event hookup might look like `MyEvent += this.GeneratedHandlerName;` editSpan = memberAccessExpression.Name.Span; } _inlineRenameService.StartInlineSession(document, editSpan, cancellationToken); textView.SetSelection(editSpan.ToSnapshotSpan(textView.TextSnapshot)); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.EventHookup { internal partial class EventHookupCommandHandler : IChainedCommandHandler<TabKeyCommandArgs> { public void ExecuteCommand(TabKeyCommandArgs args, Action nextHandler, CommandExecutionContext context) { AssertIsForeground(); if (!args.SubjectBuffer.GetFeatureOnOffOption(InternalFeatureOnOffOptions.EventHookup)) { nextHandler(); return; } if (EventHookupSessionManager.CurrentSession == null) { nextHandler(); return; } // Handling tab is currently uncancellable. HandleTabWorker(args.TextView, args.SubjectBuffer, nextHandler, CancellationToken.None); } public CommandState GetCommandState(TabKeyCommandArgs args, Func<CommandState> nextHandler) { AssertIsForeground(); if (EventHookupSessionManager.CurrentSession != null) { return CommandState.Available; } else { return nextHandler(); } } private void HandleTabWorker(ITextView textView, ITextBuffer subjectBuffer, Action nextHandler, CancellationToken cancellationToken) { AssertIsForeground(); // For test purposes only! if (EventHookupSessionManager.CurrentSession.TESTSessionHookupMutex != null) { try { EventHookupSessionManager.CurrentSession.TESTSessionHookupMutex.ReleaseMutex(); } catch (ApplicationException) { } } // Blocking wait (if necessary) to determine whether to consume the tab and // generate the event handler. EventHookupSessionManager.CurrentSession.GetEventNameTask.Wait(cancellationToken); string eventHandlerMethodName = null; if (EventHookupSessionManager.CurrentSession.GetEventNameTask.Status == TaskStatus.RanToCompletion) { eventHandlerMethodName = EventHookupSessionManager.CurrentSession.GetEventNameTask.WaitAndGetResult(cancellationToken); } if (eventHandlerMethodName == null || EventHookupSessionManager.CurrentSession.TextView != textView) { nextHandler(); EventHookupSessionManager.CancelAndDismissExistingSessions(); return; } // This tab means we should generate the event handler method. Begin the code // generation process. GenerateAndAddEventHandler(textView, subjectBuffer, eventHandlerMethodName, nextHandler, cancellationToken); } private void GenerateAndAddEventHandler(ITextView textView, ITextBuffer subjectBuffer, string eventHandlerMethodName, Action nextHandler, CancellationToken cancellationToken) { AssertIsForeground(); using (Logger.LogBlock(FunctionId.EventHookup_Generate_Handler, cancellationToken)) { EventHookupSessionManager.CancelAndDismissExistingSessions(); var workspace = textView.TextSnapshot.TextBuffer.GetWorkspace(); if (workspace == null) { nextHandler(); EventHookupSessionManager.CancelAndDismissExistingSessions(); return; } var document = textView.TextSnapshot.GetOpenDocumentInCurrentContextWithChanges(); Contract.ThrowIfNull(document, "Event Hookup could not find the document for the IBufferView."); var position = textView.GetCaretPoint(subjectBuffer).Value.Position; var solutionWithEventHandler = CreateSolutionWithEventHandler( document, eventHandlerMethodName, position, out var plusEqualTokenEndPosition, cancellationToken); Contract.ThrowIfNull(solutionWithEventHandler, "Event Hookup could not create solution with event handler."); // The new solution is created, so start user observable changes Contract.ThrowIfFalse(workspace.TryApplyChanges(solutionWithEventHandler), "Event Hookup could not update the solution."); // The += token will not move during this process, so it is safe to use that // position as a location from which to find the identifier we're renaming. BeginInlineRename(textView, plusEqualTokenEndPosition, cancellationToken); } } private Solution CreateSolutionWithEventHandler( Document document, string eventHandlerMethodName, int position, out int plusEqualTokenEndPosition, CancellationToken cancellationToken) { AssertIsForeground(); // Mark the += token with an annotation so we can find it after formatting var plusEqualsTokenAnnotation = new SyntaxAnnotation(); var documentWithNameAndAnnotationsAdded = AddMethodNameAndAnnotationsToSolution(document, eventHandlerMethodName, position, plusEqualsTokenAnnotation, cancellationToken); var semanticDocument = SemanticDocument.CreateAsync(documentWithNameAndAnnotationsAdded, cancellationToken).WaitAndGetResult(cancellationToken); var updatedRoot = AddGeneratedHandlerMethodToSolution(semanticDocument, eventHandlerMethodName, plusEqualsTokenAnnotation, cancellationToken); if (updatedRoot == null) { plusEqualTokenEndPosition = 0; return null; } var simplifiedDocument = Simplifier.ReduceAsync(documentWithNameAndAnnotationsAdded.WithSyntaxRoot(updatedRoot), Simplifier.Annotation, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken); var formattedDocument = Formatter.FormatAsync(simplifiedDocument, Formatter.Annotation, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken); var newRoot = formattedDocument.GetSyntaxRootSynchronously(cancellationToken); plusEqualTokenEndPosition = newRoot.GetAnnotatedNodesAndTokens(plusEqualsTokenAnnotation) .Single().Span.End; return document.Project.Solution.WithDocumentText( formattedDocument.Id, formattedDocument.GetTextSynchronously(cancellationToken)); } private static Document AddMethodNameAndAnnotationsToSolution( Document document, string eventHandlerMethodName, int position, SyntaxAnnotation plusEqualsTokenAnnotation, CancellationToken cancellationToken) { // First find the event hookup to determine if we are in a static context. var root = document.GetSyntaxRootSynchronously(cancellationToken); var plusEqualsToken = root.FindTokenOnLeftOfPosition(position); var eventHookupExpression = plusEqualsToken.GetAncestor<AssignmentExpressionSyntax>(); var textToInsert = eventHandlerMethodName + ";"; if (!eventHookupExpression.IsInStaticContext()) { // This will be simplified later if it's not needed. textToInsert = "this." + textToInsert; } // Next, perform a textual insertion of the event handler method name. var textChange = new TextChange(new TextSpan(position, 0), textToInsert); var newText = document.GetTextSynchronously(cancellationToken).WithChanges(textChange); var documentWithNameAdded = document.WithText(newText); // Now find the event hookup again to add the appropriate annotations. root = documentWithNameAdded.GetSyntaxRootSynchronously(cancellationToken); plusEqualsToken = root.FindTokenOnLeftOfPosition(position); eventHookupExpression = plusEqualsToken.GetAncestor<AssignmentExpressionSyntax>(); var updatedEventHookupExpression = eventHookupExpression .ReplaceToken(plusEqualsToken, plusEqualsToken.WithAdditionalAnnotations(plusEqualsTokenAnnotation)) .WithRight(eventHookupExpression.Right.WithAdditionalAnnotations(Simplifier.Annotation)) .WithAdditionalAnnotations(Formatter.Annotation); var rootWithUpdatedEventHookupExpression = root.ReplaceNode(eventHookupExpression, updatedEventHookupExpression); return documentWithNameAdded.WithSyntaxRoot(rootWithUpdatedEventHookupExpression); } private static SyntaxNode AddGeneratedHandlerMethodToSolution( SemanticDocument document, string eventHandlerMethodName, SyntaxAnnotation plusEqualsTokenAnnotation, CancellationToken cancellationToken) { var root = document.Root as SyntaxNode; var eventHookupExpression = root.GetAnnotatedNodesAndTokens(plusEqualsTokenAnnotation).Single().AsToken().GetAncestor<AssignmentExpressionSyntax>(); var generatedMethodSymbol = GetMethodSymbol(document, eventHandlerMethodName, eventHookupExpression, cancellationToken); if (generatedMethodSymbol == null) { return null; } var typeDecl = eventHookupExpression.GetAncestor<TypeDeclarationSyntax>(); var typeDeclWithMethodAdded = CodeGenerator.AddMethodDeclaration(typeDecl, generatedMethodSymbol, document.Project.Solution.Workspace, new CodeGenerationOptions(afterThisLocation: eventHookupExpression.GetLocation())); return root.ReplaceNode(typeDecl, typeDeclWithMethodAdded); } private static IMethodSymbol GetMethodSymbol( SemanticDocument semanticDocument, string eventHandlerMethodName, AssignmentExpressionSyntax eventHookupExpression, CancellationToken cancellationToken) { var semanticModel = semanticDocument.SemanticModel as SemanticModel; var symbolInfo = semanticModel.GetSymbolInfo(eventHookupExpression.Left, cancellationToken); var symbol = symbolInfo.Symbol; if (symbol == null || symbol.Kind != SymbolKind.Event) { return null; } var typeInference = semanticDocument.Document.GetLanguageService<ITypeInferenceService>(); var delegateType = typeInference.InferDelegateType(semanticModel, eventHookupExpression.Right, cancellationToken); if (delegateType == null || delegateType.DelegateInvokeMethod == null) { return null; } var syntaxFactory = semanticDocument.Document.GetLanguageService<SyntaxGenerator>(); var delegateInvokeMethod = delegateType.DelegateInvokeMethod.RemoveInaccessibleAttributesAndAttributesOfTypes(semanticDocument.SemanticModel.Compilation.Assembly); return CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: default, accessibility: Accessibility.Private, modifiers: new DeclarationModifiers(isStatic: eventHookupExpression.IsInStaticContext()), returnType: delegateInvokeMethod.ReturnType, refKind: delegateInvokeMethod.RefKind, explicitInterfaceImplementations: default, name: eventHandlerMethodName, typeParameters: default, parameters: delegateInvokeMethod.Parameters, statements: ImmutableArray.Create( CodeGenerationHelpers.GenerateThrowStatement(syntaxFactory, semanticDocument, "System.NotImplementedException"))); } private void BeginInlineRename(ITextView textView, int plusEqualTokenEndPosition, CancellationToken cancellationToken) { AssertIsForeground(); if (_inlineRenameService.ActiveSession == null) { var document = textView.TextSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null) { // In the middle of a user action, cannot cancel. var root = document.GetSyntaxRootSynchronously(cancellationToken); var token = root.FindTokenOnRightOfPosition(plusEqualTokenEndPosition); var editSpan = token.Span; var memberAccessExpression = token.GetAncestor<MemberAccessExpressionSyntax>(); if (memberAccessExpression != null) { // the event hookup might look like `MyEvent += this.GeneratedHandlerName;` editSpan = memberAccessExpression.Name.Span; } _inlineRenameService.StartInlineSession(document, editSpan, cancellationToken); textView.SetSelection(editSpan.ToSnapshotSpan(textView.TextSnapshot)); } } } } }
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/Compilers/Core/Portable/SourceGeneration/GeneratorInfo.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 readonly struct GeneratorInfo { internal SyntaxContextReceiverCreator? SyntaxContextReceiverCreator { get; } internal Action<IncrementalGeneratorPostInitializationContext>? PostInitCallback { get; } internal Action<IncrementalGeneratorInitializationContext>? PipelineCallback { get; } internal bool Initialized { get; } internal GeneratorInfo(SyntaxContextReceiverCreator? receiverCreator, Action<IncrementalGeneratorPostInitializationContext>? postInitCallback, Action<IncrementalGeneratorInitializationContext>? pipelineCallback) { SyntaxContextReceiverCreator = receiverCreator; PostInitCallback = postInitCallback; PipelineCallback = pipelineCallback; Initialized = true; } internal class Builder { internal SyntaxContextReceiverCreator? SyntaxContextReceiverCreator { get; set; } internal Action<IncrementalGeneratorPostInitializationContext>? PostInitCallback { get; set; } internal Action<IncrementalGeneratorInitializationContext>? PipelineCallback { get; set; } public GeneratorInfo ToImmutable() => new GeneratorInfo(SyntaxContextReceiverCreator, PostInitCallback, PipelineCallback); } } }
// Licensed to the .NET Foundation under one or more 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 readonly struct GeneratorInfo { internal SyntaxContextReceiverCreator? SyntaxContextReceiverCreator { get; } internal Action<IncrementalGeneratorPostInitializationContext>? PostInitCallback { get; } internal Action<IncrementalGeneratorInitializationContext>? PipelineCallback { get; } internal bool Initialized { get; } internal GeneratorInfo(SyntaxContextReceiverCreator? receiverCreator, Action<IncrementalGeneratorPostInitializationContext>? postInitCallback, Action<IncrementalGeneratorInitializationContext>? pipelineCallback) { SyntaxContextReceiverCreator = receiverCreator; PostInitCallback = postInitCallback; PipelineCallback = pipelineCallback; Initialized = true; } internal class Builder { internal SyntaxContextReceiverCreator? SyntaxContextReceiverCreator { get; set; } internal Action<IncrementalGeneratorPostInitializationContext>? PostInitCallback { get; set; } internal Action<IncrementalGeneratorInitializationContext>? PipelineCallback { get; set; } public GeneratorInfo ToImmutable() => new GeneratorInfo(SyntaxContextReceiverCreator, PostInitCallback, PipelineCallback); } } }
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/Features/Core/Portable/ChangeSignature/ChangeSignatureCodeAction.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ChangeSignature { internal class ChangeSignatureCodeAction : CodeActionWithOptions { private readonly AbstractChangeSignatureService _changeSignatureService; private readonly ChangeSignatureAnalysisSucceededContext _context; public ChangeSignatureCodeAction(AbstractChangeSignatureService changeSignatureService, ChangeSignatureAnalysisSucceededContext context) { _changeSignatureService = changeSignatureService; _context = context; } public override string Title => FeaturesResources.Change_signature; public override object? GetOptions(CancellationToken cancellationToken) => AbstractChangeSignatureService.GetChangeSignatureOptions(_context); protected override async Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(object options, CancellationToken cancellationToken) { if (options is ChangeSignatureOptionsResult changeSignatureOptions && changeSignatureOptions != null) { var changeSignatureResult = await _changeSignatureService.ChangeSignatureWithContextAsync(_context, changeSignatureOptions, cancellationToken).ConfigureAwait(false); if (changeSignatureResult.Succeeded) { return SpecializedCollections.SingletonEnumerable<CodeActionOperation>(new ChangeSignatureCodeActionOperation(changeSignatureResult.UpdatedSolution, changeSignatureResult.ConfirmationMessage)); } } return SpecializedCollections.EmptyEnumerable<CodeActionOperation>(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ChangeSignature { internal class ChangeSignatureCodeAction : CodeActionWithOptions { private readonly AbstractChangeSignatureService _changeSignatureService; private readonly ChangeSignatureAnalysisSucceededContext _context; public ChangeSignatureCodeAction(AbstractChangeSignatureService changeSignatureService, ChangeSignatureAnalysisSucceededContext context) { _changeSignatureService = changeSignatureService; _context = context; } public override string Title => FeaturesResources.Change_signature; public override object? GetOptions(CancellationToken cancellationToken) => AbstractChangeSignatureService.GetChangeSignatureOptions(_context); protected override async Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(object options, CancellationToken cancellationToken) { if (options is ChangeSignatureOptionsResult changeSignatureOptions && changeSignatureOptions != null) { var changeSignatureResult = await _changeSignatureService.ChangeSignatureWithContextAsync(_context, changeSignatureOptions, cancellationToken).ConfigureAwait(false); if (changeSignatureResult.Succeeded) { return SpecializedCollections.SingletonEnumerable<CodeActionOperation>(new ChangeSignatureCodeActionOperation(changeSignatureResult.UpdatedSolution, changeSignatureResult.ConfirmationMessage)); } } return SpecializedCollections.EmptyEnumerable<CodeActionOperation>(); } } }
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/EditorFeatures/Core/Shared/Extensions/IBufferGraphExtensions.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 Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Projection; namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal enum BufferMapDirection { Identity, Down, Up, Unrelated } internal static class IBufferGraphExtensions { public static SnapshotSpan? MapUpOrDownToFirstMatch(this IBufferGraph bufferGraph, SnapshotSpan span, Predicate<ITextSnapshot> match) { var spans = bufferGraph.MapDownToFirstMatch(span, SpanTrackingMode.EdgeExclusive, match); if (!spans.Any()) { spans = bufferGraph.MapUpToFirstMatch(span, SpanTrackingMode.EdgeExclusive, match); } return spans.Select(s => (SnapshotSpan?)s).FirstOrDefault(); } public static SnapshotSpan? MapUpOrDownToBuffer(this IBufferGraph bufferGraph, SnapshotSpan span, ITextBuffer targetBuffer) { var direction = ClassifyBufferMapDirection(span.Snapshot.TextBuffer, targetBuffer); switch (direction) { case BufferMapDirection.Identity: return span; case BufferMapDirection.Down: { var spans = bufferGraph.MapDownToBuffer(span, SpanTrackingMode.EdgeExclusive, targetBuffer); return spans.Select(s => (SnapshotSpan?)s).FirstOrDefault(); } case BufferMapDirection.Up: { var spans = bufferGraph.MapUpToBuffer(span, SpanTrackingMode.EdgeExclusive, targetBuffer); return spans.Select(s => (SnapshotSpan?)s).FirstOrDefault(); } default: return null; } } public static SnapshotPoint? MapUpOrDownToBuffer(this IBufferGraph bufferGraph, SnapshotPoint point, ITextBuffer targetBuffer) { var direction = ClassifyBufferMapDirection(point.Snapshot.TextBuffer, targetBuffer); switch (direction) { case BufferMapDirection.Identity: return point; case BufferMapDirection.Down: { // TODO (https://github.com/dotnet/roslyn/issues/5281): Remove try-catch. try { return bufferGraph.MapDownToInsertionPoint(point, PointTrackingMode.Positive, s => s == targetBuffer.CurrentSnapshot); } catch (ArgumentOutOfRangeException) when (bufferGraph.TopBuffer.ContentType.TypeName == "Interactive Content") { // Suppress this to work around DevDiv #144964. // Note: Other callers might be affected, but this is the narrowest workaround for the observed problems. // A fix is already being reviewed, so a broader change is not required. return null; } } case BufferMapDirection.Up: { return bufferGraph.MapUpToBuffer(point, PointTrackingMode.Positive, PositionAffinity.Predecessor, targetBuffer); } default: return null; } } public static BufferMapDirection ClassifyBufferMapDirection(ITextBuffer startBuffer, ITextBuffer destinationBuffer) { if (startBuffer == destinationBuffer) { return BufferMapDirection.Identity; } // Are we trying to map down or up? if (startBuffer is IProjectionBufferBase startProjBuffer && IsSourceBuffer(startProjBuffer, destinationBuffer)) { return BufferMapDirection.Down; } if (destinationBuffer is IProjectionBufferBase destProjBuffer && IsSourceBuffer(destProjBuffer, startBuffer)) { return BufferMapDirection.Up; } return BufferMapDirection.Unrelated; } private static bool IsSourceBuffer(IProjectionBufferBase top, ITextBuffer bottom) { return top.SourceBuffers.Contains(bottom) || top.SourceBuffers.OfType<IProjectionBufferBase>().Any(b => IsSourceBuffer(b, bottom)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Linq; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Projection; namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal enum BufferMapDirection { Identity, Down, Up, Unrelated } internal static class IBufferGraphExtensions { public static SnapshotSpan? MapUpOrDownToFirstMatch(this IBufferGraph bufferGraph, SnapshotSpan span, Predicate<ITextSnapshot> match) { var spans = bufferGraph.MapDownToFirstMatch(span, SpanTrackingMode.EdgeExclusive, match); if (!spans.Any()) { spans = bufferGraph.MapUpToFirstMatch(span, SpanTrackingMode.EdgeExclusive, match); } return spans.Select(s => (SnapshotSpan?)s).FirstOrDefault(); } public static SnapshotSpan? MapUpOrDownToBuffer(this IBufferGraph bufferGraph, SnapshotSpan span, ITextBuffer targetBuffer) { var direction = ClassifyBufferMapDirection(span.Snapshot.TextBuffer, targetBuffer); switch (direction) { case BufferMapDirection.Identity: return span; case BufferMapDirection.Down: { var spans = bufferGraph.MapDownToBuffer(span, SpanTrackingMode.EdgeExclusive, targetBuffer); return spans.Select(s => (SnapshotSpan?)s).FirstOrDefault(); } case BufferMapDirection.Up: { var spans = bufferGraph.MapUpToBuffer(span, SpanTrackingMode.EdgeExclusive, targetBuffer); return spans.Select(s => (SnapshotSpan?)s).FirstOrDefault(); } default: return null; } } public static SnapshotPoint? MapUpOrDownToBuffer(this IBufferGraph bufferGraph, SnapshotPoint point, ITextBuffer targetBuffer) { var direction = ClassifyBufferMapDirection(point.Snapshot.TextBuffer, targetBuffer); switch (direction) { case BufferMapDirection.Identity: return point; case BufferMapDirection.Down: { // TODO (https://github.com/dotnet/roslyn/issues/5281): Remove try-catch. try { return bufferGraph.MapDownToInsertionPoint(point, PointTrackingMode.Positive, s => s == targetBuffer.CurrentSnapshot); } catch (ArgumentOutOfRangeException) when (bufferGraph.TopBuffer.ContentType.TypeName == "Interactive Content") { // Suppress this to work around DevDiv #144964. // Note: Other callers might be affected, but this is the narrowest workaround for the observed problems. // A fix is already being reviewed, so a broader change is not required. return null; } } case BufferMapDirection.Up: { return bufferGraph.MapUpToBuffer(point, PointTrackingMode.Positive, PositionAffinity.Predecessor, targetBuffer); } default: return null; } } public static BufferMapDirection ClassifyBufferMapDirection(ITextBuffer startBuffer, ITextBuffer destinationBuffer) { if (startBuffer == destinationBuffer) { return BufferMapDirection.Identity; } // Are we trying to map down or up? if (startBuffer is IProjectionBufferBase startProjBuffer && IsSourceBuffer(startProjBuffer, destinationBuffer)) { return BufferMapDirection.Down; } if (destinationBuffer is IProjectionBufferBase destProjBuffer && IsSourceBuffer(destProjBuffer, startBuffer)) { return BufferMapDirection.Up; } return BufferMapDirection.Unrelated; } private static bool IsSourceBuffer(IProjectionBufferBase top, ITextBuffer bottom) { return top.SourceBuffers.Contains(bottom) || top.SourceBuffers.OfType<IProjectionBufferBase>().Any(b => IsSourceBuffer(b, bottom)); } } }
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/Workspaces/MSBuildTest/Resources/NetCoreApp2AndTwoLibraries/Class1.cs
namespace Library1 { class Class1 { } }
namespace Library1 { class Class1 { } }
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/Compilers/CSharp/Test/Syntax/Parsing/PatternParsingTests.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.Text; 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 { [CompilerTrait(CompilerFeature.Patterns)] public class PatternParsingTests : ParsingTests { private new void UsingStatement(string text, params DiagnosticDescription[] expectedErrors) { UsingStatement(text, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8), expectedErrors); } public PatternParsingTests(ITestOutputHelper output) : base(output) { } [Fact] public void CasePatternVersusFeatureFlag() { var test = @" class C { public static void Main(string[] args) { switch ((int) args[0][0]) { case 1: case 2 when args.Length == 2: case 1<<2: case string s: default: break; } bool b = args[0] is string s; } } "; CreateCompilation(test, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)).VerifyDiagnostics( // (9,13): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater. // case 2 when args.Length == 2: Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "case 2 when args.Length == 2:").WithArguments("pattern matching", "7.0").WithLocation(9, 13), // (11,13): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater. // case string s: Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "case string s:").WithArguments("pattern matching", "7.0").WithLocation(11, 13), // (15,18): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater. // bool b = args[0] is string s; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "args[0] is string s").WithArguments("pattern matching", "7.0").WithLocation(15, 18), // (11,18): error CS8121: An expression of type 'int' cannot be handled by a pattern of type 'string'. // case string s: Diagnostic(ErrorCode.ERR_PatternWrongType, "string").WithArguments("int", "string").WithLocation(11, 18), // (11,25): error CS0136: A local or parameter named 's' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case string s: Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "s").WithArguments("s").WithLocation(11, 25) ); } [Fact] public void ThrowExpression_Good() { var test = @"using System; class C { public static void Sample(bool b, string s) { void NeverReturnsFunction() => throw new NullReferenceException(); int x = b ? throw new NullReferenceException() : 1; x = b ? 2 : throw new NullReferenceException(); s = s ?? throw new NullReferenceException(); NeverReturnsFunction(); throw new NullReferenceException() ?? throw new NullReferenceException() ?? throw null; } public static void NeverReturns() => throw new NullReferenceException(); }"; CreateCompilation(test).VerifyDiagnostics(); CreateCompilation(test, parseOptions: TestOptions.Regular6).VerifyDiagnostics( // (6,14): error CS8059: Feature 'local functions' is not available in C# 6. Please use language version 7.0 or greater. // void NeverReturnsFunction() => throw new NullReferenceException(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "NeverReturnsFunction").WithArguments("local functions", "7.0").WithLocation(6, 14), // (6,40): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // void NeverReturnsFunction() => throw new NullReferenceException(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw new NullReferenceException()").WithArguments("throw expression", "7.0").WithLocation(6, 40), // (7,21): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // int x = b ? throw new NullReferenceException() : 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw new NullReferenceException()").WithArguments("throw expression", "7.0").WithLocation(7, 21), // (8,21): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // x = b ? 2 : throw new NullReferenceException(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw new NullReferenceException()").WithArguments("throw expression", "7.0").WithLocation(8, 21), // (9,18): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // s = s ?? throw new NullReferenceException(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw new NullReferenceException()").WithArguments("throw expression", "7.0").WithLocation(9, 18), // (11,47): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // throw new NullReferenceException() ?? throw new NullReferenceException() ?? throw null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw new NullReferenceException() ?? throw null").WithArguments("throw expression", "7.0").WithLocation(11, 47), // (11,85): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // throw new NullReferenceException() ?? throw new NullReferenceException() ?? throw null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw null").WithArguments("throw expression", "7.0").WithLocation(11, 85), // (13,42): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // public static void NeverReturns() => throw new NullReferenceException(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw new NullReferenceException()").WithArguments("throw expression", "7.0").WithLocation(13, 42) ); } [Fact] public void ThrowExpression_Bad() { var test = @"using System; class C { public static void Sample(bool b, string s) { // throw expression at wrong precedence s = s + throw new NullReferenceException(); if (b || throw new NullReferenceException()) { } // throw expression where not permitted var z = from x in throw new NullReferenceException() select x; M(throw new NullReferenceException()); throw throw null; (int, int) w = (1, throw null); return throw null; } static void M(string s) {} }"; CreateCompilationWithMscorlib46(test).VerifyDiagnostics( // (7,17): error CS1525: Invalid expression term 'throw' // s = s + throw new NullReferenceException(); Diagnostic(ErrorCode.ERR_InvalidExprTerm, "throw new NullReferenceException()").WithArguments("throw").WithLocation(7, 17), // (8,18): error CS1525: Invalid expression term 'throw' // if (b || throw new NullReferenceException()) { } Diagnostic(ErrorCode.ERR_InvalidExprTerm, "throw new NullReferenceException()").WithArguments("throw").WithLocation(8, 18), // (11,27): error CS8115: A throw expression is not allowed in this context. // var z = from x in throw new NullReferenceException() select x; Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(11, 27), // (12,11): error CS8115: A throw expression is not allowed in this context. // M(throw new NullReferenceException()); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(12, 11), // (13,15): error CS8115: A throw expression is not allowed in this context. // throw throw null; Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(13, 15), // (14,9): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // (int, int) w = (1, throw null); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(int, int)").WithArguments("System.ValueTuple`2").WithLocation(14, 9), // (14,28): error CS8115: A throw expression is not allowed in this context. // (int, int) w = (1, throw null); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(14, 28), // (14,24): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // (int, int) w = (1, throw null); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(1, throw null)").WithArguments("System.ValueTuple`2").WithLocation(14, 24), // (15,16): error CS8115: A throw expression is not allowed in this context. // return throw null; Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(15, 16), // (14,9): warning CS0162: Unreachable code detected // (int, int) w = (1, throw null); Diagnostic(ErrorCode.WRN_UnreachableCode, "(").WithLocation(14, 9) ); } [Fact] public void ThrowExpression() { UsingTree(@" class C { int x = y ?? throw null; }", 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.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.CoalesceExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.QuestionQuestionToken); N(SyntaxKind.ThrowExpression); { N(SyntaxKind.ThrowKeyword); N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(14785, "https://github.com/dotnet/roslyn/issues/14785")] public void IsPatternPrecedence_1() { UsingNode(SyntaxFactory.ParseExpression("A is B < C, D > [ ]")); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "B"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "D"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } EOF(); } [Fact, WorkItem(14785, "https://github.com/dotnet/roslyn/issues/14785")] public void IsPatternPrecedence_2() { UsingNode(SyntaxFactory.ParseExpression("A < B > C")); N(SyntaxKind.GreaterThanExpression); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.GreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } EOF(); } [Fact, WorkItem(14785, "https://github.com/dotnet/roslyn/issues/14785")] public void IsPatternPrecedence_3() { SyntaxFactory.ParseExpression("e is A<B> && e").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("e is A<B> || e").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("e is A<B> ^ e").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("e is A<B> | e").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("e is A<B> & e").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("e is A<B>[]").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("new { X = e is A<B> }").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("e is A<B>").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("(item is Dictionary<string, object>[])").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("A is B < C, D > [ ]").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("A is B < C, D > [ ] E").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("A < B > C").GetDiagnostics().Verify(); } [Fact] public void QueryContextualPatternVariable_01() { SyntaxFactory.ParseExpression("from s in a where s is string where s.Length > 1 select s").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("M(out int? x)").GetDiagnostics().Verify(); } [Fact] public void TypeDisambiguation_01() { UsingStatement(@" var r = from s in a where s is X<T> // should disambiguate as a type here where M(s) select s as X<T>;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "r"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.QueryExpression); { N(SyntaxKind.FromClause); { N(SyntaxKind.FromKeyword); N(SyntaxKind.IdentifierToken, "s"); N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.QueryBody); { N(SyntaxKind.WhereClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "s"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "X"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } } } N(SyntaxKind.WhereClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "s"); } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.SelectClause); { N(SyntaxKind.SelectKeyword); N(SyntaxKind.AsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "s"); } N(SyntaxKind.AsKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "X"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } } } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypeDisambiguation_02() { UsingStatement(@" var r = a is X<T> // should disambiguate as a type here is bool;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "r"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "X"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.IsKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.BoolKeyword); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypeDisambiguation_03() { UsingStatement(@" var r = a is X<T> // should disambiguate as a type here > Z;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "r"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.GreaterThanExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "X"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.GreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Z"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence00() { UsingExpression("A is B << C"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence01() { UsingExpression("A is 1 << 2"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence02() { UsingExpression("A is null < B"); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence02b() { UsingExpression("A is B < C"); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence03() { UsingExpression("A is null == B"); N(SyntaxKind.EqualsExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } N(SyntaxKind.EqualsEqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence04() { UsingExpression("A is null & B"); N(SyntaxKind.BitwiseAndExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } N(SyntaxKind.AmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence05() { UsingExpression("A is null && B"); N(SyntaxKind.LogicalAndExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } N(SyntaxKind.AmpersandAmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence05b() { UsingExpression("A is null || B"); N(SyntaxKind.LogicalOrExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } N(SyntaxKind.BarBarToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence06() { UsingStatement(@"switch (e) { case 1 << 2: case B << C: case null < B: case null == B: case null & B: case null && B: break; }"); 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.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.EqualsExpression); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } N(SyntaxKind.EqualsEqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.BitwiseAndExpression); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } N(SyntaxKind.AmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.LogicalAndExpression); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } N(SyntaxKind.AmpersandAmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(21515, "https://github.com/dotnet/roslyn/issues/21515")] public void PatternExpressionPrecedence07() { // This should actually be error-free. UsingStatement(@"switch (array) { case KeyValuePair<string, DateTime>[] pairs1: case KeyValuePair<String, DateTime>[] pairs2: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "array"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "KeyValuePair"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "DateTime"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "pairs1"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "KeyValuePair"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "String"); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "DateTime"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "pairs2"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_01() { UsingExpression("A is B***", // (1,10): error CS1733: Expected expression // A is B*** Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(1, 10) ); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } } } } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_01b() { UsingExpression("A is B*** C"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } } } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_02() { UsingExpression("A is B***[]"); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_03() { UsingExpression("A is B***[] C"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "C"); } } } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_04() { UsingExpression("(B*** C, D)"); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "D"); } } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_04b() { UsingExpression("(B*** C)"); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_05() { UsingExpression("(B***[] C, D)"); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "C"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "D"); } } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_06() { UsingExpression("(D, B*** C)"); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "D"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_07() { UsingExpression("(D, B***[] C)"); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "D"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "C"); } } } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_08() { UsingStatement("switch (e) { case B*** C: break; }"); 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.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_09() { UsingStatement("switch (e) { case B***[] C: break; }"); 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.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "C"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void NameofInPattern_01() { // This should actually be error-free, because `nameof` might be a type. UsingStatement(@"switch (e) { case nameof n: ; }"); 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.IdentifierName); { N(SyntaxKind.IdentifierToken, "nameof"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "n"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void NameofInPattern_02() { // This should actually be error-free; a constant pattern with nameof(n) as the constant. UsingStatement(@"switch (e) { case nameof(n): ; }"); 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.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "nameof"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "n"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void NameofInPattern_03() { // This should actually be error-free; a constant pattern with nameof(n) as the constant. UsingStatement(@"switch (e) { case nameof(n) when true: ; }"); 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.ConstantPattern); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "nameof"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "n"); } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.WhenClause); { N(SyntaxKind.WhenKeyword); N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParenthesizedExpression_01() { UsingStatement(@"switch (e) { case (((3))): ; }"); 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.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParenthesizedExpression_02() { UsingStatement(@"switch (e) { case (((3))) when true: ; }"); 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.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.WhenClause); { N(SyntaxKind.WhenKeyword); N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParenthesizedExpression_03() { var expect = new[] { // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case (x: ((3))): ; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "(x: ((3)))").WithArguments("recursive patterns", "8.0").WithLocation(1, 19) }; UsingStatement(@"switch (e) { case (x: ((3))): ; }", TestOptions.RegularWithoutRecursivePatterns, expect); checkNodes(); UsingStatement(@"switch (e) { case (x: ((3))): ; }", TestOptions.Regular8); checkNodes(); void checkNodes() { 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.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } } [Fact] public void ParenthesizedExpression_04() { UsingStatement(@"switch (e) { case (((x: 3))): ; }", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8370: Feature 'parenthesized pattern' is not available in C# 7.3. Please use language version 9.0 or greater. // switch (e) { case (((x: 3))): ; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "(((x: 3)))").WithArguments("parenthesized pattern", "9.0").WithLocation(1, 19), // (1,20): error CS8370: Feature 'parenthesized pattern' is not available in C# 7.3. Please use language version 9.0 or greater. // switch (e) { case (((x: 3))): ; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "((x: 3))").WithArguments("parenthesized pattern", "9.0").WithLocation(1, 20) ); 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.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void RecursivePattern_01() { UsingStatement(@"switch (e) { case T(X: 3, Y: 4){L: 5} p: ; }", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case T(X: 3, Y: 4){L: 5} p: ; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "T(X: 3, Y: 4){L: 5} p").WithArguments("recursive patterns", "8.0").WithLocation(1, 19) ); 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.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Y"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "L"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "p"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void BrokenPattern_06() { UsingStatement(@"switch (e) { case (: ; }", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case (: ; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "(: ").WithArguments("recursive patterns", "8.0").WithLocation(1, 19), // (1,20): error CS1001: Identifier expected // switch (e) { case (: ; } Diagnostic(ErrorCode.ERR_IdentifierExpected, ":").WithLocation(1, 20), // (1,22): error CS1026: ) expected // switch (e) { case (: ; } Diagnostic(ErrorCode.ERR_CloseParenExpected, ";").WithLocation(1, 22), // (1,22): error CS1003: Syntax error, ':' expected // switch (e) { case (: ; } Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(":", ";").WithLocation(1, 22) ); 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.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void BrokenPattern_07() { UsingStatement(@"switch (e) { case (", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case ( Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "(").WithArguments("recursive patterns", "8.0").WithLocation(1, 19), // (1,20): error CS1026: ) expected // switch (e) { case ( Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(1, 20), // (1,20): error CS1003: Syntax error, ':' expected // switch (e) { case ( Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments(":", "").WithLocation(1, 20), // (1,20): error CS1513: } expected // switch (e) { case ( Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(1, 20) ); 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.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); } } M(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParenthesizedExpression_07() { UsingStatement(@"switch (e) { case (): }", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case (): } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "()").WithArguments("recursive patterns", "8.0").WithLocation(1, 19)); 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.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.ColonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void BrokenPattern_08() { UsingStatement(@"switch (e) { case", // (1,18): error CS1733: Expected expression // switch (e) { case Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(1, 18), // (1,18): error CS1003: Syntax error, ':' expected // switch (e) { case Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments(":", "").WithLocation(1, 18), // (1,18): error CS1513: } expected // switch (e) { case Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(1, 18) ); 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.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.ColonToken); } } M(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParenthesizedExpression_05() { UsingStatement(@"switch (e) { case (x: ): ; }", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case (x: ): ; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "(x: )").WithArguments("recursive patterns", "8.0").WithLocation(1, 19), // (1,23): error CS8504: Pattern missing // switch (e) { case (x: ): ; } Diagnostic(ErrorCode.ERR_MissingPattern, ")").WithLocation(1, 23) ); 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.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); } M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void EmptySwitchExpression() { UsingExpression("1 switch {}", TestOptions.RegularWithoutRecursivePatterns, // (1,1): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // 1 switch {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1 switch {}").WithArguments("recursive patterns", "8.0").WithLocation(1, 1) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpression01() { UsingExpression("1 switch {a => b, c => d}", TestOptions.RegularWithoutRecursivePatterns, // (1,1): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // 1 switch {a => b, c => d} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1 switch {a => b, c => d}").WithArguments("recursive patterns", "8.0").WithLocation(1, 1) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpression02() { UsingExpression("1 switch { a?b:c => d }", TestOptions.RegularWithoutRecursivePatterns, // (1,1): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // 1 switch { a?b:c => d } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1 switch { a?b:c => d }").WithArguments("recursive patterns", "8.0").WithLocation(1, 1), // (1,13): error CS1003: Syntax error, '=>' expected // 1 switch { a?b:c => d } Diagnostic(ErrorCode.ERR_SyntaxError, "?").WithArguments("=>", "?").WithLocation(1, 13), // (1,13): error CS1525: Invalid expression term '?' // 1 switch { a?b:c => d } Diagnostic(ErrorCode.ERR_InvalidExprTerm, "?").WithArguments("?").WithLocation(1, 13) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } M(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.ConditionalExpression); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); N(SyntaxKind.SimpleLambdaExpression); { N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpression03() { UsingExpression("1 switch { (a, b, c) => d }", TestOptions.RegularWithoutRecursivePatterns, // (1,1): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // 1 switch { (a, b, c) => d } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1 switch { (a, b, c) => d }").WithArguments("recursive patterns", "8.0").WithLocation(1, 1) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void BrokenRecursivePattern01() { // This put the parser into an infinite loop at one time. The precise diagnostics and nodes // are not as important as the fact that it terminates. UsingStatement("switch (e) { case T( : Q x = n; break; } ", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case T( : Q x = n; break; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "T( : Q x = n").WithArguments("recursive patterns", "8.0").WithLocation(1, 19), // (1,22): error CS1001: Identifier expected // switch (e) { case T( : Q x = n; break; } Diagnostic(ErrorCode.ERR_IdentifierExpected, ":").WithLocation(1, 22), // (1,28): error CS1003: Syntax error, ',' expected // switch (e) { case T( : Q x = n; break; } Diagnostic(ErrorCode.ERR_SyntaxError, "=").WithArguments(",", "=").WithLocation(1, 28), // (1,30): error CS1003: Syntax error, ',' expected // switch (e) { case T( : Q x = n; break; } Diagnostic(ErrorCode.ERR_SyntaxError, "n").WithArguments(",", "").WithLocation(1, 30), // (1,31): error CS1026: ) expected // switch (e) { case T( : Q x = n; break; } Diagnostic(ErrorCode.ERR_CloseParenExpected, ";").WithLocation(1, 31), // (1,31): error CS1003: Syntax error, ':' expected // switch (e) { case T( : Q x = n; break; } Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(":", ";").WithLocation(1, 31) ); 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.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Q"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "n"); } } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(26000, "https://github.com/dotnet/roslyn/issues/26000")] public void VarIsContextualKeywordForPatterns01() { UsingStatement("switch (e) { case var: break; }"); 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.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(26000, "https://github.com/dotnet/roslyn/issues/26000")] public void VarIsContextualKeywordForPatterns02() { UsingStatement("if (e is var) {}"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact, WorkItem(26000, "https://github.com/dotnet/roslyn/issues/26000")] public void WhenAsPatternVariable01() { UsingStatement("switch (e) { case var when: break; }", // (1,27): error CS1525: Invalid expression term ':' // switch (e) { case var when: break; } Diagnostic(ErrorCode.ERR_InvalidExprTerm, ":").WithArguments(":").WithLocation(1, 27) ); 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.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } } N(SyntaxKind.WhenClause); { N(SyntaxKind.WhenKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(26000, "https://github.com/dotnet/roslyn/issues/26000")] public void WhenAsPatternVariable02() { UsingStatement("switch (e) { case K when: break; }", // (1,25): error CS1525: Invalid expression term ':' // switch (e) { case K when: break; } Diagnostic(ErrorCode.ERR_InvalidExprTerm, ":").WithArguments(":").WithLocation(1, 25) ); 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.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "K"); } } N(SyntaxKind.WhenClause); { N(SyntaxKind.WhenKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact(Skip = "This is not a reliable test, and its failure modes are hard to capture. But it is helpful to run by hand to find parser issues.")] public void ParseFuzz() { Random random = new Random(); for (int i = 0; i < 4000; i++) { string source = $"class C{{void M(){{switch(e){{case {makePattern0()}:T v = e;}}}}}}"; try { Parse(source, options: TestOptions.RegularWithRecursivePatterns); for (int j = 0; j < 30; j++) { int k1 = random.Next(source.Length); int k2 = random.Next(source.Length); string source2 = source.Substring(0, k1) + source.Substring(k2); Parse(source2, options: TestOptions.RegularWithRecursivePatterns); } } catch (StackOverflowException) { Console.WriteLine("Failed on \"" + source + "\""); Assert.True(false, source); } catch (OutOfMemoryException) { Console.WriteLine("Failed on \"" + source + "\""); Assert.True(false, source); } } return; string makeProps(int maxDepth, bool needNames) { int nProps = random.Next(maxDepth); var builder = new StringBuilder(); for (int i = 0; i < nProps; i++) { if (i != 0) builder.Append(", "); if (needNames || random.Next(5) == 0) builder.Append("N: "); builder.Append(makePattern(maxDepth - 1)); } return builder.ToString(); } string makePattern(int maxDepth) { if (maxDepth <= 0 || random.Next(6) == 0) { switch (random.Next(4)) { case 0: return "_"; case 1: return "1"; case 2: return "T x"; default: return "var y"; } } else { // recursive pattern while (true) { bool nameType = random.Next(2) == 0; bool parensPart = random.Next(2) == 0; bool propsPart = random.Next(2) == 0; bool name = random.Next(2) == 0; if (!parensPart && !propsPart && !(nameType && name)) continue; return $"{(nameType ? "N" : "")} {(parensPart ? $"({makeProps(maxDepth, false)})" : "")} {(propsPart ? $"{{ {makeProps(maxDepth, true)} }}" : "")} {(name ? "n" : "")}"; } } } string makePattern0() => makePattern(random.Next(6)); } [Fact] public void ArrayOfTupleType01() { UsingStatement("if (o is (int, int)[]) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { 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.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType02() { UsingStatement("if (o is (int a, int b)[]) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType03() { UsingStatement("if (o is (int, int)[] q) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { 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.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType04() { UsingStatement("if (o is (int a, int b)[] q) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType05() { UsingStatement("if (o is (Int, Int)[]) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType06() { UsingStatement("if (o is (Int a, Int b)[]) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType07() { UsingStatement("if (o is (Int, Int)[] q) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType08() { UsingStatement("if (o is (Int a, Int b)[] q) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType09() { UsingStatement("if (o is (S.Int, S.Int)[]) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType10() { UsingStatement("if (o is (S.Int a, S.Int b)[]) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType11() { UsingStatement("if (o is (S.Int, S.Int)[] q) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType12() { UsingStatement("if (o is (S.Int a, S.Int b)[] q) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType13() { UsingStatement("switch (o) { case (int, int)[] q: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { 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.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ArrayOfTupleType14() { UsingStatement("switch (o) { case (int a, int b)[] q: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ArrayOfTupleType15() { UsingStatement("switch (o) { case (Int, Int)[] q: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ArrayOfTupleType16() { UsingStatement("switch (o) { case (Int a, Int b)[] q: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ArrayOfTupleType17() { UsingStatement("switch (o) { case (S.Int, S.Int)[] q: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ArrayOfTupleType18() { UsingStatement("switch (o) { case (S.Int a, S.Int b)[] q: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void RecursivePattern_00() { UsingStatement("var x = o is Type (Param: 3, Param2: 4) { Prop : 3 } x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_02() { UsingStatement("var x = o is (Param: 3, Param2: 4) { Prop : 3 } x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_03() { UsingStatement("var x = o is Type { Prop : 3 } x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_04() { UsingStatement("var x = o is { Prop : 3 } x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_05() { UsingStatement("var x = o is Type (Param: 3, Param2: 4) x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_06() { UsingStatement("var x = o is (Param: 3, Param2: 4) x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_07() { UsingStatement("var x = o is Type x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_08() { UsingStatement("var x = o is Type (Param: 3, Param2: 4) { Prop : 3 };"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_09() { UsingStatement("var x = o is (Param: 3, Param2: 4) { Prop : 3 };"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_10() { UsingStatement("var x = o is Type { Prop : 3 };"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_11() { UsingStatement("var x = o is { Prop : 3 };"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_12() { UsingStatement("var x = o is Type (Param: 3, Param2: 4);"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_13() { UsingStatement("var x = o is (Param: 3, Param2: 4);"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void ParenthesizedExpressionOfSwitchExpression() { UsingStatement("Console.Write((t) switch {var x => x});"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Console"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Write"); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.SwitchExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "t"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.VarPattern); { N(SyntaxKind.VarKeyword, "var"); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void DiscardInSwitchExpression() { UsingExpression("e switch { _ => 1 }"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.DiscardPattern); { N(SyntaxKind.UnderscoreToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void DiscardInSwitchStatement_01a() { UsingStatement("switch(e) { case _: break; }"); 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.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void DiscardInSwitchStatement_01b() { UsingStatement("switch(e) { case _: break; }", TestOptions.Regular7_3); 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.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void DiscardInSwitchStatement_02() { UsingStatement("switch(e) { case _ when true: break; }"); 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.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } } N(SyntaxKind.WhenClause); { N(SyntaxKind.WhenKeyword); N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void DiscardInRecursivePattern_01() { UsingExpression("e is (_, _)"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.DiscardPattern); { N(SyntaxKind.UnderscoreToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.DiscardPattern); { N(SyntaxKind.UnderscoreToken); } } N(SyntaxKind.CloseParenToken); } } } EOF(); } [Fact] public void DiscardInRecursivePattern_02() { UsingExpression("e is { P: _ }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "P"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.DiscardPattern); { N(SyntaxKind.UnderscoreToken); } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void NotDiscardInIsTypeExpression() { UsingExpression("e is _"); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } } EOF(); } [Fact] public void ShortTuplePatterns() { UsingExpression( @"e switch { var () => 1, () => 2, var (x) => 3, (1) _ => 4, (1) x => 5, (1) {} => 6, (Item1: 1) => 7, C(1) => 8 }", expectedErrors: new DiagnosticDescription[0]); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.VarPattern); { N(SyntaxKind.VarKeyword); N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.VarPattern); { N(SyntaxKind.VarKeyword); N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.DiscardDesignation); { N(SyntaxKind.UnderscoreToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "6"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Item1"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "7"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "8"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void NestedShortTuplePatterns() { UsingExpression( @"e switch { {X: var ()} => 1, {X: ()} => 2, {X: var (x)} => 3, {X: (1) _} => 4, {X: (1) x} => 5, {X: (1) {}} => 6, {X: (Item1: 1)} => 7, {X: C(1)} => 8 }", expectedErrors: new DiagnosticDescription[0]); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.VarPattern); { N(SyntaxKind.VarKeyword); N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.VarPattern); { N(SyntaxKind.VarKeyword); N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.DiscardDesignation); { N(SyntaxKind.UnderscoreToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "6"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Item1"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "7"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "8"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void IsNullableArray01() { // OK, this means `(o is A[]) ? b : c` because nullable types are not permitted for a pattern's type UsingExpression("o is A[] ? b : c"); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } EOF(); } [Fact] public void IsNullableArray02() { // error: 'cannot use nullable reference type for a pattern' or 'expected :' UsingExpression("o is A[] ? b && c", // (1,18): error CS1003: Syntax error, ':' expected // o is A[] ? b && c Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments(":", "").WithLocation(1, 18), // (1,18): error CS1733: Expected expression // o is A[] ? b && c Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(1, 18) ); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.QuestionToken); N(SyntaxKind.LogicalAndExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.AmpersandAmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } EOF(); } [Fact] public void IsNullableArray03() { // OK, this means `(o is A[][]) ? b : c` UsingExpression("o is A[][] ? b : c"); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } EOF(); } [Fact] public void IsNullableType01() { UsingExpression("o is A ? b : c"); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } EOF(); } [Fact] public void IsNullableType02() { UsingExpression("o is A? ? b : c"); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } EOF(); } [Fact, WorkItem(32161, "https://github.com/dotnet/roslyn/issues/32161")] public void ParenthesizedSwitchCase() { var text = @" switch (e) { case (0): break; case (-1): break; case (+2): break; case (~3): break; } "; foreach (var langVersion in new[] { LanguageVersion.CSharp6, LanguageVersion.CSharp7, LanguageVersion.CSharp8 }) { UsingStatement(text, options: CSharpParseOptions.Default.WithLanguageVersion(langVersion)); 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.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.UnaryMinusExpression); { N(SyntaxKind.MinusToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.UnaryPlusExpression); { N(SyntaxKind.PlusToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.BitwiseNotExpression); { N(SyntaxKind.TildeToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } } [Fact] public void TrailingCommaInSwitchExpression_01() { UsingExpression("1 switch { 1 => 2, }"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void TrailingCommaInSwitchExpression_02() { UsingExpression("1 switch { , }", // (1,12): error CS8504: Pattern missing // 1 switch { , } Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 12), // (1,12): error CS1003: Syntax error, '=>' expected // 1 switch { , } Diagnostic(ErrorCode.ERR_SyntaxError, ",").WithArguments("=>", ",").WithLocation(1, 12), // (1,12): error CS1525: Invalid expression term ',' // 1 switch { , } Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(1, 12) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); M(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.EqualsGreaterThanToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void TrailingCommaInPropertyPattern_01() { UsingExpression("e is { X: 3, }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void TrailingCommaInPropertyPattern_02() { UsingExpression("e is { , }", // (1,8): error CS8504: Pattern missing // e is { , } Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 8) ); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); M(SyntaxKind.Subpattern); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void TrailingCommaInPositionalPattern_01() { UsingExpression("e is ( X: 3, )", // (1,14): error CS8504: Pattern missing // e is ( X: 3, ) Diagnostic(ErrorCode.ERR_MissingPattern, ")").WithLocation(1, 14) ); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); M(SyntaxKind.Subpattern); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.CloseParenToken); } } } EOF(); } [Fact] public void TrailingCommaInPositionalPattern_02() { UsingExpression("e is ( , )", // (1,8): error CS8504: Pattern missing // e is ( , ) Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 8), // (1,10): error CS8504: Pattern missing // e is ( , ) Diagnostic(ErrorCode.ERR_MissingPattern, ")").WithLocation(1, 10) ); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.Subpattern); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.CommaToken); M(SyntaxKind.Subpattern); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.CloseParenToken); } } } EOF(); } [Fact] public void ExtraCommaInSwitchExpression() { UsingExpression("e switch { 1 => 2,, }", // (1,19): error CS8504: Pattern missing // e switch { 1 => 2,, } Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 19), // (1,19): error CS1003: Syntax error, '=>' expected // e switch { 1 => 2,, } Diagnostic(ErrorCode.ERR_SyntaxError, ",").WithArguments("=>", ",").WithLocation(1, 19), // (1,19): error CS1525: Invalid expression term ',' // e switch { 1 => 2,, } Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(1, 19) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); M(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.EqualsGreaterThanToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ExtraCommaInPropertyPattern() { UsingExpression("e is { A: 1,, }", // (1,13): error CS8504: Pattern missing // e is { A: 1,, } Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 13) ); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CommaToken); M(SyntaxKind.Subpattern); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact, WorkItem(33054, "https://github.com/dotnet/roslyn/issues/33054")] public void ParenthesizedExpressionInPattern_01() { UsingStatement( @"switch (e) { case (('C') << 24) + (('g') << 16) + (('B') << 8) + 'I': break; }"); 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.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.AddExpression); { N(SyntaxKind.AddExpression); { N(SyntaxKind.AddExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "24"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PlusToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "16"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.PlusToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "8"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.PlusToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(33208, "https://github.com/dotnet/roslyn/issues/33208")] public void ParenthesizedExpressionInPattern_02() { UsingStatement( @"switch (e) { case ((2) + (2)): break; }"); 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.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.AddExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PlusToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(33208, "https://github.com/dotnet/roslyn/issues/33208")] public void ParenthesizedExpressionInPattern_03() { UsingStatement( @"switch (e) { case ((2 + 2) - 2): break; }"); 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.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SubtractExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.AddExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.PlusToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.MinusToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(33208, "https://github.com/dotnet/roslyn/issues/33208")] public void ParenthesizedExpressionInPattern_04() { UsingStatement( @"switch (e) { case (2) | (2): break; }"); 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.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.BitwiseOrExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.BarToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(33208, "https://github.com/dotnet/roslyn/issues/33208")] public void ParenthesizedExpressionInPattern_05() { UsingStatement( @"switch (e) { case ((2 << 2) | 2): break; }"); 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.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.BitwiseOrExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.BarToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ChainedSwitchExpression_01() { UsingExpression("1 switch { 1 => 2 } switch { 2 => 3 }"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ChainedSwitchExpression_02() { UsingExpression("a < b switch { 1 => 2 } < c switch { 2 => 3 }"); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.LessThanToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void SwitchExpressionPrecedence_01() { UsingExpression("a < b switch { true => 1 }"); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void SwitchExpressionPrecedence_02() { // The left-hand-side of a switch is equality, which binds more loosely than the `switch`, // so `b` ends up on the left of the `switch` and the `a ==` expression has a switch on the right. UsingExpression("a == b switch { true => 1 }"); N(SyntaxKind.EqualsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.EqualsEqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void SwitchExpressionPrecedence_03() { UsingExpression("a * b switch {}"); N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void SwitchExpressionPrecedence_04() { UsingExpression("a + b switch {}"); N(SyntaxKind.AddExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.PlusToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void SwitchExpressionPrecedence_05() { UsingExpression("-a switch {}"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.UnaryMinusExpression); { N(SyntaxKind.MinusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_06() { UsingExpression("(Type)a switch {}"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_07() { UsingExpression("(Type)a++ switch {}"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.PostIncrementExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.PlusPlusToken); } } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_08() { UsingExpression("+a switch {}"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.UnaryPlusExpression); { N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_09() { UsingExpression("a switch {}.X", // (1,1): error CS1073: Unexpected token '.' // a switch {}.X Diagnostic(ErrorCode.ERR_UnexpectedToken, "a switch {}").WithArguments(".").WithLocation(1, 1)); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_10() { UsingExpression("a switch {}[i]", // (1,1): error CS1073: Unexpected token '[' // a switch {}[i] Diagnostic(ErrorCode.ERR_UnexpectedToken, "a switch {}").WithArguments("[").WithLocation(1, 1)); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_11() { UsingExpression("a switch {}(b)", // (1,1): error CS1073: Unexpected token '(' // a switch {}(b) Diagnostic(ErrorCode.ERR_UnexpectedToken, "a switch {}").WithArguments("(").WithLocation(1, 1)); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_12() { UsingExpression("a switch {}!", // (1,1): error CS1073: Unexpected token '!' // a switch {}! Diagnostic(ErrorCode.ERR_UnexpectedToken, "a switch {}").WithArguments("!").WithLocation(1, 1)); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(32749, "https://github.com/dotnet/roslyn/issues/32749")] public void BrokenSwitchExpression_01() { UsingExpression("(e switch {)", // (1,12): error CS1513: } expected // (e switch {) Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(1, 12) ); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(32749, "https://github.com/dotnet/roslyn/issues/32749")] public void BrokenSwitchExpression_02() { UsingExpression("(e switch {,)", // (1,12): error CS8504: Pattern missing // (e switch {,) Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 12), // (1,12): error CS1003: Syntax error, '=>' expected // (e switch {,) Diagnostic(ErrorCode.ERR_SyntaxError, ",").WithArguments("=>", ",").WithLocation(1, 12), // (1,12): error CS1525: Invalid expression term ',' // (e switch {,) Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(1, 12), // (1,13): error CS1513: } expected // (e switch {,) Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(1, 13) ); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); M(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.EqualsGreaterThanToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(32749, "https://github.com/dotnet/roslyn/issues/32749")] public void BrokenSwitchExpression_03() { UsingExpression("e switch {,", // (1,11): error CS8504: Pattern missing // e switch {, Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 11), // (1,11): error CS1003: Syntax error, '=>' expected // e switch {, Diagnostic(ErrorCode.ERR_SyntaxError, ",").WithArguments("=>", ",").WithLocation(1, 11), // (1,11): error CS1525: Invalid expression term ',' // e switch {, Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(1, 11), // (1,12): error CS1513: } expected // e switch {, Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(1, 12) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); M(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.EqualsGreaterThanToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); M(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(33675, "https://github.com/dotnet/roslyn/issues/33675")] public void ParenthesizedNamedConstantPatternInSwitchExpression() { UsingExpression("e switch { (X) => 1 }"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(34482, "https://github.com/dotnet/roslyn/issues/34482")] public void SwitchCaseArmErrorRecovery_01() { UsingExpression("e switch { 1 => 1; 2 => 2 }", // (1,18): error CS1003: Syntax error, ',' expected // e switch { 1 => 1; 2 => 2 } Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(",", ";").WithLocation(1, 18) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } M(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(34482, "https://github.com/dotnet/roslyn/issues/34482")] public void SwitchCaseArmErrorRecovery_02() { UsingExpression("e switch { 1 => 1, 2 => 2; }", // (1,26): error CS1003: Syntax error, ',' expected // e switch { 1 => 1, 2 => 2; } Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(",", ";").WithLocation(1, 26) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } M(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(38121, "https://github.com/dotnet/roslyn/issues/38121")] public void GenericPropertyPattern() { UsingExpression("e is A<B> {}"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact, WorkItem(10492, "https://github.com/dotnet/roslyn/issues/10492")] public void PrecedenceInversionWithDeclarationPattern() { UsingExpression("o is C c + d", // (1,10): error CS1073: Unexpected token '+' // o is C c + d Diagnostic(ErrorCode.ERR_UnexpectedToken, "+").WithArguments("+").WithLocation(1, 10) ); N(SyntaxKind.AddExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "c"); } } } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } EOF(); } [Fact, WorkItem(10492, "https://github.com/dotnet/roslyn/issues/10492")] public void PrecedenceInversionWithRecursivePattern() { UsingExpression("o is {} + d", // (1,9): error CS1073: Unexpected token '+' // o is {} + d Diagnostic(ErrorCode.ERR_UnexpectedToken, "+").WithArguments("+").WithLocation(1, 9) ); N(SyntaxKind.AddExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } EOF(); } [Fact] public void PatternCombinators_01() { UsingStatement("_ = e is a or b;", TestOptions.RegularWithoutPatternCombinators, // (1,10): error CS8400: Feature 'or pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = e is a or b; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "a or b").WithArguments("or pattern", "9.0").WithLocation(1, 10) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void PatternCombinators_02() { UsingStatement("_ = e is a and b;", TestOptions.RegularWithoutPatternCombinators, // (1,10): error CS8400: Feature 'and pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = e is a and b; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "a and b").WithArguments("and pattern", "9.0").WithLocation(1, 10) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void PatternCombinators_03() { UsingStatement("_ = e is not b;", TestOptions.RegularWithoutPatternCombinators, // (1,10): error CS8400: Feature 'not pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = e is not b; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "not b").WithArguments("not pattern", "9.0").WithLocation(1, 10) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.NotPattern); { N(SyntaxKind.NotKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void PatternCombinators_04() { UsingStatement("_ = e is not null;", TestOptions.RegularWithoutPatternCombinators, // (1,10): error CS8400: Feature 'not pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = e is not null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "not null").WithArguments("not pattern", "9.0").WithLocation(1, 10) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.NotPattern); { N(SyntaxKind.NotKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void PatternCombinators_05() { UsingStatement( @"_ = e switch { a or b => 1, c and d => 2, not e => 3, not null => 4, };", TestOptions.RegularWithoutPatternCombinators, // (2,5): error CS8400: Feature 'or pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // a or b => 1, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "a or b").WithArguments("or pattern", "9.0").WithLocation(2, 5), // (3,5): error CS8400: Feature 'and pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // c and d => 2, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "c and d").WithArguments("and pattern", "9.0").WithLocation(3, 5), // (4,5): error CS8400: Feature 'not pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // not e => 3, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "not e").WithArguments("not pattern", "9.0").WithLocation(4, 5), // (5,5): error CS8400: Feature 'not pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // not null => 4, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "not null").WithArguments("not pattern", "9.0").WithLocation(5, 5) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.AndPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.NotPattern); { N(SyntaxKind.NotKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.NotPattern); { N(SyntaxKind.NotKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RelationalPattern_01() { UsingStatement( @"_ = e switch { < 0 => 0, <= 1 => 1, > 2 => 2, >= 3 => 3, == 4 => 4, != 5 => 5, };", TestOptions.RegularWithoutPatternCombinators, // (2,5): error CS8400: Feature 'relational pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // < 0 => 0, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "< 0").WithArguments("relational pattern", "9.0").WithLocation(2, 5), // (3,5): error CS8400: Feature 'relational pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // <= 1 => 1, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "<= 1").WithArguments("relational pattern", "9.0").WithLocation(3, 5), // (4,5): error CS8400: Feature 'relational pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // > 2 => 2, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "> 2").WithArguments("relational pattern", "9.0").WithLocation(4, 5), // (5,5): error CS8400: Feature 'relational pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // >= 3 => 3, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, ">= 3").WithArguments("relational pattern", "9.0").WithLocation(5, 5), // (6,5): error CS8400: Feature 'relational pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // == 4 => 4, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "== 4").WithArguments("relational pattern", "9.0").WithLocation(6, 5), // (7,5): error CS8400: Feature 'relational pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // != 5 => 5, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "!= 5").WithArguments("relational pattern", "9.0").WithLocation(7, 5) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.EqualsEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.ExclamationEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RelationalPatternPrecedence_01() { UsingStatement( @"_ = e switch { < 0 < 0 => 0, == 4 < 4 => 4, != 5 < 5 => 5, };", TestOptions.RegularWithPatternCombinators, // (2,9): error CS1003: Syntax error, '=>' expected // < 0 < 0 => 0, Diagnostic(ErrorCode.ERR_SyntaxError, "<").WithArguments("=>", "<").WithLocation(2, 9), // (2,9): error CS1525: Invalid expression term '<' // < 0 < 0 => 0, Diagnostic(ErrorCode.ERR_InvalidExprTerm, "<").WithArguments("<").WithLocation(2, 9), // (2,13): error CS1003: Syntax error, ',' expected // < 0 < 0 => 0, Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(",", "=>").WithLocation(2, 13), // (2,13): error CS8504: Pattern missing // < 0 < 0 => 0, Diagnostic(ErrorCode.ERR_MissingPattern, "=>").WithLocation(2, 13), // (3,10): error CS1003: Syntax error, '=>' expected // == 4 < 4 => 4, Diagnostic(ErrorCode.ERR_SyntaxError, "<").WithArguments("=>", "<").WithLocation(3, 10), // (3,10): error CS1525: Invalid expression term '<' // == 4 < 4 => 4, Diagnostic(ErrorCode.ERR_InvalidExprTerm, "<").WithArguments("<").WithLocation(3, 10), // (3,14): error CS1003: Syntax error, ',' expected // == 4 < 4 => 4, Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(",", "=>").WithLocation(3, 14), // (3,14): error CS8504: Pattern missing // == 4 < 4 => 4, Diagnostic(ErrorCode.ERR_MissingPattern, "=>").WithLocation(3, 14), // (4,10): error CS1003: Syntax error, '=>' expected // != 5 < 5 => 5, Diagnostic(ErrorCode.ERR_SyntaxError, "<").WithArguments("=>", "<").WithLocation(4, 10), // (4,10): error CS1525: Invalid expression term '<' // != 5 < 5 => 5, Diagnostic(ErrorCode.ERR_InvalidExprTerm, "<").WithArguments("<").WithLocation(4, 10), // (4,14): error CS1003: Syntax error, ',' expected // != 5 < 5 => 5, Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(",", "=>").WithLocation(4, 14), // (4,14): error CS8504: Pattern missing // != 5 < 5 => 5, Diagnostic(ErrorCode.ERR_MissingPattern, "=>").WithLocation(4, 14) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } M(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.LessThanExpression); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.EqualsEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } M(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.LessThanExpression); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.ExclamationEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } M(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.LessThanExpression); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RelationalPatternPrecedence_02() { UsingStatement( @"_ = e switch { < 0 << 0 => 0, == 4 << 4 => 4, != 5 << 5 => 5, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.EqualsEqualsToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.ExclamationEqualsToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RelationalPatternPrecedence_03() { UsingStatement( @"_ = e is < 4;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RelationalPatternPrecedence_04() { UsingStatement( @"_ = e is < 4 < 4;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RelationalPatternPrecedence_05() { UsingStatement( @"_ = e is < 4 << 4;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void WhenIsNotKeywordInIsExpression() { UsingStatement(@"_ = e is T when;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "when"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void WhenIsNotKeywordInRecursivePattern() { UsingStatement(@"_ = e switch { T(X when) => 1, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "when"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_01() { UsingStatement(@"_ = e is int or long;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.LongKeyword); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_02() { UsingStatement(@"_ = e is int or System.Int64;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "System"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int64"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_03() { UsingStatement(@"_ = e switch { int or long => 1, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.OrPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.LongKeyword); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_04() { UsingStatement(@"_ = e switch { int or System.Int64 => 1, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.OrPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "System"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int64"); } } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_05() { UsingStatement(@"_ = e switch { T(int) => 1, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_06() { UsingStatement(@"_ = e switch { int => 1, long => 2, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.LongKeyword); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(49354, "https://github.com/dotnet/roslyn/issues/49354")] public void TypePattern_07() { UsingStatement(@"_ = e is (int) or string;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.OrKeyword); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_08() { UsingStatement($"_ = e is (a) or b;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CompoundPattern_01() { UsingStatement(@"bool isLetter(char c) => c is >= 'a' and <= 'z' or >= 'A' and <= 'Z';", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.LocalFunctionStatement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.BoolKeyword); } N(SyntaxKind.IdentifierToken, "isLetter"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.CharKeyword); } N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.AndPattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } } N(SyntaxKind.OrKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_01() { UsingStatement(@"_ = e is int and;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "and"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_02() { UsingStatement(@"_ = e is int and < Z;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Z"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_03() { UsingStatement(@"_ = e is int and && b;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.LogicalAndExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "and"); } } } N(SyntaxKind.AmpersandAmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_04() { UsingStatement(@"_ = e is int and int.MaxValue;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "MaxValue"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_05() { UsingStatement(@"_ = e is int and MaxValue;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "MaxValue"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_06() { UsingStatement(@"_ = e is int and ?? Z;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.CoalesceExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "and"); } } } N(SyntaxKind.QuestionQuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Z"); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_07() { UsingStatement(@"_ = e is int and ? a : b;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "and"); } } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(10492, "https://github.com/dotnet/roslyn/issues/10492")] public void PrecedenceInversionWithTypeTest() { UsingExpression("o is int + d", // (1,6): error CS1525: Invalid expression term 'int' // o is int + d Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(1, 6) ); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.AddExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } } } EOF(); } [Fact, WorkItem(10492, "https://github.com/dotnet/roslyn/issues/10492")] public void PrecedenceInversionWithBlockLambda() { UsingExpression("() => {} + d", // (1,10): warning CS8848: Operator '+' cannot be used here due to precedence. Use parentheses to disambiguate. // () => {} + d Diagnostic(ErrorCode.WRN_PrecedenceInversion, "+").WithArguments("+").WithLocation(1, 10) ); N(SyntaxKind.AddExpression); { N(SyntaxKind.ParenthesizedLambdaExpression); { N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } EOF(); } [Fact, WorkItem(10492, "https://github.com/dotnet/roslyn/issues/10492")] public void PrecedenceInversionWithAnonymousMethod() { UsingExpression("delegate {} + d", // (1,13): warning CS8848: Operator '+' cannot be used here due to precedence. Use parentheses to disambiguate. // delegate {} + d Diagnostic(ErrorCode.WRN_PrecedenceInversion, "+").WithArguments("+").WithLocation(1, 13) ); N(SyntaxKind.AddExpression); { N(SyntaxKind.AnonymousMethodExpression); { N(SyntaxKind.DelegateKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void OneElementPositional_01() { UsingStatement(@"_ = e is (3);", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void OneElementPositional_02() { UsingStatement(@"_ = e is (A);", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void OneElementPositional_03() { UsingStatement(@"_ = e is (int);", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void OneElementPositional_04() { UsingStatement(@"_ = e is (Item1: int);", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Item1"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void OneElementPositional_05() { UsingStatement(@"_ = e is (A) x;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void OneElementPositional_06() { UsingStatement(@"_ = e is ((A, A)) x;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void ZeroElementPositional_01() { UsingStatement(@"_ = e is ();", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void ZeroElementPositional_02() { UsingStatement(@"_ = e is () x;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void ZeroElementPositional_03() { UsingStatement(@"_ = e is () {};", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CastExpressionInPattern_01() { UsingStatement(@"_ = e is (int)+1;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.UnaryPlusExpression); { N(SyntaxKind.PlusToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Theory] [InlineData("or")] [InlineData("and")] [InlineData("not")] public void CastExpressionInPattern_02(string identifier) { UsingStatement($"_ = e is (int){identifier};", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, identifier); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Theory] [CombinatorialData] public void CastExpressionInPattern_03( [CombinatorialValues("and", "or")] string left, [CombinatorialValues(SyntaxKind.AndKeyword, SyntaxKind.OrKeyword)] SyntaxKind opKind, [CombinatorialValues("and", "or")] string right) { UsingStatement($"_ = e is (int){left} {SyntaxFacts.GetText(opKind)} {right};", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(opKind == SyntaxKind.AndKeyword ? SyntaxKind.AndPattern : SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, left); } } } N(opKind); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, right); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CastExpressionInPattern_04() { UsingStatement($"_ = e is (a)42 or b;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "42"); } } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Theory] [CombinatorialData] public void CombinatorAsConstant_00( [CombinatorialValues("and", "or")] string left, [CombinatorialValues(SyntaxKind.AndKeyword, SyntaxKind.OrKeyword)] SyntaxKind opKind, [CombinatorialValues("and", "or")] string right) { UsingStatement($"_ = e is {left} {SyntaxFacts.GetText(opKind)} {right};", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(opKind == SyntaxKind.AndKeyword ? SyntaxKind.AndPattern : SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, left); } } N(opKind); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, right); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Theory] [CombinatorialData] public void CombinatorAsConstant_01( [CombinatorialValues(SyntaxKind.AndKeyword, SyntaxKind.OrKeyword)] SyntaxKind opKind, [CombinatorialValues("and", "or")] string right) { UsingStatement($"_ = e is (int) {SyntaxFacts.GetText(opKind)} {right};", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(opKind == SyntaxKind.AndKeyword ? SyntaxKind.AndPattern : SyntaxKind.OrPattern); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(opKind); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, right); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsConstant_02() { UsingStatement($"_ = e is (int) or >= 0;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.OrKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsConstant_03() { UsingStatement($"_ = e is (int)or or >= 0;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "or"); } } } N(SyntaxKind.OrKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsConstant_04() { UsingStatement($"_ = e is (int) or or or >= 0;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.OrPattern); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "or"); } } } N(SyntaxKind.OrKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void ConjunctiveFollowedByPropertyPattern_01() { UsingStatement(@"switch (e) { case {} and {}: break; }", TestOptions.RegularWithPatternCombinators ); 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.AndPattern); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ConjunctiveFollowedByTuplePattern_01() { UsingStatement(@"switch (e) { case {} and (): break; }", TestOptions.RegularWithPatternCombinators ); 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.AndPattern); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] [WorkItem(42107, "https://github.com/dotnet/roslyn/issues/42107")] public void ParenthesizedRelationalPattern_01() { UsingStatement(@"_ = e is (>= 1);", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] [WorkItem(42107, "https://github.com/dotnet/roslyn/issues/42107")] public void ParenthesizedRelationalPattern_02() { UsingStatement(@"_ = e switch { (>= 1) => 1 };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] [WorkItem(42107, "https://github.com/dotnet/roslyn/issues/42107")] public void ParenthesizedRelationalPattern_03() { UsingStatement(@"bool isAsciiLetter(char c) => c is (>= 'A' and <= 'Z') or (>= 'a' and <= 'z');", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.LocalFunctionStatement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.BoolKeyword); } N(SyntaxKind.IdentifierToken, "isAsciiLetter"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.CharKeyword); } N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.AndPattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.OrKeyword); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.AndPattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] [WorkItem(42107, "https://github.com/dotnet/roslyn/issues/42107")] public void ParenthesizedRelationalPattern_04() { UsingStatement(@"_ = e is (<= 1, >= 2);", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void AndPatternAssociativity_01() { UsingStatement(@"_ = e is A and B and C;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.AndPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } } N(SyntaxKind.AndKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void OrPatternAssociativity_01() { UsingStatement(@"_ = e is A or B or C;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(43960, "https://github.com/dotnet/roslyn/issues/43960")] public void NamespaceQualifiedEnumConstantInSwitchCase() { var source = @"switch (e) { case global::E.A: break; }"; UsingStatement(source, TestOptions.RegularWithPatternCombinators ); verifyTree(); UsingStatement(source, TestOptions.RegularWithoutPatternCombinators ); verifyTree(); void verifyTree() { 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.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.GlobalKeyword); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "E"); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } } [Fact, WorkItem(44019, "https://github.com/dotnet/roslyn/issues/44019")] public void NamespaceQualifiedEnumConstantInIsPattern() { var source = @"_ = e is global::E.A;"; UsingStatement(source, TestOptions.RegularWithPatternCombinators ); verifyTree(); UsingStatement(source, TestOptions.RegularWithoutPatternCombinators ); verifyTree(); void verifyTree() { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.GlobalKeyword); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "E"); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact, WorkItem(45757, "https://github.com/dotnet/roslyn/issues/45757")] public void IncompleteTuplePatternInPropertySubpattern() { var source = @"_ = this is Program { P1: (1, }"; var expectedErrors = new[] { // (1,32): error CS1026: ) expected // _ = this is Program { P1: (1, } Diagnostic(ErrorCode.ERR_CloseParenExpected, "}").WithLocation(1, 32), // (1,33): error CS1002: ; expected // _ = this is Program { P1: (1, } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(1, 33) }; UsingStatement(source, TestOptions.RegularWithPatternCombinators, expectedErrors ); verifyTree(); UsingStatement(source, TestOptions.RegularWithoutPatternCombinators, expectedErrors ); verifyTree(); void verifyTree() { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.ThisExpression); { N(SyntaxKind.ThisKeyword); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Program"); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "P1"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CommaToken); M(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseBraceToken); } } } } M(SyntaxKind.SemicolonToken); } EOF(); } } [Fact, WorkItem(45757, "https://github.com/dotnet/roslyn/issues/45757")] public void IncompleteTuplePattern() { var source = @"_ = i is (1, }"; var expectedErrors = new[] { // (1,1): error CS1073: Unexpected token '}' // _ = i is (1, } Diagnostic(ErrorCode.ERR_UnexpectedToken, "_ = i is (1, ").WithArguments("}").WithLocation(1, 1), // (1,16): error CS1026: ) expected // _ = i is (1, } Diagnostic(ErrorCode.ERR_CloseParenExpected, "}").WithLocation(1, 16), // (1,16): error CS1002: ; expected // _ = i is (1, } Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(1, 16) }; UsingStatement(source, TestOptions.RegularWithPatternCombinators, expectedErrors ); verifyTree(); UsingStatement(source, TestOptions.RegularWithoutPatternCombinators, expectedErrors ); verifyTree(); void verifyTree() { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "i"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CommaToken); M(SyntaxKind.CloseParenToken); } } } } M(SyntaxKind.SemicolonToken); } EOF(); } } [Fact, WorkItem(47614, "https://github.com/dotnet/roslyn/issues/47614")] public void GenericTypeAsTypePatternInSwitchExpression() { UsingStatement(@"_ = e switch { List<X> => 1, List<Y> => 2, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.TypePattern); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "List"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.TypePattern); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "List"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Y"); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchExpression_PredefinedType() { UsingStatement(@"_ = e switch { int? => 1 };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchStatement_PredefinedType() { UsingStatement(@"switch(a) { case int?: break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchExpression_PredefinedType_Parenthesized() { UsingStatement(@"_ = e switch { (int?) => 1 };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchStatement_PredefinedType_Parenthesized() { UsingStatement(@"switch(a) { case (int?): break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchExpression() { UsingStatement(@"_ = e switch { a? => 1 };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchStatement() { UsingStatement(@"switch(a) { case a?: break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchExpression_Parenthesized() { UsingStatement(@"_ = e switch { (a?) => 1 };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchStatement_Parenthesized() { UsingStatement(@"switch(a) { case (a?): break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ConditionalAsConstantPatternInSwitchExpression() { UsingStatement(@"_ = e switch { (a?x:y) => 1 };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void ConditionalAsConstantPatternInSwitchStatement() { UsingStatement(@"switch(a) { case a?x:y: break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ConditionalAsConstantPatternInSwitchStatement_Parenthesized() { UsingStatement(@"switch(a) { case (a?x:y): break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } 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 System; using System.Text; 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 { [CompilerTrait(CompilerFeature.Patterns)] public class PatternParsingTests : ParsingTests { private new void UsingStatement(string text, params DiagnosticDescription[] expectedErrors) { UsingStatement(text, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8), expectedErrors); } public PatternParsingTests(ITestOutputHelper output) : base(output) { } [Fact] public void CasePatternVersusFeatureFlag() { var test = @" class C { public static void Main(string[] args) { switch ((int) args[0][0]) { case 1: case 2 when args.Length == 2: case 1<<2: case string s: default: break; } bool b = args[0] is string s; } } "; CreateCompilation(test, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)).VerifyDiagnostics( // (9,13): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater. // case 2 when args.Length == 2: Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "case 2 when args.Length == 2:").WithArguments("pattern matching", "7.0").WithLocation(9, 13), // (11,13): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater. // case string s: Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "case string s:").WithArguments("pattern matching", "7.0").WithLocation(11, 13), // (15,18): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater. // bool b = args[0] is string s; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "args[0] is string s").WithArguments("pattern matching", "7.0").WithLocation(15, 18), // (11,18): error CS8121: An expression of type 'int' cannot be handled by a pattern of type 'string'. // case string s: Diagnostic(ErrorCode.ERR_PatternWrongType, "string").WithArguments("int", "string").WithLocation(11, 18), // (11,25): error CS0136: A local or parameter named 's' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case string s: Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "s").WithArguments("s").WithLocation(11, 25) ); } [Fact] public void ThrowExpression_Good() { var test = @"using System; class C { public static void Sample(bool b, string s) { void NeverReturnsFunction() => throw new NullReferenceException(); int x = b ? throw new NullReferenceException() : 1; x = b ? 2 : throw new NullReferenceException(); s = s ?? throw new NullReferenceException(); NeverReturnsFunction(); throw new NullReferenceException() ?? throw new NullReferenceException() ?? throw null; } public static void NeverReturns() => throw new NullReferenceException(); }"; CreateCompilation(test).VerifyDiagnostics(); CreateCompilation(test, parseOptions: TestOptions.Regular6).VerifyDiagnostics( // (6,14): error CS8059: Feature 'local functions' is not available in C# 6. Please use language version 7.0 or greater. // void NeverReturnsFunction() => throw new NullReferenceException(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "NeverReturnsFunction").WithArguments("local functions", "7.0").WithLocation(6, 14), // (6,40): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // void NeverReturnsFunction() => throw new NullReferenceException(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw new NullReferenceException()").WithArguments("throw expression", "7.0").WithLocation(6, 40), // (7,21): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // int x = b ? throw new NullReferenceException() : 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw new NullReferenceException()").WithArguments("throw expression", "7.0").WithLocation(7, 21), // (8,21): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // x = b ? 2 : throw new NullReferenceException(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw new NullReferenceException()").WithArguments("throw expression", "7.0").WithLocation(8, 21), // (9,18): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // s = s ?? throw new NullReferenceException(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw new NullReferenceException()").WithArguments("throw expression", "7.0").WithLocation(9, 18), // (11,47): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // throw new NullReferenceException() ?? throw new NullReferenceException() ?? throw null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw new NullReferenceException() ?? throw null").WithArguments("throw expression", "7.0").WithLocation(11, 47), // (11,85): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // throw new NullReferenceException() ?? throw new NullReferenceException() ?? throw null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw null").WithArguments("throw expression", "7.0").WithLocation(11, 85), // (13,42): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // public static void NeverReturns() => throw new NullReferenceException(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw new NullReferenceException()").WithArguments("throw expression", "7.0").WithLocation(13, 42) ); } [Fact] public void ThrowExpression_Bad() { var test = @"using System; class C { public static void Sample(bool b, string s) { // throw expression at wrong precedence s = s + throw new NullReferenceException(); if (b || throw new NullReferenceException()) { } // throw expression where not permitted var z = from x in throw new NullReferenceException() select x; M(throw new NullReferenceException()); throw throw null; (int, int) w = (1, throw null); return throw null; } static void M(string s) {} }"; CreateCompilationWithMscorlib46(test).VerifyDiagnostics( // (7,17): error CS1525: Invalid expression term 'throw' // s = s + throw new NullReferenceException(); Diagnostic(ErrorCode.ERR_InvalidExprTerm, "throw new NullReferenceException()").WithArguments("throw").WithLocation(7, 17), // (8,18): error CS1525: Invalid expression term 'throw' // if (b || throw new NullReferenceException()) { } Diagnostic(ErrorCode.ERR_InvalidExprTerm, "throw new NullReferenceException()").WithArguments("throw").WithLocation(8, 18), // (11,27): error CS8115: A throw expression is not allowed in this context. // var z = from x in throw new NullReferenceException() select x; Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(11, 27), // (12,11): error CS8115: A throw expression is not allowed in this context. // M(throw new NullReferenceException()); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(12, 11), // (13,15): error CS8115: A throw expression is not allowed in this context. // throw throw null; Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(13, 15), // (14,9): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // (int, int) w = (1, throw null); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(int, int)").WithArguments("System.ValueTuple`2").WithLocation(14, 9), // (14,28): error CS8115: A throw expression is not allowed in this context. // (int, int) w = (1, throw null); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(14, 28), // (14,24): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // (int, int) w = (1, throw null); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(1, throw null)").WithArguments("System.ValueTuple`2").WithLocation(14, 24), // (15,16): error CS8115: A throw expression is not allowed in this context. // return throw null; Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(15, 16), // (14,9): warning CS0162: Unreachable code detected // (int, int) w = (1, throw null); Diagnostic(ErrorCode.WRN_UnreachableCode, "(").WithLocation(14, 9) ); } [Fact] public void ThrowExpression() { UsingTree(@" class C { int x = y ?? throw null; }", 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.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.CoalesceExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.QuestionQuestionToken); N(SyntaxKind.ThrowExpression); { N(SyntaxKind.ThrowKeyword); N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(14785, "https://github.com/dotnet/roslyn/issues/14785")] public void IsPatternPrecedence_1() { UsingNode(SyntaxFactory.ParseExpression("A is B < C, D > [ ]")); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "B"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "D"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } EOF(); } [Fact, WorkItem(14785, "https://github.com/dotnet/roslyn/issues/14785")] public void IsPatternPrecedence_2() { UsingNode(SyntaxFactory.ParseExpression("A < B > C")); N(SyntaxKind.GreaterThanExpression); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.GreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } EOF(); } [Fact, WorkItem(14785, "https://github.com/dotnet/roslyn/issues/14785")] public void IsPatternPrecedence_3() { SyntaxFactory.ParseExpression("e is A<B> && e").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("e is A<B> || e").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("e is A<B> ^ e").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("e is A<B> | e").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("e is A<B> & e").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("e is A<B>[]").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("new { X = e is A<B> }").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("e is A<B>").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("(item is Dictionary<string, object>[])").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("A is B < C, D > [ ]").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("A is B < C, D > [ ] E").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("A < B > C").GetDiagnostics().Verify(); } [Fact] public void QueryContextualPatternVariable_01() { SyntaxFactory.ParseExpression("from s in a where s is string where s.Length > 1 select s").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("M(out int? x)").GetDiagnostics().Verify(); } [Fact] public void TypeDisambiguation_01() { UsingStatement(@" var r = from s in a where s is X<T> // should disambiguate as a type here where M(s) select s as X<T>;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "r"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.QueryExpression); { N(SyntaxKind.FromClause); { N(SyntaxKind.FromKeyword); N(SyntaxKind.IdentifierToken, "s"); N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.QueryBody); { N(SyntaxKind.WhereClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "s"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "X"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } } } N(SyntaxKind.WhereClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "s"); } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.SelectClause); { N(SyntaxKind.SelectKeyword); N(SyntaxKind.AsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "s"); } N(SyntaxKind.AsKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "X"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } } } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypeDisambiguation_02() { UsingStatement(@" var r = a is X<T> // should disambiguate as a type here is bool;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "r"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "X"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.IsKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.BoolKeyword); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypeDisambiguation_03() { UsingStatement(@" var r = a is X<T> // should disambiguate as a type here > Z;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "r"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.GreaterThanExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "X"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.GreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Z"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence00() { UsingExpression("A is B << C"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence01() { UsingExpression("A is 1 << 2"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence02() { UsingExpression("A is null < B"); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence02b() { UsingExpression("A is B < C"); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence03() { UsingExpression("A is null == B"); N(SyntaxKind.EqualsExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } N(SyntaxKind.EqualsEqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence04() { UsingExpression("A is null & B"); N(SyntaxKind.BitwiseAndExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } N(SyntaxKind.AmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence05() { UsingExpression("A is null && B"); N(SyntaxKind.LogicalAndExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } N(SyntaxKind.AmpersandAmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence05b() { UsingExpression("A is null || B"); N(SyntaxKind.LogicalOrExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } N(SyntaxKind.BarBarToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence06() { UsingStatement(@"switch (e) { case 1 << 2: case B << C: case null < B: case null == B: case null & B: case null && B: break; }"); 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.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.EqualsExpression); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } N(SyntaxKind.EqualsEqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.BitwiseAndExpression); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } N(SyntaxKind.AmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.LogicalAndExpression); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } N(SyntaxKind.AmpersandAmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(21515, "https://github.com/dotnet/roslyn/issues/21515")] public void PatternExpressionPrecedence07() { // This should actually be error-free. UsingStatement(@"switch (array) { case KeyValuePair<string, DateTime>[] pairs1: case KeyValuePair<String, DateTime>[] pairs2: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "array"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "KeyValuePair"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "DateTime"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "pairs1"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "KeyValuePair"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "String"); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "DateTime"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "pairs2"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_01() { UsingExpression("A is B***", // (1,10): error CS1733: Expected expression // A is B*** Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(1, 10) ); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } } } } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_01b() { UsingExpression("A is B*** C"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } } } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_02() { UsingExpression("A is B***[]"); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_03() { UsingExpression("A is B***[] C"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "C"); } } } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_04() { UsingExpression("(B*** C, D)"); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "D"); } } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_04b() { UsingExpression("(B*** C)"); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_05() { UsingExpression("(B***[] C, D)"); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "C"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "D"); } } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_06() { UsingExpression("(D, B*** C)"); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "D"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_07() { UsingExpression("(D, B***[] C)"); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "D"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "C"); } } } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_08() { UsingStatement("switch (e) { case B*** C: break; }"); 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.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_09() { UsingStatement("switch (e) { case B***[] C: break; }"); 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.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "C"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void NameofInPattern_01() { // This should actually be error-free, because `nameof` might be a type. UsingStatement(@"switch (e) { case nameof n: ; }"); 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.IdentifierName); { N(SyntaxKind.IdentifierToken, "nameof"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "n"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void NameofInPattern_02() { // This should actually be error-free; a constant pattern with nameof(n) as the constant. UsingStatement(@"switch (e) { case nameof(n): ; }"); 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.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "nameof"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "n"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void NameofInPattern_03() { // This should actually be error-free; a constant pattern with nameof(n) as the constant. UsingStatement(@"switch (e) { case nameof(n) when true: ; }"); 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.ConstantPattern); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "nameof"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "n"); } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.WhenClause); { N(SyntaxKind.WhenKeyword); N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParenthesizedExpression_01() { UsingStatement(@"switch (e) { case (((3))): ; }"); 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.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParenthesizedExpression_02() { UsingStatement(@"switch (e) { case (((3))) when true: ; }"); 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.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.WhenClause); { N(SyntaxKind.WhenKeyword); N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParenthesizedExpression_03() { var expect = new[] { // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case (x: ((3))): ; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "(x: ((3)))").WithArguments("recursive patterns", "8.0").WithLocation(1, 19) }; UsingStatement(@"switch (e) { case (x: ((3))): ; }", TestOptions.RegularWithoutRecursivePatterns, expect); checkNodes(); UsingStatement(@"switch (e) { case (x: ((3))): ; }", TestOptions.Regular8); checkNodes(); void checkNodes() { 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.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } } [Fact] public void ParenthesizedExpression_04() { UsingStatement(@"switch (e) { case (((x: 3))): ; }", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8370: Feature 'parenthesized pattern' is not available in C# 7.3. Please use language version 9.0 or greater. // switch (e) { case (((x: 3))): ; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "(((x: 3)))").WithArguments("parenthesized pattern", "9.0").WithLocation(1, 19), // (1,20): error CS8370: Feature 'parenthesized pattern' is not available in C# 7.3. Please use language version 9.0 or greater. // switch (e) { case (((x: 3))): ; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "((x: 3))").WithArguments("parenthesized pattern", "9.0").WithLocation(1, 20) ); 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.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void RecursivePattern_01() { UsingStatement(@"switch (e) { case T(X: 3, Y: 4){L: 5} p: ; }", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case T(X: 3, Y: 4){L: 5} p: ; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "T(X: 3, Y: 4){L: 5} p").WithArguments("recursive patterns", "8.0").WithLocation(1, 19) ); 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.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Y"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "L"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "p"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void BrokenPattern_06() { UsingStatement(@"switch (e) { case (: ; }", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case (: ; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "(: ").WithArguments("recursive patterns", "8.0").WithLocation(1, 19), // (1,20): error CS1001: Identifier expected // switch (e) { case (: ; } Diagnostic(ErrorCode.ERR_IdentifierExpected, ":").WithLocation(1, 20), // (1,22): error CS1026: ) expected // switch (e) { case (: ; } Diagnostic(ErrorCode.ERR_CloseParenExpected, ";").WithLocation(1, 22), // (1,22): error CS1003: Syntax error, ':' expected // switch (e) { case (: ; } Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(":", ";").WithLocation(1, 22) ); 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.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void BrokenPattern_07() { UsingStatement(@"switch (e) { case (", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case ( Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "(").WithArguments("recursive patterns", "8.0").WithLocation(1, 19), // (1,20): error CS1026: ) expected // switch (e) { case ( Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(1, 20), // (1,20): error CS1003: Syntax error, ':' expected // switch (e) { case ( Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments(":", "").WithLocation(1, 20), // (1,20): error CS1513: } expected // switch (e) { case ( Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(1, 20) ); 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.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); } } M(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParenthesizedExpression_07() { UsingStatement(@"switch (e) { case (): }", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case (): } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "()").WithArguments("recursive patterns", "8.0").WithLocation(1, 19)); 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.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.ColonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void BrokenPattern_08() { UsingStatement(@"switch (e) { case", // (1,18): error CS1733: Expected expression // switch (e) { case Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(1, 18), // (1,18): error CS1003: Syntax error, ':' expected // switch (e) { case Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments(":", "").WithLocation(1, 18), // (1,18): error CS1513: } expected // switch (e) { case Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(1, 18) ); 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.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.ColonToken); } } M(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParenthesizedExpression_05() { UsingStatement(@"switch (e) { case (x: ): ; }", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case (x: ): ; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "(x: )").WithArguments("recursive patterns", "8.0").WithLocation(1, 19), // (1,23): error CS8504: Pattern missing // switch (e) { case (x: ): ; } Diagnostic(ErrorCode.ERR_MissingPattern, ")").WithLocation(1, 23) ); 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.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); } M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void EmptySwitchExpression() { UsingExpression("1 switch {}", TestOptions.RegularWithoutRecursivePatterns, // (1,1): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // 1 switch {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1 switch {}").WithArguments("recursive patterns", "8.0").WithLocation(1, 1) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpression01() { UsingExpression("1 switch {a => b, c => d}", TestOptions.RegularWithoutRecursivePatterns, // (1,1): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // 1 switch {a => b, c => d} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1 switch {a => b, c => d}").WithArguments("recursive patterns", "8.0").WithLocation(1, 1) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpression02() { UsingExpression("1 switch { a?b:c => d }", TestOptions.RegularWithoutRecursivePatterns, // (1,1): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // 1 switch { a?b:c => d } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1 switch { a?b:c => d }").WithArguments("recursive patterns", "8.0").WithLocation(1, 1), // (1,13): error CS1003: Syntax error, '=>' expected // 1 switch { a?b:c => d } Diagnostic(ErrorCode.ERR_SyntaxError, "?").WithArguments("=>", "?").WithLocation(1, 13), // (1,13): error CS1525: Invalid expression term '?' // 1 switch { a?b:c => d } Diagnostic(ErrorCode.ERR_InvalidExprTerm, "?").WithArguments("?").WithLocation(1, 13) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } M(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.ConditionalExpression); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); N(SyntaxKind.SimpleLambdaExpression); { N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpression03() { UsingExpression("1 switch { (a, b, c) => d }", TestOptions.RegularWithoutRecursivePatterns, // (1,1): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // 1 switch { (a, b, c) => d } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1 switch { (a, b, c) => d }").WithArguments("recursive patterns", "8.0").WithLocation(1, 1) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void BrokenRecursivePattern01() { // This put the parser into an infinite loop at one time. The precise diagnostics and nodes // are not as important as the fact that it terminates. UsingStatement("switch (e) { case T( : Q x = n; break; } ", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case T( : Q x = n; break; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "T( : Q x = n").WithArguments("recursive patterns", "8.0").WithLocation(1, 19), // (1,22): error CS1001: Identifier expected // switch (e) { case T( : Q x = n; break; } Diagnostic(ErrorCode.ERR_IdentifierExpected, ":").WithLocation(1, 22), // (1,28): error CS1003: Syntax error, ',' expected // switch (e) { case T( : Q x = n; break; } Diagnostic(ErrorCode.ERR_SyntaxError, "=").WithArguments(",", "=").WithLocation(1, 28), // (1,30): error CS1003: Syntax error, ',' expected // switch (e) { case T( : Q x = n; break; } Diagnostic(ErrorCode.ERR_SyntaxError, "n").WithArguments(",", "").WithLocation(1, 30), // (1,31): error CS1026: ) expected // switch (e) { case T( : Q x = n; break; } Diagnostic(ErrorCode.ERR_CloseParenExpected, ";").WithLocation(1, 31), // (1,31): error CS1003: Syntax error, ':' expected // switch (e) { case T( : Q x = n; break; } Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(":", ";").WithLocation(1, 31) ); 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.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Q"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "n"); } } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(26000, "https://github.com/dotnet/roslyn/issues/26000")] public void VarIsContextualKeywordForPatterns01() { UsingStatement("switch (e) { case var: break; }"); 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.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(26000, "https://github.com/dotnet/roslyn/issues/26000")] public void VarIsContextualKeywordForPatterns02() { UsingStatement("if (e is var) {}"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact, WorkItem(26000, "https://github.com/dotnet/roslyn/issues/26000")] public void WhenAsPatternVariable01() { UsingStatement("switch (e) { case var when: break; }", // (1,27): error CS1525: Invalid expression term ':' // switch (e) { case var when: break; } Diagnostic(ErrorCode.ERR_InvalidExprTerm, ":").WithArguments(":").WithLocation(1, 27) ); 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.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } } N(SyntaxKind.WhenClause); { N(SyntaxKind.WhenKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(26000, "https://github.com/dotnet/roslyn/issues/26000")] public void WhenAsPatternVariable02() { UsingStatement("switch (e) { case K when: break; }", // (1,25): error CS1525: Invalid expression term ':' // switch (e) { case K when: break; } Diagnostic(ErrorCode.ERR_InvalidExprTerm, ":").WithArguments(":").WithLocation(1, 25) ); 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.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "K"); } } N(SyntaxKind.WhenClause); { N(SyntaxKind.WhenKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact(Skip = "This is not a reliable test, and its failure modes are hard to capture. But it is helpful to run by hand to find parser issues.")] public void ParseFuzz() { Random random = new Random(); for (int i = 0; i < 4000; i++) { string source = $"class C{{void M(){{switch(e){{case {makePattern0()}:T v = e;}}}}}}"; try { Parse(source, options: TestOptions.RegularWithRecursivePatterns); for (int j = 0; j < 30; j++) { int k1 = random.Next(source.Length); int k2 = random.Next(source.Length); string source2 = source.Substring(0, k1) + source.Substring(k2); Parse(source2, options: TestOptions.RegularWithRecursivePatterns); } } catch (StackOverflowException) { Console.WriteLine("Failed on \"" + source + "\""); Assert.True(false, source); } catch (OutOfMemoryException) { Console.WriteLine("Failed on \"" + source + "\""); Assert.True(false, source); } } return; string makeProps(int maxDepth, bool needNames) { int nProps = random.Next(maxDepth); var builder = new StringBuilder(); for (int i = 0; i < nProps; i++) { if (i != 0) builder.Append(", "); if (needNames || random.Next(5) == 0) builder.Append("N: "); builder.Append(makePattern(maxDepth - 1)); } return builder.ToString(); } string makePattern(int maxDepth) { if (maxDepth <= 0 || random.Next(6) == 0) { switch (random.Next(4)) { case 0: return "_"; case 1: return "1"; case 2: return "T x"; default: return "var y"; } } else { // recursive pattern while (true) { bool nameType = random.Next(2) == 0; bool parensPart = random.Next(2) == 0; bool propsPart = random.Next(2) == 0; bool name = random.Next(2) == 0; if (!parensPart && !propsPart && !(nameType && name)) continue; return $"{(nameType ? "N" : "")} {(parensPart ? $"({makeProps(maxDepth, false)})" : "")} {(propsPart ? $"{{ {makeProps(maxDepth, true)} }}" : "")} {(name ? "n" : "")}"; } } } string makePattern0() => makePattern(random.Next(6)); } [Fact] public void ArrayOfTupleType01() { UsingStatement("if (o is (int, int)[]) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { 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.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType02() { UsingStatement("if (o is (int a, int b)[]) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType03() { UsingStatement("if (o is (int, int)[] q) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { 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.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType04() { UsingStatement("if (o is (int a, int b)[] q) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType05() { UsingStatement("if (o is (Int, Int)[]) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType06() { UsingStatement("if (o is (Int a, Int b)[]) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType07() { UsingStatement("if (o is (Int, Int)[] q) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType08() { UsingStatement("if (o is (Int a, Int b)[] q) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType09() { UsingStatement("if (o is (S.Int, S.Int)[]) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType10() { UsingStatement("if (o is (S.Int a, S.Int b)[]) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType11() { UsingStatement("if (o is (S.Int, S.Int)[] q) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType12() { UsingStatement("if (o is (S.Int a, S.Int b)[] q) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType13() { UsingStatement("switch (o) { case (int, int)[] q: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { 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.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ArrayOfTupleType14() { UsingStatement("switch (o) { case (int a, int b)[] q: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ArrayOfTupleType15() { UsingStatement("switch (o) { case (Int, Int)[] q: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ArrayOfTupleType16() { UsingStatement("switch (o) { case (Int a, Int b)[] q: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ArrayOfTupleType17() { UsingStatement("switch (o) { case (S.Int, S.Int)[] q: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ArrayOfTupleType18() { UsingStatement("switch (o) { case (S.Int a, S.Int b)[] q: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void RecursivePattern_00() { UsingStatement("var x = o is Type (Param: 3, Param2: 4) { Prop : 3 } x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_02() { UsingStatement("var x = o is (Param: 3, Param2: 4) { Prop : 3 } x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_03() { UsingStatement("var x = o is Type { Prop : 3 } x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_04() { UsingStatement("var x = o is { Prop : 3 } x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_05() { UsingStatement("var x = o is Type (Param: 3, Param2: 4) x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_06() { UsingStatement("var x = o is (Param: 3, Param2: 4) x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_07() { UsingStatement("var x = o is Type x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_08() { UsingStatement("var x = o is Type (Param: 3, Param2: 4) { Prop : 3 };"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_09() { UsingStatement("var x = o is (Param: 3, Param2: 4) { Prop : 3 };"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_10() { UsingStatement("var x = o is Type { Prop : 3 };"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_11() { UsingStatement("var x = o is { Prop : 3 };"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_12() { UsingStatement("var x = o is Type (Param: 3, Param2: 4);"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_13() { UsingStatement("var x = o is (Param: 3, Param2: 4);"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void ParenthesizedExpressionOfSwitchExpression() { UsingStatement("Console.Write((t) switch {var x => x});"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Console"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Write"); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.SwitchExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "t"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.VarPattern); { N(SyntaxKind.VarKeyword, "var"); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void DiscardInSwitchExpression() { UsingExpression("e switch { _ => 1 }"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.DiscardPattern); { N(SyntaxKind.UnderscoreToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void DiscardInSwitchStatement_01a() { UsingStatement("switch(e) { case _: break; }"); 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.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void DiscardInSwitchStatement_01b() { UsingStatement("switch(e) { case _: break; }", TestOptions.Regular7_3); 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.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void DiscardInSwitchStatement_02() { UsingStatement("switch(e) { case _ when true: break; }"); 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.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } } N(SyntaxKind.WhenClause); { N(SyntaxKind.WhenKeyword); N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void DiscardInRecursivePattern_01() { UsingExpression("e is (_, _)"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.DiscardPattern); { N(SyntaxKind.UnderscoreToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.DiscardPattern); { N(SyntaxKind.UnderscoreToken); } } N(SyntaxKind.CloseParenToken); } } } EOF(); } [Fact] public void DiscardInRecursivePattern_02() { UsingExpression("e is { P: _ }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "P"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.DiscardPattern); { N(SyntaxKind.UnderscoreToken); } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void NotDiscardInIsTypeExpression() { UsingExpression("e is _"); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } } EOF(); } [Fact] public void ShortTuplePatterns() { UsingExpression( @"e switch { var () => 1, () => 2, var (x) => 3, (1) _ => 4, (1) x => 5, (1) {} => 6, (Item1: 1) => 7, C(1) => 8 }", expectedErrors: new DiagnosticDescription[0]); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.VarPattern); { N(SyntaxKind.VarKeyword); N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.VarPattern); { N(SyntaxKind.VarKeyword); N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.DiscardDesignation); { N(SyntaxKind.UnderscoreToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "6"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Item1"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "7"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "8"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void NestedShortTuplePatterns() { UsingExpression( @"e switch { {X: var ()} => 1, {X: ()} => 2, {X: var (x)} => 3, {X: (1) _} => 4, {X: (1) x} => 5, {X: (1) {}} => 6, {X: (Item1: 1)} => 7, {X: C(1)} => 8 }", expectedErrors: new DiagnosticDescription[0]); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.VarPattern); { N(SyntaxKind.VarKeyword); N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.VarPattern); { N(SyntaxKind.VarKeyword); N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.DiscardDesignation); { N(SyntaxKind.UnderscoreToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "6"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Item1"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "7"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "8"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void IsNullableArray01() { // OK, this means `(o is A[]) ? b : c` because nullable types are not permitted for a pattern's type UsingExpression("o is A[] ? b : c"); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } EOF(); } [Fact] public void IsNullableArray02() { // error: 'cannot use nullable reference type for a pattern' or 'expected :' UsingExpression("o is A[] ? b && c", // (1,18): error CS1003: Syntax error, ':' expected // o is A[] ? b && c Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments(":", "").WithLocation(1, 18), // (1,18): error CS1733: Expected expression // o is A[] ? b && c Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(1, 18) ); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.QuestionToken); N(SyntaxKind.LogicalAndExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.AmpersandAmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } EOF(); } [Fact] public void IsNullableArray03() { // OK, this means `(o is A[][]) ? b : c` UsingExpression("o is A[][] ? b : c"); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } EOF(); } [Fact] public void IsNullableType01() { UsingExpression("o is A ? b : c"); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } EOF(); } [Fact] public void IsNullableType02() { UsingExpression("o is A? ? b : c"); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } EOF(); } [Fact, WorkItem(32161, "https://github.com/dotnet/roslyn/issues/32161")] public void ParenthesizedSwitchCase() { var text = @" switch (e) { case (0): break; case (-1): break; case (+2): break; case (~3): break; } "; foreach (var langVersion in new[] { LanguageVersion.CSharp6, LanguageVersion.CSharp7, LanguageVersion.CSharp8 }) { UsingStatement(text, options: CSharpParseOptions.Default.WithLanguageVersion(langVersion)); 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.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.UnaryMinusExpression); { N(SyntaxKind.MinusToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.UnaryPlusExpression); { N(SyntaxKind.PlusToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.BitwiseNotExpression); { N(SyntaxKind.TildeToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } } [Fact] public void TrailingCommaInSwitchExpression_01() { UsingExpression("1 switch { 1 => 2, }"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void TrailingCommaInSwitchExpression_02() { UsingExpression("1 switch { , }", // (1,12): error CS8504: Pattern missing // 1 switch { , } Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 12), // (1,12): error CS1003: Syntax error, '=>' expected // 1 switch { , } Diagnostic(ErrorCode.ERR_SyntaxError, ",").WithArguments("=>", ",").WithLocation(1, 12), // (1,12): error CS1525: Invalid expression term ',' // 1 switch { , } Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(1, 12) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); M(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.EqualsGreaterThanToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void TrailingCommaInPropertyPattern_01() { UsingExpression("e is { X: 3, }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void TrailingCommaInPropertyPattern_02() { UsingExpression("e is { , }", // (1,8): error CS8504: Pattern missing // e is { , } Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 8) ); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); M(SyntaxKind.Subpattern); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void TrailingCommaInPositionalPattern_01() { UsingExpression("e is ( X: 3, )", // (1,14): error CS8504: Pattern missing // e is ( X: 3, ) Diagnostic(ErrorCode.ERR_MissingPattern, ")").WithLocation(1, 14) ); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); M(SyntaxKind.Subpattern); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.CloseParenToken); } } } EOF(); } [Fact] public void TrailingCommaInPositionalPattern_02() { UsingExpression("e is ( , )", // (1,8): error CS8504: Pattern missing // e is ( , ) Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 8), // (1,10): error CS8504: Pattern missing // e is ( , ) Diagnostic(ErrorCode.ERR_MissingPattern, ")").WithLocation(1, 10) ); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.Subpattern); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.CommaToken); M(SyntaxKind.Subpattern); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.CloseParenToken); } } } EOF(); } [Fact] public void ExtraCommaInSwitchExpression() { UsingExpression("e switch { 1 => 2,, }", // (1,19): error CS8504: Pattern missing // e switch { 1 => 2,, } Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 19), // (1,19): error CS1003: Syntax error, '=>' expected // e switch { 1 => 2,, } Diagnostic(ErrorCode.ERR_SyntaxError, ",").WithArguments("=>", ",").WithLocation(1, 19), // (1,19): error CS1525: Invalid expression term ',' // e switch { 1 => 2,, } Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(1, 19) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); M(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.EqualsGreaterThanToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ExtraCommaInPropertyPattern() { UsingExpression("e is { A: 1,, }", // (1,13): error CS8504: Pattern missing // e is { A: 1,, } Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 13) ); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CommaToken); M(SyntaxKind.Subpattern); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact, WorkItem(33054, "https://github.com/dotnet/roslyn/issues/33054")] public void ParenthesizedExpressionInPattern_01() { UsingStatement( @"switch (e) { case (('C') << 24) + (('g') << 16) + (('B') << 8) + 'I': break; }"); 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.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.AddExpression); { N(SyntaxKind.AddExpression); { N(SyntaxKind.AddExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "24"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PlusToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "16"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.PlusToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "8"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.PlusToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(33208, "https://github.com/dotnet/roslyn/issues/33208")] public void ParenthesizedExpressionInPattern_02() { UsingStatement( @"switch (e) { case ((2) + (2)): break; }"); 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.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.AddExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PlusToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(33208, "https://github.com/dotnet/roslyn/issues/33208")] public void ParenthesizedExpressionInPattern_03() { UsingStatement( @"switch (e) { case ((2 + 2) - 2): break; }"); 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.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SubtractExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.AddExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.PlusToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.MinusToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(33208, "https://github.com/dotnet/roslyn/issues/33208")] public void ParenthesizedExpressionInPattern_04() { UsingStatement( @"switch (e) { case (2) | (2): break; }"); 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.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.BitwiseOrExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.BarToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(33208, "https://github.com/dotnet/roslyn/issues/33208")] public void ParenthesizedExpressionInPattern_05() { UsingStatement( @"switch (e) { case ((2 << 2) | 2): break; }"); 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.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.BitwiseOrExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.BarToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ChainedSwitchExpression_01() { UsingExpression("1 switch { 1 => 2 } switch { 2 => 3 }"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ChainedSwitchExpression_02() { UsingExpression("a < b switch { 1 => 2 } < c switch { 2 => 3 }"); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.LessThanToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void SwitchExpressionPrecedence_01() { UsingExpression("a < b switch { true => 1 }"); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void SwitchExpressionPrecedence_02() { // The left-hand-side of a switch is equality, which binds more loosely than the `switch`, // so `b` ends up on the left of the `switch` and the `a ==` expression has a switch on the right. UsingExpression("a == b switch { true => 1 }"); N(SyntaxKind.EqualsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.EqualsEqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void SwitchExpressionPrecedence_03() { UsingExpression("a * b switch {}"); N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void SwitchExpressionPrecedence_04() { UsingExpression("a + b switch {}"); N(SyntaxKind.AddExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.PlusToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void SwitchExpressionPrecedence_05() { UsingExpression("-a switch {}"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.UnaryMinusExpression); { N(SyntaxKind.MinusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_06() { UsingExpression("(Type)a switch {}"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_07() { UsingExpression("(Type)a++ switch {}"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.PostIncrementExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.PlusPlusToken); } } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_08() { UsingExpression("+a switch {}"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.UnaryPlusExpression); { N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_09() { UsingExpression("a switch {}.X", // (1,1): error CS1073: Unexpected token '.' // a switch {}.X Diagnostic(ErrorCode.ERR_UnexpectedToken, "a switch {}").WithArguments(".").WithLocation(1, 1)); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_10() { UsingExpression("a switch {}[i]", // (1,1): error CS1073: Unexpected token '[' // a switch {}[i] Diagnostic(ErrorCode.ERR_UnexpectedToken, "a switch {}").WithArguments("[").WithLocation(1, 1)); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_11() { UsingExpression("a switch {}(b)", // (1,1): error CS1073: Unexpected token '(' // a switch {}(b) Diagnostic(ErrorCode.ERR_UnexpectedToken, "a switch {}").WithArguments("(").WithLocation(1, 1)); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_12() { UsingExpression("a switch {}!", // (1,1): error CS1073: Unexpected token '!' // a switch {}! Diagnostic(ErrorCode.ERR_UnexpectedToken, "a switch {}").WithArguments("!").WithLocation(1, 1)); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(32749, "https://github.com/dotnet/roslyn/issues/32749")] public void BrokenSwitchExpression_01() { UsingExpression("(e switch {)", // (1,12): error CS1513: } expected // (e switch {) Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(1, 12) ); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(32749, "https://github.com/dotnet/roslyn/issues/32749")] public void BrokenSwitchExpression_02() { UsingExpression("(e switch {,)", // (1,12): error CS8504: Pattern missing // (e switch {,) Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 12), // (1,12): error CS1003: Syntax error, '=>' expected // (e switch {,) Diagnostic(ErrorCode.ERR_SyntaxError, ",").WithArguments("=>", ",").WithLocation(1, 12), // (1,12): error CS1525: Invalid expression term ',' // (e switch {,) Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(1, 12), // (1,13): error CS1513: } expected // (e switch {,) Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(1, 13) ); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); M(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.EqualsGreaterThanToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(32749, "https://github.com/dotnet/roslyn/issues/32749")] public void BrokenSwitchExpression_03() { UsingExpression("e switch {,", // (1,11): error CS8504: Pattern missing // e switch {, Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 11), // (1,11): error CS1003: Syntax error, '=>' expected // e switch {, Diagnostic(ErrorCode.ERR_SyntaxError, ",").WithArguments("=>", ",").WithLocation(1, 11), // (1,11): error CS1525: Invalid expression term ',' // e switch {, Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(1, 11), // (1,12): error CS1513: } expected // e switch {, Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(1, 12) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); M(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.EqualsGreaterThanToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); M(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(33675, "https://github.com/dotnet/roslyn/issues/33675")] public void ParenthesizedNamedConstantPatternInSwitchExpression() { UsingExpression("e switch { (X) => 1 }"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(34482, "https://github.com/dotnet/roslyn/issues/34482")] public void SwitchCaseArmErrorRecovery_01() { UsingExpression("e switch { 1 => 1; 2 => 2 }", // (1,18): error CS1003: Syntax error, ',' expected // e switch { 1 => 1; 2 => 2 } Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(",", ";").WithLocation(1, 18) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } M(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(34482, "https://github.com/dotnet/roslyn/issues/34482")] public void SwitchCaseArmErrorRecovery_02() { UsingExpression("e switch { 1 => 1, 2 => 2; }", // (1,26): error CS1003: Syntax error, ',' expected // e switch { 1 => 1, 2 => 2; } Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(",", ";").WithLocation(1, 26) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } M(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(38121, "https://github.com/dotnet/roslyn/issues/38121")] public void GenericPropertyPattern() { UsingExpression("e is A<B> {}"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact, WorkItem(10492, "https://github.com/dotnet/roslyn/issues/10492")] public void PrecedenceInversionWithDeclarationPattern() { UsingExpression("o is C c + d", // (1,10): error CS1073: Unexpected token '+' // o is C c + d Diagnostic(ErrorCode.ERR_UnexpectedToken, "+").WithArguments("+").WithLocation(1, 10) ); N(SyntaxKind.AddExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "c"); } } } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } EOF(); } [Fact, WorkItem(10492, "https://github.com/dotnet/roslyn/issues/10492")] public void PrecedenceInversionWithRecursivePattern() { UsingExpression("o is {} + d", // (1,9): error CS1073: Unexpected token '+' // o is {} + d Diagnostic(ErrorCode.ERR_UnexpectedToken, "+").WithArguments("+").WithLocation(1, 9) ); N(SyntaxKind.AddExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } EOF(); } [Fact] public void PatternCombinators_01() { UsingStatement("_ = e is a or b;", TestOptions.RegularWithoutPatternCombinators, // (1,10): error CS8400: Feature 'or pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = e is a or b; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "a or b").WithArguments("or pattern", "9.0").WithLocation(1, 10) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void PatternCombinators_02() { UsingStatement("_ = e is a and b;", TestOptions.RegularWithoutPatternCombinators, // (1,10): error CS8400: Feature 'and pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = e is a and b; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "a and b").WithArguments("and pattern", "9.0").WithLocation(1, 10) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void PatternCombinators_03() { UsingStatement("_ = e is not b;", TestOptions.RegularWithoutPatternCombinators, // (1,10): error CS8400: Feature 'not pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = e is not b; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "not b").WithArguments("not pattern", "9.0").WithLocation(1, 10) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.NotPattern); { N(SyntaxKind.NotKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void PatternCombinators_04() { UsingStatement("_ = e is not null;", TestOptions.RegularWithoutPatternCombinators, // (1,10): error CS8400: Feature 'not pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = e is not null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "not null").WithArguments("not pattern", "9.0").WithLocation(1, 10) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.NotPattern); { N(SyntaxKind.NotKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void PatternCombinators_05() { UsingStatement( @"_ = e switch { a or b => 1, c and d => 2, not e => 3, not null => 4, };", TestOptions.RegularWithoutPatternCombinators, // (2,5): error CS8400: Feature 'or pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // a or b => 1, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "a or b").WithArguments("or pattern", "9.0").WithLocation(2, 5), // (3,5): error CS8400: Feature 'and pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // c and d => 2, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "c and d").WithArguments("and pattern", "9.0").WithLocation(3, 5), // (4,5): error CS8400: Feature 'not pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // not e => 3, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "not e").WithArguments("not pattern", "9.0").WithLocation(4, 5), // (5,5): error CS8400: Feature 'not pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // not null => 4, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "not null").WithArguments("not pattern", "9.0").WithLocation(5, 5) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.AndPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.NotPattern); { N(SyntaxKind.NotKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.NotPattern); { N(SyntaxKind.NotKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RelationalPattern_01() { UsingStatement( @"_ = e switch { < 0 => 0, <= 1 => 1, > 2 => 2, >= 3 => 3, == 4 => 4, != 5 => 5, };", TestOptions.RegularWithoutPatternCombinators, // (2,5): error CS8400: Feature 'relational pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // < 0 => 0, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "< 0").WithArguments("relational pattern", "9.0").WithLocation(2, 5), // (3,5): error CS8400: Feature 'relational pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // <= 1 => 1, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "<= 1").WithArguments("relational pattern", "9.0").WithLocation(3, 5), // (4,5): error CS8400: Feature 'relational pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // > 2 => 2, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "> 2").WithArguments("relational pattern", "9.0").WithLocation(4, 5), // (5,5): error CS8400: Feature 'relational pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // >= 3 => 3, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, ">= 3").WithArguments("relational pattern", "9.0").WithLocation(5, 5), // (6,5): error CS8400: Feature 'relational pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // == 4 => 4, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "== 4").WithArguments("relational pattern", "9.0").WithLocation(6, 5), // (7,5): error CS8400: Feature 'relational pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // != 5 => 5, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "!= 5").WithArguments("relational pattern", "9.0").WithLocation(7, 5) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.EqualsEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.ExclamationEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RelationalPatternPrecedence_01() { UsingStatement( @"_ = e switch { < 0 < 0 => 0, == 4 < 4 => 4, != 5 < 5 => 5, };", TestOptions.RegularWithPatternCombinators, // (2,9): error CS1003: Syntax error, '=>' expected // < 0 < 0 => 0, Diagnostic(ErrorCode.ERR_SyntaxError, "<").WithArguments("=>", "<").WithLocation(2, 9), // (2,9): error CS1525: Invalid expression term '<' // < 0 < 0 => 0, Diagnostic(ErrorCode.ERR_InvalidExprTerm, "<").WithArguments("<").WithLocation(2, 9), // (2,13): error CS1003: Syntax error, ',' expected // < 0 < 0 => 0, Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(",", "=>").WithLocation(2, 13), // (2,13): error CS8504: Pattern missing // < 0 < 0 => 0, Diagnostic(ErrorCode.ERR_MissingPattern, "=>").WithLocation(2, 13), // (3,10): error CS1003: Syntax error, '=>' expected // == 4 < 4 => 4, Diagnostic(ErrorCode.ERR_SyntaxError, "<").WithArguments("=>", "<").WithLocation(3, 10), // (3,10): error CS1525: Invalid expression term '<' // == 4 < 4 => 4, Diagnostic(ErrorCode.ERR_InvalidExprTerm, "<").WithArguments("<").WithLocation(3, 10), // (3,14): error CS1003: Syntax error, ',' expected // == 4 < 4 => 4, Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(",", "=>").WithLocation(3, 14), // (3,14): error CS8504: Pattern missing // == 4 < 4 => 4, Diagnostic(ErrorCode.ERR_MissingPattern, "=>").WithLocation(3, 14), // (4,10): error CS1003: Syntax error, '=>' expected // != 5 < 5 => 5, Diagnostic(ErrorCode.ERR_SyntaxError, "<").WithArguments("=>", "<").WithLocation(4, 10), // (4,10): error CS1525: Invalid expression term '<' // != 5 < 5 => 5, Diagnostic(ErrorCode.ERR_InvalidExprTerm, "<").WithArguments("<").WithLocation(4, 10), // (4,14): error CS1003: Syntax error, ',' expected // != 5 < 5 => 5, Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(",", "=>").WithLocation(4, 14), // (4,14): error CS8504: Pattern missing // != 5 < 5 => 5, Diagnostic(ErrorCode.ERR_MissingPattern, "=>").WithLocation(4, 14) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } M(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.LessThanExpression); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.EqualsEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } M(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.LessThanExpression); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.ExclamationEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } M(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.LessThanExpression); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RelationalPatternPrecedence_02() { UsingStatement( @"_ = e switch { < 0 << 0 => 0, == 4 << 4 => 4, != 5 << 5 => 5, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.EqualsEqualsToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.ExclamationEqualsToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RelationalPatternPrecedence_03() { UsingStatement( @"_ = e is < 4;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RelationalPatternPrecedence_04() { UsingStatement( @"_ = e is < 4 < 4;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RelationalPatternPrecedence_05() { UsingStatement( @"_ = e is < 4 << 4;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void WhenIsNotKeywordInIsExpression() { UsingStatement(@"_ = e is T when;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "when"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void WhenIsNotKeywordInRecursivePattern() { UsingStatement(@"_ = e switch { T(X when) => 1, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "when"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_01() { UsingStatement(@"_ = e is int or long;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.LongKeyword); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_02() { UsingStatement(@"_ = e is int or System.Int64;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "System"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int64"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_03() { UsingStatement(@"_ = e switch { int or long => 1, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.OrPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.LongKeyword); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_04() { UsingStatement(@"_ = e switch { int or System.Int64 => 1, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.OrPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "System"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int64"); } } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_05() { UsingStatement(@"_ = e switch { T(int) => 1, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_06() { UsingStatement(@"_ = e switch { int => 1, long => 2, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.LongKeyword); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(49354, "https://github.com/dotnet/roslyn/issues/49354")] public void TypePattern_07() { UsingStatement(@"_ = e is (int) or string;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.OrKeyword); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_08() { UsingStatement($"_ = e is (a) or b;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CompoundPattern_01() { UsingStatement(@"bool isLetter(char c) => c is >= 'a' and <= 'z' or >= 'A' and <= 'Z';", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.LocalFunctionStatement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.BoolKeyword); } N(SyntaxKind.IdentifierToken, "isLetter"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.CharKeyword); } N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.AndPattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } } N(SyntaxKind.OrKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_01() { UsingStatement(@"_ = e is int and;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "and"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_02() { UsingStatement(@"_ = e is int and < Z;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Z"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_03() { UsingStatement(@"_ = e is int and && b;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.LogicalAndExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "and"); } } } N(SyntaxKind.AmpersandAmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_04() { UsingStatement(@"_ = e is int and int.MaxValue;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "MaxValue"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_05() { UsingStatement(@"_ = e is int and MaxValue;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "MaxValue"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_06() { UsingStatement(@"_ = e is int and ?? Z;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.CoalesceExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "and"); } } } N(SyntaxKind.QuestionQuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Z"); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_07() { UsingStatement(@"_ = e is int and ? a : b;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "and"); } } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(10492, "https://github.com/dotnet/roslyn/issues/10492")] public void PrecedenceInversionWithTypeTest() { UsingExpression("o is int + d", // (1,6): error CS1525: Invalid expression term 'int' // o is int + d Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(1, 6) ); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.AddExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } } } EOF(); } [Fact, WorkItem(10492, "https://github.com/dotnet/roslyn/issues/10492")] public void PrecedenceInversionWithBlockLambda() { UsingExpression("() => {} + d", // (1,10): warning CS8848: Operator '+' cannot be used here due to precedence. Use parentheses to disambiguate. // () => {} + d Diagnostic(ErrorCode.WRN_PrecedenceInversion, "+").WithArguments("+").WithLocation(1, 10) ); N(SyntaxKind.AddExpression); { N(SyntaxKind.ParenthesizedLambdaExpression); { N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } EOF(); } [Fact, WorkItem(10492, "https://github.com/dotnet/roslyn/issues/10492")] public void PrecedenceInversionWithAnonymousMethod() { UsingExpression("delegate {} + d", // (1,13): warning CS8848: Operator '+' cannot be used here due to precedence. Use parentheses to disambiguate. // delegate {} + d Diagnostic(ErrorCode.WRN_PrecedenceInversion, "+").WithArguments("+").WithLocation(1, 13) ); N(SyntaxKind.AddExpression); { N(SyntaxKind.AnonymousMethodExpression); { N(SyntaxKind.DelegateKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void OneElementPositional_01() { UsingStatement(@"_ = e is (3);", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void OneElementPositional_02() { UsingStatement(@"_ = e is (A);", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void OneElementPositional_03() { UsingStatement(@"_ = e is (int);", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void OneElementPositional_04() { UsingStatement(@"_ = e is (Item1: int);", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Item1"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void OneElementPositional_05() { UsingStatement(@"_ = e is (A) x;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void OneElementPositional_06() { UsingStatement(@"_ = e is ((A, A)) x;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void ZeroElementPositional_01() { UsingStatement(@"_ = e is ();", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void ZeroElementPositional_02() { UsingStatement(@"_ = e is () x;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void ZeroElementPositional_03() { UsingStatement(@"_ = e is () {};", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CastExpressionInPattern_01() { UsingStatement(@"_ = e is (int)+1;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.UnaryPlusExpression); { N(SyntaxKind.PlusToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Theory] [InlineData("or")] [InlineData("and")] [InlineData("not")] public void CastExpressionInPattern_02(string identifier) { UsingStatement($"_ = e is (int){identifier};", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, identifier); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Theory] [CombinatorialData] public void CastExpressionInPattern_03( [CombinatorialValues("and", "or")] string left, [CombinatorialValues(SyntaxKind.AndKeyword, SyntaxKind.OrKeyword)] SyntaxKind opKind, [CombinatorialValues("and", "or")] string right) { UsingStatement($"_ = e is (int){left} {SyntaxFacts.GetText(opKind)} {right};", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(opKind == SyntaxKind.AndKeyword ? SyntaxKind.AndPattern : SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, left); } } } N(opKind); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, right); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CastExpressionInPattern_04() { UsingStatement($"_ = e is (a)42 or b;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "42"); } } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Theory] [CombinatorialData] public void CombinatorAsConstant_00( [CombinatorialValues("and", "or")] string left, [CombinatorialValues(SyntaxKind.AndKeyword, SyntaxKind.OrKeyword)] SyntaxKind opKind, [CombinatorialValues("and", "or")] string right) { UsingStatement($"_ = e is {left} {SyntaxFacts.GetText(opKind)} {right};", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(opKind == SyntaxKind.AndKeyword ? SyntaxKind.AndPattern : SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, left); } } N(opKind); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, right); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Theory] [CombinatorialData] public void CombinatorAsConstant_01( [CombinatorialValues(SyntaxKind.AndKeyword, SyntaxKind.OrKeyword)] SyntaxKind opKind, [CombinatorialValues("and", "or")] string right) { UsingStatement($"_ = e is (int) {SyntaxFacts.GetText(opKind)} {right};", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(opKind == SyntaxKind.AndKeyword ? SyntaxKind.AndPattern : SyntaxKind.OrPattern); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(opKind); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, right); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsConstant_02() { UsingStatement($"_ = e is (int) or >= 0;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.OrKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsConstant_03() { UsingStatement($"_ = e is (int)or or >= 0;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "or"); } } } N(SyntaxKind.OrKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsConstant_04() { UsingStatement($"_ = e is (int) or or or >= 0;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.OrPattern); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "or"); } } } N(SyntaxKind.OrKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void ConjunctiveFollowedByPropertyPattern_01() { UsingStatement(@"switch (e) { case {} and {}: break; }", TestOptions.RegularWithPatternCombinators ); 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.AndPattern); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ConjunctiveFollowedByTuplePattern_01() { UsingStatement(@"switch (e) { case {} and (): break; }", TestOptions.RegularWithPatternCombinators ); 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.AndPattern); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] [WorkItem(42107, "https://github.com/dotnet/roslyn/issues/42107")] public void ParenthesizedRelationalPattern_01() { UsingStatement(@"_ = e is (>= 1);", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] [WorkItem(42107, "https://github.com/dotnet/roslyn/issues/42107")] public void ParenthesizedRelationalPattern_02() { UsingStatement(@"_ = e switch { (>= 1) => 1 };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] [WorkItem(42107, "https://github.com/dotnet/roslyn/issues/42107")] public void ParenthesizedRelationalPattern_03() { UsingStatement(@"bool isAsciiLetter(char c) => c is (>= 'A' and <= 'Z') or (>= 'a' and <= 'z');", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.LocalFunctionStatement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.BoolKeyword); } N(SyntaxKind.IdentifierToken, "isAsciiLetter"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.CharKeyword); } N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.AndPattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.OrKeyword); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.AndPattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] [WorkItem(42107, "https://github.com/dotnet/roslyn/issues/42107")] public void ParenthesizedRelationalPattern_04() { UsingStatement(@"_ = e is (<= 1, >= 2);", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void AndPatternAssociativity_01() { UsingStatement(@"_ = e is A and B and C;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.AndPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } } N(SyntaxKind.AndKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void OrPatternAssociativity_01() { UsingStatement(@"_ = e is A or B or C;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(43960, "https://github.com/dotnet/roslyn/issues/43960")] public void NamespaceQualifiedEnumConstantInSwitchCase() { var source = @"switch (e) { case global::E.A: break; }"; UsingStatement(source, TestOptions.RegularWithPatternCombinators ); verifyTree(); UsingStatement(source, TestOptions.RegularWithoutPatternCombinators ); verifyTree(); void verifyTree() { 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.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.GlobalKeyword); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "E"); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } } [Fact, WorkItem(44019, "https://github.com/dotnet/roslyn/issues/44019")] public void NamespaceQualifiedEnumConstantInIsPattern() { var source = @"_ = e is global::E.A;"; UsingStatement(source, TestOptions.RegularWithPatternCombinators ); verifyTree(); UsingStatement(source, TestOptions.RegularWithoutPatternCombinators ); verifyTree(); void verifyTree() { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.GlobalKeyword); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "E"); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact, WorkItem(45757, "https://github.com/dotnet/roslyn/issues/45757")] public void IncompleteTuplePatternInPropertySubpattern() { var source = @"_ = this is Program { P1: (1, }"; var expectedErrors = new[] { // (1,32): error CS1026: ) expected // _ = this is Program { P1: (1, } Diagnostic(ErrorCode.ERR_CloseParenExpected, "}").WithLocation(1, 32), // (1,33): error CS1002: ; expected // _ = this is Program { P1: (1, } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(1, 33) }; UsingStatement(source, TestOptions.RegularWithPatternCombinators, expectedErrors ); verifyTree(); UsingStatement(source, TestOptions.RegularWithoutPatternCombinators, expectedErrors ); verifyTree(); void verifyTree() { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.ThisExpression); { N(SyntaxKind.ThisKeyword); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Program"); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "P1"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CommaToken); M(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseBraceToken); } } } } M(SyntaxKind.SemicolonToken); } EOF(); } } [Fact, WorkItem(45757, "https://github.com/dotnet/roslyn/issues/45757")] public void IncompleteTuplePattern() { var source = @"_ = i is (1, }"; var expectedErrors = new[] { // (1,1): error CS1073: Unexpected token '}' // _ = i is (1, } Diagnostic(ErrorCode.ERR_UnexpectedToken, "_ = i is (1, ").WithArguments("}").WithLocation(1, 1), // (1,16): error CS1026: ) expected // _ = i is (1, } Diagnostic(ErrorCode.ERR_CloseParenExpected, "}").WithLocation(1, 16), // (1,16): error CS1002: ; expected // _ = i is (1, } Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(1, 16) }; UsingStatement(source, TestOptions.RegularWithPatternCombinators, expectedErrors ); verifyTree(); UsingStatement(source, TestOptions.RegularWithoutPatternCombinators, expectedErrors ); verifyTree(); void verifyTree() { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "i"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CommaToken); M(SyntaxKind.CloseParenToken); } } } } M(SyntaxKind.SemicolonToken); } EOF(); } } [Fact, WorkItem(47614, "https://github.com/dotnet/roslyn/issues/47614")] public void GenericTypeAsTypePatternInSwitchExpression() { UsingStatement(@"_ = e switch { List<X> => 1, List<Y> => 2, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.TypePattern); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "List"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.TypePattern); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "List"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Y"); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchExpression_PredefinedType() { UsingStatement(@"_ = e switch { int? => 1 };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchStatement_PredefinedType() { UsingStatement(@"switch(a) { case int?: break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchExpression_PredefinedType_Parenthesized() { UsingStatement(@"_ = e switch { (int?) => 1 };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchStatement_PredefinedType_Parenthesized() { UsingStatement(@"switch(a) { case (int?): break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchExpression() { UsingStatement(@"_ = e switch { a? => 1 };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchStatement() { UsingStatement(@"switch(a) { case a?: break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchExpression_Parenthesized() { UsingStatement(@"_ = e switch { (a?) => 1 };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchStatement_Parenthesized() { UsingStatement(@"switch(a) { case (a?): break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ConditionalAsConstantPatternInSwitchExpression() { UsingStatement(@"_ = e switch { (a?x:y) => 1 };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void ConditionalAsConstantPatternInSwitchStatement() { UsingStatement(@"switch(a) { case a?x:y: break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ConditionalAsConstantPatternInSwitchStatement_Parenthesized() { UsingStatement(@"switch(a) { case (a?x:y): break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } } }
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/Tools/ExternalAccess/Razor/RazorDynamicFileInfo.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.Host; namespace Microsoft.CodeAnalysis.ExternalAccess.Razor { /// <summary> /// provides info on the given file /// /// this will be used to provide dynamic content such as generated content from cshtml to workspace /// we acquire this from <see cref="IDynamicFileInfoProvider"/> exposed from external components such as razor for cshtml /// </summary> internal sealed class RazorDynamicFileInfo { public RazorDynamicFileInfo(string filePath, SourceCodeKind sourceCodeKind, TextLoader textLoader, IRazorDocumentServiceProvider documentServiceProvider) { FilePath = filePath; SourceCodeKind = sourceCodeKind; TextLoader = textLoader; DocumentServiceProvider = documentServiceProvider; } /// <summary> /// for now, return null. in future, we will use this to get right options from editorconfig /// </summary> public string FilePath { get; } /// <summary> /// return <see cref="SourceCodeKind"/> for this file /// </summary> public SourceCodeKind SourceCodeKind { get; } /// <summary> /// return <see cref="RazorDynamicFileInfo.TextLoader"/> to load content for the dynamic file /// </summary> public TextLoader TextLoader { get; } /// <summary> /// return <see cref="IRazorDocumentServiceProvider"/> for the contents it provides /// </summary> public IRazorDocumentServiceProvider DocumentServiceProvider { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.ExternalAccess.Razor { /// <summary> /// provides info on the given file /// /// this will be used to provide dynamic content such as generated content from cshtml to workspace /// we acquire this from <see cref="IDynamicFileInfoProvider"/> exposed from external components such as razor for cshtml /// </summary> internal sealed class RazorDynamicFileInfo { public RazorDynamicFileInfo(string filePath, SourceCodeKind sourceCodeKind, TextLoader textLoader, IRazorDocumentServiceProvider documentServiceProvider) { FilePath = filePath; SourceCodeKind = sourceCodeKind; TextLoader = textLoader; DocumentServiceProvider = documentServiceProvider; } /// <summary> /// for now, return null. in future, we will use this to get right options from editorconfig /// </summary> public string FilePath { get; } /// <summary> /// return <see cref="SourceCodeKind"/> for this file /// </summary> public SourceCodeKind SourceCodeKind { get; } /// <summary> /// return <see cref="RazorDynamicFileInfo.TextLoader"/> to load content for the dynamic file /// </summary> public TextLoader TextLoader { get; } /// <summary> /// return <see cref="IRazorDocumentServiceProvider"/> for the contents it provides /// </summary> public IRazorDocumentServiceProvider DocumentServiceProvider { get; } } }
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/Features/CSharp/Portable/ConvertTupleToStruct/CSharpConvertTupleToStructCodeRefactoringProvider.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 Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.ConvertTupleToStruct; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.ConvertTupleToStruct { [ExtensionOrder(Before = PredefinedCodeRefactoringProviderNames.IntroduceVariable)] [ExportLanguageService(typeof(IConvertTupleToStructCodeRefactoringProvider), LanguageNames.CSharp)] [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertTupleToStruct), Shared] internal class CSharpConvertTupleToStructCodeRefactoringProvider : AbstractConvertTupleToStructCodeRefactoringProvider< ExpressionSyntax, NameSyntax, IdentifierNameSyntax, LiteralExpressionSyntax, ObjectCreationExpressionSyntax, TupleExpressionSyntax, ArgumentSyntax, TupleTypeSyntax, TypeDeclarationSyntax, BaseNamespaceDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpConvertTupleToStructCodeRefactoringProvider() { } protected override ArgumentSyntax GetArgumentWithChangedName(ArgumentSyntax argument, string name) => argument.WithNameColon(ChangeName(argument.NameColon, name)); private static NameColonSyntax? ChangeName(NameColonSyntax? nameColon, string name) { if (nameColon == null) { return null; } var newName = SyntaxFactory.IdentifierName(name).WithTriviaFrom(nameColon.Name); return nameColon.WithName(newName); } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.ConvertTupleToStruct; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.ConvertTupleToStruct { [ExtensionOrder(Before = PredefinedCodeRefactoringProviderNames.IntroduceVariable)] [ExportLanguageService(typeof(IConvertTupleToStructCodeRefactoringProvider), LanguageNames.CSharp)] [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertTupleToStruct), Shared] internal class CSharpConvertTupleToStructCodeRefactoringProvider : AbstractConvertTupleToStructCodeRefactoringProvider< ExpressionSyntax, NameSyntax, IdentifierNameSyntax, LiteralExpressionSyntax, ObjectCreationExpressionSyntax, TupleExpressionSyntax, ArgumentSyntax, TupleTypeSyntax, TypeDeclarationSyntax, BaseNamespaceDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpConvertTupleToStructCodeRefactoringProvider() { } protected override ArgumentSyntax GetArgumentWithChangedName(ArgumentSyntax argument, string name) => argument.WithNameColon(ChangeName(argument.NameColon, name)); private static NameColonSyntax? ChangeName(NameColonSyntax? nameColon, string name) { if (nameColon == null) { return null; } var newName = SyntaxFactory.IdentifierName(name).WithTriviaFrom(nameColon.Name); return nameColon.WithName(newName); } } }
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/VisualStudio/Core/Impl/Options/RadioButtonViewModel.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.Options; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { internal class RadioButtonViewModel<TOption> : AbstractRadioButtonViewModel { private readonly Option<TOption> _option; private readonly TOption _value; public RadioButtonViewModel(string description, string preview, string group, TOption value, Option<TOption> option, AbstractOptionPreviewViewModel info, OptionStore optionStore) : base(description, preview, info, isChecked: optionStore.GetOption(option).Equals(value), group: group) { _value = value; _option = option; } internal override void SetOptionAndUpdatePreview(AbstractOptionPreviewViewModel info, string preview) => info.SetOptionAndUpdatePreview(_value, _option, preview); } }
// Licensed to the .NET Foundation under one or more 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.Options; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { internal class RadioButtonViewModel<TOption> : AbstractRadioButtonViewModel { private readonly Option<TOption> _option; private readonly TOption _value; public RadioButtonViewModel(string description, string preview, string group, TOption value, Option<TOption> option, AbstractOptionPreviewViewModel info, OptionStore optionStore) : base(description, preview, info, isChecked: optionStore.GetOption(option).Equals(value), group: group) { _value = value; _option = option; } internal override void SetOptionAndUpdatePreview(AbstractOptionPreviewViewModel info, string preview) => info.SetOptionAndUpdatePreview(_value, _option, preview); } }
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/EditorFeatures/Text/Implementation/TextBufferFactoryService/ITextBufferCloneService.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.Editor; using Microsoft.CodeAnalysis.Host; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Text { internal interface ITextBufferCloneService : IWorkspaceService { /// <summary> /// get new <see cref="ITextBuffer"/> from <see cref="SnapshotSpan"/> with <see cref="IContentTypeRegistryService.UnknownContentType"/> /// /// it is explicitly marked with unknown content type so that it can't be used with editor directly /// </summary> ITextBuffer CloneWithUnknownContentType(SnapshotSpan span); /// <summary> /// get new <see cref="ITextBuffer"/> from <see cref="ITextImage"/> with <see cref="IContentTypeRegistryService.UnknownContentType"/> /// /// it is explicitly marked with unknown content type so that it can't be used with editor directly /// </summary> ITextBuffer CloneWithUnknownContentType(ITextImage textImage); /// <summary> /// get new <see cref="ITextBuffer"/> from <see cref="SourceText"/> with <see cref="ContentTypeNames.RoslynContentType"/> /// </summary> ITextBuffer CloneWithRoslynContentType(SourceText sourceText); /// <summary> /// get new <see cref="ITextBuffer"/> from <see cref="SourceText"/> with <see cref="IContentType"/> /// </summary> ITextBuffer Clone(SourceText sourceText, IContentType contentType); } }
// Licensed to the .NET Foundation under one or more 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.Editor; using Microsoft.CodeAnalysis.Host; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Text { internal interface ITextBufferCloneService : IWorkspaceService { /// <summary> /// get new <see cref="ITextBuffer"/> from <see cref="SnapshotSpan"/> with <see cref="IContentTypeRegistryService.UnknownContentType"/> /// /// it is explicitly marked with unknown content type so that it can't be used with editor directly /// </summary> ITextBuffer CloneWithUnknownContentType(SnapshotSpan span); /// <summary> /// get new <see cref="ITextBuffer"/> from <see cref="ITextImage"/> with <see cref="IContentTypeRegistryService.UnknownContentType"/> /// /// it is explicitly marked with unknown content type so that it can't be used with editor directly /// </summary> ITextBuffer CloneWithUnknownContentType(ITextImage textImage); /// <summary> /// get new <see cref="ITextBuffer"/> from <see cref="SourceText"/> with <see cref="ContentTypeNames.RoslynContentType"/> /// </summary> ITextBuffer CloneWithRoslynContentType(SourceText sourceText); /// <summary> /// get new <see cref="ITextBuffer"/> from <see cref="SourceText"/> with <see cref="IContentType"/> /// </summary> ITextBuffer Clone(SourceText sourceText, IContentType contentType); } }
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenConstructorInitTests.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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class CodeGenConstructorInitTests : CSharpTestBase { [Fact] public void TestImplicitConstructor() { var source = @" class C { static void Main() { C c = new C(); } } "; CompileAndVerify(source, expectedOutput: string.Empty). VerifyIL("C..ctor", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret } "); } [Fact] public void TestImplicitConstructorInitializer() { var source = @" class C { C() { } static void Main() { C c = new C(); } } "; CompileAndVerify(source, expectedOutput: string.Empty). VerifyIL("C..ctor", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret } "); } [Fact] public void TestExplicitBaseConstructorInitializer() { var source = @" class C { C() : base() { } static void Main() { C c = new C(); } } "; CompileAndVerify(source, expectedOutput: string.Empty). VerifyIL("C..ctor", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret } "); } [Fact] public void TestExplicitThisConstructorInitializer() { var source = @" class C { C() : this(1) { } C(int x) { } static void Main() { C c = new C(); } } "; CompileAndVerify(source, expectedOutput: string.Empty). VerifyIL("C..ctor", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: call ""C..ctor(int)"" IL_0007: ret } "); } [Fact] public void TestExplicitOverloadedBaseConstructorInitializer() { var source = @" class B { public B(int x) { } public B(string x) { } } class C : B { C() : base(1) { } static void Main() { C c = new C(); } } "; CompileAndVerify(source, expectedOutput: string.Empty). VerifyIL("C..ctor", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: call ""B..ctor(int)"" IL_0007: ret } "); } [Fact] public void TestExplicitOverloadedThisConstructorInitializer() { var source = @" class C { C() : this(1) { } C(int x) { } C(string x) { } static void Main() { C c = new C(); } } "; CompileAndVerify(source, expectedOutput: string.Empty). VerifyIL("C..ctor", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: call ""C..ctor(int)"" IL_0007: ret } "); } [Fact] public void TestComplexInitialization() { var source = @" class B { private int f = E.Init(3, ""B.f""); public B() { System.Console.WriteLine(""B()""); } public B(int x) : this (x.ToString()) { System.Console.WriteLine(""B(int)""); } public B(string x) : this() { System.Console.WriteLine(""B(string)""); } } class C : B { private int f = E.Init(4, ""C.f""); public C() : this(1) { System.Console.WriteLine(""C()""); } public C(int x) : this(x.ToString()) { System.Console.WriteLine(""C(int)""); } public C(string x) : base(x.Length) { System.Console.WriteLine(""C(string)""); } } class E { static void Main() { C c = new C(); } public static int Init(int value, string message) { System.Console.WriteLine(message); return value; } } "; //interested in execution order and number of field initializations CompileAndVerify(source, expectedOutput: @" C.f B.f B() B(string) B(int) C(string) C(int) C() "); } // Successive Operator On Class [WorkItem(540992, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540992")] [Fact] public void TestSuccessiveOperatorOnClass() { var text = @" using System; class C { public int num; public C(int i) { this.num = i; } static void Main(string[] args) { C c1 = new C(1); C c2 = new C(2); C c3 = new C(3); bool verify = c1.num == 1 && c2.num == 2 & c3.num == 3; Console.WriteLine(verify); } } "; var expectedOutput = @"True"; CompileAndVerify(text, expectedOutput: expectedOutput); } [Fact] public void TestInitializerInCtor001() { var source = @" class C { public int I{get;} public C() { I = 42; } static void Main() { C c = new C(); System.Console.WriteLine(c.I); } } "; CompileAndVerify(source, expectedOutput: "42"). VerifyIL("C..ctor", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.0 IL_0007: ldc.i4.s 42 IL_0009: stfld ""int C.<I>k__BackingField"" IL_000e: ret } "); } [Fact] public void TestInitializerInCtor002() { var source = @" public struct S { public int X{get;} public int Y{get;} public S(int dummy) { X = 42; Y = X; } public static void Main() { S s = new S(1); System.Console.WriteLine(s.Y); } } "; CompileAndVerify(source, expectedOutput: "42"). VerifyIL("S..ctor", @" { // Code size 21 (0x15) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.s 42 IL_0003: stfld ""int S.<X>k__BackingField"" IL_0008: ldarg.0 IL_0009: ldarg.0 IL_000a: call ""readonly int S.X.get"" IL_000f: stfld ""int S.<Y>k__BackingField"" IL_0014: ret } "); } [Fact] public void TestInitializerInCtor003() { var source = @" struct C { public int I{get;} public int J{get; set;} public C(int arg) { I = 33; J = I; I = J; I = arg; } static void Main() { C c = new C(42); System.Console.WriteLine(c.I); } } "; CompileAndVerify(source, expectedOutput: "42"). VerifyIL("C..ctor(int)", @" { // Code size 40 (0x28) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.s 33 IL_0003: stfld ""int C.<I>k__BackingField"" IL_0008: ldarg.0 IL_0009: ldarg.0 IL_000a: call ""readonly int C.I.get"" IL_000f: call ""void C.J.set"" IL_0014: ldarg.0 IL_0015: ldarg.0 IL_0016: call ""readonly int C.J.get"" IL_001b: stfld ""int C.<I>k__BackingField"" IL_0020: ldarg.0 IL_0021: ldarg.1 IL_0022: stfld ""int C.<I>k__BackingField"" IL_0027: ret } "); } [Fact] public void TestInitializerInCtor004() { var source = @" struct C { public static int I{get;} public static int J{get; set;} static C() { I = 33; J = I; I = J; I = 42; } static void Main() { System.Console.WriteLine(C.I); } } "; CompileAndVerify(source, expectedOutput: "42"). VerifyIL("C..cctor()", @" { // Code size 35 (0x23) .maxstack 1 IL_0000: ldc.i4.s 33 IL_0002: stsfld ""int C.<I>k__BackingField"" IL_0007: call ""int C.I.get"" IL_000c: call ""void C.J.set"" IL_0011: call ""int C.J.get"" IL_0016: stsfld ""int C.<I>k__BackingField"" IL_001b: ldc.i4.s 42 IL_001d: stsfld ""int C.<I>k__BackingField"" IL_0022: ret } "); } [Fact] public void TestInitializerInCtor005() { var source = @" struct C { static int P1 { get; } static int y = (P1 = 123); static void Main() { System.Console.WriteLine(y); System.Console.WriteLine(P1); } } "; CompileAndVerify(source, expectedOutput: @"123 123"). VerifyIL("C..cctor()", @" { // Code size 14 (0xe) .maxstack 2 IL_0000: ldc.i4.s 123 IL_0002: dup IL_0003: stsfld ""int C.<P1>k__BackingField"" IL_0008: stsfld ""int C.y"" IL_000d: ret } "); } [Fact] public void TestInitializerInCtor006() { var source = @" struct C { static int P1 { get; } static int y { get; } = (P1 = 123); static void Main() { System.Console.WriteLine(y); System.Console.WriteLine(P1); } } "; CompileAndVerify(source, expectedOutput: @"123 123"). VerifyIL("C..cctor()", @" { // Code size 14 (0xe) .maxstack 2 IL_0000: ldc.i4.s 123 IL_0002: dup IL_0003: stsfld ""int C.<P1>k__BackingField"" IL_0008: stsfld ""int C.<y>k__BackingField"" IL_000d: ret } "); } [WorkItem(4383, "https://github.com/dotnet/roslyn/issues/4383")] [Fact] public void DecimalConstInit001() { var source = @" using System; using System.Collections.Generic; public static class Module1 { public static void Main() { Console.WriteLine(ClassWithStaticField.Dictionary[""String3""]); } } public class ClassWithStaticField { public const decimal DecimalConstant = 375; private static Dictionary<String, Single> DictionaryField = new Dictionary<String, Single> { {""String1"", 1.0F}, {""String2"", 2.0F}, {""String3"", 3.0F} }; public static Dictionary<String, Single> Dictionary { get { return DictionaryField; } } } "; CompileAndVerify(source, expectedOutput: "3"). VerifyIL("ClassWithStaticField..cctor", @" { // Code size 74 (0x4a) .maxstack 4 IL_0000: ldc.i4 0x177 IL_0005: newobj ""decimal..ctor(int)"" IL_000a: stsfld ""decimal ClassWithStaticField.DecimalConstant"" IL_000f: newobj ""System.Collections.Generic.Dictionary<string, float>..ctor()"" IL_0014: dup IL_0015: ldstr ""String1"" IL_001a: ldc.r4 1 IL_001f: callvirt ""void System.Collections.Generic.Dictionary<string, float>.Add(string, float)"" IL_0024: dup IL_0025: ldstr ""String2"" IL_002a: ldc.r4 2 IL_002f: callvirt ""void System.Collections.Generic.Dictionary<string, float>.Add(string, float)"" IL_0034: dup IL_0035: ldstr ""String3"" IL_003a: ldc.r4 3 IL_003f: callvirt ""void System.Collections.Generic.Dictionary<string, float>.Add(string, float)"" IL_0044: stsfld ""System.Collections.Generic.Dictionary<string, float> ClassWithStaticField.DictionaryField"" IL_0049: ret } "); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void DecimalConstInit002() { var source1 = @" class C { const decimal d1 = 0.1m; } "; var source2 = @" class C { static readonly decimal d1 = 0.1m; } "; var expectedIL = @" { // Code size 16 (0x10) .maxstack 5 IL_0000: ldc.i4.1 IL_0001: ldc.i4.0 IL_0002: ldc.i4.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.1 IL_0005: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_000a: stsfld ""decimal C.d1"" IL_000f: ret } "; CompileAndVerify(source1).VerifyIL("C..cctor", expectedIL); CompileAndVerify(source2).VerifyIL("C..cctor", expectedIL); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void DecimalConstInit003() { var source1 = @" class C { const decimal d1 = 0.0m; } "; var source2 = @" class C { static readonly decimal d1 = 0.0m; } "; var expectedIL = @" { // Code size 16 (0x10) .maxstack 5 IL_0000: ldc.i4.0 IL_0001: ldc.i4.0 IL_0002: ldc.i4.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.1 IL_0005: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_000a: stsfld ""decimal C.d1"" IL_000f: ret } "; CompileAndVerify(source1).VerifyIL("C..cctor", expectedIL); CompileAndVerify(source2).VerifyIL("C..cctor", expectedIL); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void DecimalConstInit004() { var source1 = @" class C { const decimal d1 = default; const decimal d2 = 0; const decimal d3 = 0m; } "; var source2 = @" class C { static readonly decimal d1 = default; static readonly decimal d2 = 0; static readonly decimal d3 = 0m; } "; var options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All); CompileAndVerify(source1, symbolValidator: validator, options: options); CompileAndVerify(source2, symbolValidator: validator, options: options); void validator(ModuleSymbol module) { var type = module.ContainingAssembly.GetTypeByMetadataName("C"); Assert.Null(type.GetMember(".cctor")); } } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void StaticLambdaConstructorAlwaysEmitted() { var source = @" class C { void M() { System.Action a1 = () => { }; } } "; CompileAndVerify(source). VerifyIL("C.<>c..cctor", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: newobj ""C.<>c..ctor()"" IL_0005: stsfld ""C.<>c C.<>c.<>9"" IL_000a: ret } "); } [WorkItem(217748, "https://devdiv.visualstudio.com/DevDiv/_workitems?_a=edit&id=217748")] [Fact] public void BadExpressionConstructor() { string source = @"class C { static dynamic F() => 0; dynamic d = F() * 2; }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyEmitDiagnostics( // (4,17): error CS0656: Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create' // dynamic d = F() * 2; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "F()").WithArguments("Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo", "Create").WithLocation(4, 17)); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void SkipSynthesizedStaticConstructor_01() { string source = @" #nullable enable class C { static int i = 0; static bool b = false; }"; CompileAndVerify( source, symbolValidator: validator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); void validator(ModuleSymbol module) { var type = module.ContainingAssembly.GetTypeByMetadataName("C"); Assert.Null(type.GetMember(".cctor")); } } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void SkipSynthesizedStaticConstructor_02() { string source = @" #nullable enable class C { static string s = null!; }"; CompileAndVerify( source, symbolValidator: validator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); void validator(ModuleSymbol module) { var type = module.ContainingAssembly.GetTypeByMetadataName("C"); Assert.Null(type.GetMember(".cctor")); } } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void SkipSynthesizedStaticConstructor_03() { string source = @" #nullable enable class C { static (int, object) pair = (0, null!); }"; CompileAndVerify(source).VerifyIL("C..cctor()", @"{ // Code size 13 (0xd) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: ldnull IL_0002: newobj ""System.ValueTuple<int, object>..ctor(int, object)"" IL_0007: stsfld ""System.ValueTuple<int, object> C.pair"" IL_000c: ret }"); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void SkipSynthesizedStaticConstructor_04() { string source = @" #nullable enable class C { static (int, object) pair1 = default; static (int, object) pair2 = default((int, object)); static (int, object) pair3 = default!; static (int, object) pair4 = default((int, object))!; }"; // note: we could make the synthesized constructor smarter and realize that // nothing needs to be emitted for these initializers. // but it doesn't serve any realistic scenarios at this time. CompileAndVerify(source).VerifyIL("C..cctor()", @" { // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void SkipSynthesizedStaticConstructor_05() { string source = @" #nullable enable class C { static C instance = default!; }"; CompileAndVerify( source, symbolValidator: validator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); void validator(ModuleSymbol module) { var type = module.ContainingAssembly.GetTypeByMetadataName("C"); Assert.Null(type.GetMember(".cctor")); } } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void SkipSynthesizedStaticConstructor_06() { string source = @" #nullable enable struct S { public int x; public int y; } class C { static S field1 = default; static S field2 = default(S); static S field3 = new S(); }"; // note: we could make the synthesized constructor smarter and realize that // nothing needs to be emitted for these initializers. // but it doesn't serve any realistic scenarios at this time. CompileAndVerify(source).VerifyIL("C..cctor()", @" { // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void SkipSynthesizedStaticConstructor_08() { string source = @" #nullable enable class C { static int x = 1; }"; CompileAndVerify(source).VerifyIL("C..cctor()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: stsfld ""int C.x"" IL_0006: ret }"); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void SkipSynthesizedStaticConstructor_09() { string source = @" #nullable enable struct S { public int x; } class C { static S? s1 = null; static S? s2 = default(S?); }"; CompileAndVerify( source, symbolValidator: validator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); void validator(ModuleSymbol module) { var type = module.ContainingAssembly.GetTypeByMetadataName("C"); Assert.Null(type.GetMember(".cctor")); } } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void SkipSynthesizedStaticConstructor_10() { string source = @" #nullable enable struct S { public int x; } class C { static S? s1 = default; }"; // note: we could make the synthesized constructor smarter and realize that // nothing needs to be emitted for these initializers. // but it doesn't serve any realistic scenarios at this time. CompileAndVerify(source).VerifyIL("C..cctor()", @" { // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void SkipSynthesizedStaticConstructor_11() { string source = @" #nullable enable struct S { public int x; } class C { static S? s1 = new S?(); }"; // note: we could make the synthesized constructor smarter and realize that // nothing needs to be emitted for these initializers. // but it doesn't serve any realistic scenarios at this time. CompileAndVerify(source).VerifyIL("C..cctor()", @" { // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void SkipSynthesizedStaticConstructor_12() { string source = @" #nullable enable struct S { public int x; } class C { static S? s1 = default(S); }"; CompileAndVerify(source).VerifyIL("C..cctor()", @" { // Code size 20 (0x14) .maxstack 1 .locals init (S V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloc.0 IL_0009: newobj ""S?..ctor(S)"" IL_000e: stsfld ""S? C.s1"" IL_0013: ret }"); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void SkipSynthesizedStaticConstructor_13() { string source = @" #nullable enable struct S { public int x; } class C { static S? s1 = new S(); }"; CompileAndVerify(source).VerifyIL("C..cctor()", @" { // Code size 20 (0x14) .maxstack 1 .locals init (S V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloc.0 IL_0009: newobj ""S?..ctor(S)"" IL_000e: stsfld ""S? C.s1"" IL_0013: ret }"); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void SkipSynthesizedStaticConstructor_14() { string source = @" #nullable enable struct S { public int x; } class C { static object s1 = default(S); }"; CompileAndVerify(source).VerifyIL("C..cctor()", @" { // Code size 20 (0x14) .maxstack 1 .locals init (S V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloc.0 IL_0009: box ""S"" IL_000e: stsfld ""object C.s1"" IL_0013: ret }"); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void SkipSynthesizedStaticConstructor_15() { string source = @" #nullable enable struct S { public int x; } class C { static object s1 = new S(); }"; CompileAndVerify(source).VerifyIL("C..cctor()", @" { // Code size 20 (0x14) .maxstack 1 .locals init (S V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloc.0 IL_0009: box ""S"" IL_000e: stsfld ""object C.s1"" IL_0013: ret }"); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void SkipSynthesizedStaticConstructor_16() { string source = @" #nullable enable struct S { public int x; } class C { static object s1 = default(S?); static object s2 = (S?)null; static object s3 = new S?(); }"; // note: we could make the synthesized constructor smarter and realize that // nothing needs to be emitted for these initializers. // but it doesn't serve any realistic scenarios at this time. CompileAndVerify(source).VerifyIL("C..cctor()", @" { // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void SkipSynthesizedStaticConstructor_17() { string source = @" unsafe class C { static System.IntPtr s1 = (System.IntPtr)0; static System.UIntPtr s2 = (System.UIntPtr)0; static void* s3 = (void*)0; }"; // note: we could make the synthesized constructor smarter and realize that // nothing needs to be emitted for the `(void*)0` initializer. // but it doesn't serve any realistic scenarios at this time. CompileAndVerify(source, options: TestOptions.UnsafeDebugDll, verify: Verification.Skipped).VerifyIL("C..cctor()", @" { // Code size 31 (0x1f) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: call ""System.IntPtr System.IntPtr.op_Explicit(int)"" IL_0006: stsfld ""System.IntPtr C.s1"" IL_000b: ldc.i4.0 IL_000c: conv.i8 IL_000d: call ""System.UIntPtr System.UIntPtr.op_Explicit(ulong)"" IL_0012: stsfld ""System.UIntPtr C.s2"" IL_0017: ldc.i4.0 IL_0018: conv.i IL_0019: stsfld ""void* C.s3"" IL_001e: ret }"); } [WorkItem(543606, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543606")] [ConditionalFact(typeof(DesktopOnly))] public void StaticNullInitializerHasNoEffectOnTypeIL() { var source1 = @" #nullable enable class C { static string s1; }"; var source2 = @" #nullable enable class C { static string s1 = null!; }"; var expectedIL = @" .class private auto ansi beforefieldinit C extends [mscorlib]System.Object { // Fields .field private static string s1 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 01 00 00 ) // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x207f // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method C::.ctor } // end of class C "; CompileAndVerify(source1).VerifyTypeIL("C", expectedIL); CompileAndVerify(source2).VerifyTypeIL("C", expectedIL); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void ExplicitStaticConstructor_01() { string source = @" #nullable enable class C { static string x = null!; static C() { } }"; CompileAndVerify(source).VerifyIL("C..cctor()", @" { // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void ExplicitStaticConstructor_02() { string source = @" #nullable enable class C { static string x; static C() { x = null!; } }"; CompileAndVerify(source).VerifyIL("C..cctor()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldnull IL_0001: stsfld ""string C.x"" IL_0006: ret }"); } [Fact, WorkItem(55797, "https://github.com/dotnet/roslyn/issues/55797")] public void TwoParameterlessConstructors() { string source = @" public class C { public C() : Garbage() { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,12): error CS0501: 'C.C()' must declare a body because it is not marked abstract, extern, or partial // public C() : Garbage() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "C").WithArguments("C.C()").WithLocation(4, 12), // (4,18): error CS1018: Keyword 'this' or 'base' expected // public C() : Garbage() Diagnostic(ErrorCode.ERR_ThisOrBaseExpected, "Garbage").WithLocation(4, 18), // (4,18): error CS1002: ; expected // public C() : Garbage() Diagnostic(ErrorCode.ERR_SemicolonExpected, "Garbage").WithLocation(4, 18), // (4,18): error CS1520: Method must have a return type // public C() : Garbage() Diagnostic(ErrorCode.ERR_MemberNeedsType, "Garbage").WithLocation(4, 18), // (4,18): error CS0121: The call is ambiguous between the following methods or properties: 'C.C()' and 'C.C()' // public C() : Garbage() Diagnostic(ErrorCode.ERR_AmbigCall, "").WithArguments("C.C()", "C.C()").WithLocation(4, 18) ); } [Fact, WorkItem(55797, "https://github.com/dotnet/roslyn/issues/55797")] public void TwoParameterlessConstructors_2() { string source = @" public class C { public C() : this() { } public C() { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,18): error CS0121: The call is ambiguous between the following methods or properties: 'C.C()' and 'C.C()' // public C() : this() Diagnostic(ErrorCode.ERR_AmbigCall, "this").WithArguments("C.C()", "C.C()").WithLocation(4, 18), // (7,12): error CS0111: Type 'C' already defines a member called 'C' with the same parameter types // public C() Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "C").WithArguments("C", "C").WithLocation(7, 12) ); } [Fact, WorkItem(55797, "https://github.com/dotnet/roslyn/issues/55797")] public void TwoParameterlessConstructors_3() { string source = @" public class C { public C() : this() { } public C2() { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,18): error CS0121: The call is ambiguous between the following methods or properties: 'C.C()' and 'C.C()' // public C() : this() Diagnostic(ErrorCode.ERR_AmbigCall, "this").WithArguments("C.C()", "C.C()").WithLocation(4, 18), // (7,12): error CS1520: Method must have a return type // public C2() Diagnostic(ErrorCode.ERR_MemberNeedsType, "C2").WithLocation(7, 12) ); } [Fact, WorkItem(55797, "https://github.com/dotnet/roslyn/issues/55797")] public void TwoParameterlessConstructors_Struct() { string source = @" public struct C { public C() : this() { } public C2() { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,18): error CS0121: The call is ambiguous between the following methods or properties: 'C.C()' and 'C.C()' // public C() : this() Diagnostic(ErrorCode.ERR_AmbigCall, "this").WithArguments("C.C()", "C.C()").WithLocation(4, 18), // (7,12): error CS1520: Method must have a return type // public C2() Diagnostic(ErrorCode.ERR_MemberNeedsType, "C2").WithLocation(7, 12) ); } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class CodeGenConstructorInitTests : CSharpTestBase { [Fact] public void TestImplicitConstructor() { var source = @" class C { static void Main() { C c = new C(); } } "; CompileAndVerify(source, expectedOutput: string.Empty). VerifyIL("C..ctor", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret } "); } [Fact] public void TestImplicitConstructorInitializer() { var source = @" class C { C() { } static void Main() { C c = new C(); } } "; CompileAndVerify(source, expectedOutput: string.Empty). VerifyIL("C..ctor", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret } "); } [Fact] public void TestExplicitBaseConstructorInitializer() { var source = @" class C { C() : base() { } static void Main() { C c = new C(); } } "; CompileAndVerify(source, expectedOutput: string.Empty). VerifyIL("C..ctor", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret } "); } [Fact] public void TestExplicitThisConstructorInitializer() { var source = @" class C { C() : this(1) { } C(int x) { } static void Main() { C c = new C(); } } "; CompileAndVerify(source, expectedOutput: string.Empty). VerifyIL("C..ctor", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: call ""C..ctor(int)"" IL_0007: ret } "); } [Fact] public void TestExplicitOverloadedBaseConstructorInitializer() { var source = @" class B { public B(int x) { } public B(string x) { } } class C : B { C() : base(1) { } static void Main() { C c = new C(); } } "; CompileAndVerify(source, expectedOutput: string.Empty). VerifyIL("C..ctor", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: call ""B..ctor(int)"" IL_0007: ret } "); } [Fact] public void TestExplicitOverloadedThisConstructorInitializer() { var source = @" class C { C() : this(1) { } C(int x) { } C(string x) { } static void Main() { C c = new C(); } } "; CompileAndVerify(source, expectedOutput: string.Empty). VerifyIL("C..ctor", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: call ""C..ctor(int)"" IL_0007: ret } "); } [Fact] public void TestComplexInitialization() { var source = @" class B { private int f = E.Init(3, ""B.f""); public B() { System.Console.WriteLine(""B()""); } public B(int x) : this (x.ToString()) { System.Console.WriteLine(""B(int)""); } public B(string x) : this() { System.Console.WriteLine(""B(string)""); } } class C : B { private int f = E.Init(4, ""C.f""); public C() : this(1) { System.Console.WriteLine(""C()""); } public C(int x) : this(x.ToString()) { System.Console.WriteLine(""C(int)""); } public C(string x) : base(x.Length) { System.Console.WriteLine(""C(string)""); } } class E { static void Main() { C c = new C(); } public static int Init(int value, string message) { System.Console.WriteLine(message); return value; } } "; //interested in execution order and number of field initializations CompileAndVerify(source, expectedOutput: @" C.f B.f B() B(string) B(int) C(string) C(int) C() "); } // Successive Operator On Class [WorkItem(540992, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540992")] [Fact] public void TestSuccessiveOperatorOnClass() { var text = @" using System; class C { public int num; public C(int i) { this.num = i; } static void Main(string[] args) { C c1 = new C(1); C c2 = new C(2); C c3 = new C(3); bool verify = c1.num == 1 && c2.num == 2 & c3.num == 3; Console.WriteLine(verify); } } "; var expectedOutput = @"True"; CompileAndVerify(text, expectedOutput: expectedOutput); } [Fact] public void TestInitializerInCtor001() { var source = @" class C { public int I{get;} public C() { I = 42; } static void Main() { C c = new C(); System.Console.WriteLine(c.I); } } "; CompileAndVerify(source, expectedOutput: "42"). VerifyIL("C..ctor", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.0 IL_0007: ldc.i4.s 42 IL_0009: stfld ""int C.<I>k__BackingField"" IL_000e: ret } "); } [Fact] public void TestInitializerInCtor002() { var source = @" public struct S { public int X{get;} public int Y{get;} public S(int dummy) { X = 42; Y = X; } public static void Main() { S s = new S(1); System.Console.WriteLine(s.Y); } } "; CompileAndVerify(source, expectedOutput: "42"). VerifyIL("S..ctor", @" { // Code size 21 (0x15) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.s 42 IL_0003: stfld ""int S.<X>k__BackingField"" IL_0008: ldarg.0 IL_0009: ldarg.0 IL_000a: call ""readonly int S.X.get"" IL_000f: stfld ""int S.<Y>k__BackingField"" IL_0014: ret } "); } [Fact] public void TestInitializerInCtor003() { var source = @" struct C { public int I{get;} public int J{get; set;} public C(int arg) { I = 33; J = I; I = J; I = arg; } static void Main() { C c = new C(42); System.Console.WriteLine(c.I); } } "; CompileAndVerify(source, expectedOutput: "42"). VerifyIL("C..ctor(int)", @" { // Code size 40 (0x28) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.s 33 IL_0003: stfld ""int C.<I>k__BackingField"" IL_0008: ldarg.0 IL_0009: ldarg.0 IL_000a: call ""readonly int C.I.get"" IL_000f: call ""void C.J.set"" IL_0014: ldarg.0 IL_0015: ldarg.0 IL_0016: call ""readonly int C.J.get"" IL_001b: stfld ""int C.<I>k__BackingField"" IL_0020: ldarg.0 IL_0021: ldarg.1 IL_0022: stfld ""int C.<I>k__BackingField"" IL_0027: ret } "); } [Fact] public void TestInitializerInCtor004() { var source = @" struct C { public static int I{get;} public static int J{get; set;} static C() { I = 33; J = I; I = J; I = 42; } static void Main() { System.Console.WriteLine(C.I); } } "; CompileAndVerify(source, expectedOutput: "42"). VerifyIL("C..cctor()", @" { // Code size 35 (0x23) .maxstack 1 IL_0000: ldc.i4.s 33 IL_0002: stsfld ""int C.<I>k__BackingField"" IL_0007: call ""int C.I.get"" IL_000c: call ""void C.J.set"" IL_0011: call ""int C.J.get"" IL_0016: stsfld ""int C.<I>k__BackingField"" IL_001b: ldc.i4.s 42 IL_001d: stsfld ""int C.<I>k__BackingField"" IL_0022: ret } "); } [Fact] public void TestInitializerInCtor005() { var source = @" struct C { static int P1 { get; } static int y = (P1 = 123); static void Main() { System.Console.WriteLine(y); System.Console.WriteLine(P1); } } "; CompileAndVerify(source, expectedOutput: @"123 123"). VerifyIL("C..cctor()", @" { // Code size 14 (0xe) .maxstack 2 IL_0000: ldc.i4.s 123 IL_0002: dup IL_0003: stsfld ""int C.<P1>k__BackingField"" IL_0008: stsfld ""int C.y"" IL_000d: ret } "); } [Fact] public void TestInitializerInCtor006() { var source = @" struct C { static int P1 { get; } static int y { get; } = (P1 = 123); static void Main() { System.Console.WriteLine(y); System.Console.WriteLine(P1); } } "; CompileAndVerify(source, expectedOutput: @"123 123"). VerifyIL("C..cctor()", @" { // Code size 14 (0xe) .maxstack 2 IL_0000: ldc.i4.s 123 IL_0002: dup IL_0003: stsfld ""int C.<P1>k__BackingField"" IL_0008: stsfld ""int C.<y>k__BackingField"" IL_000d: ret } "); } [WorkItem(4383, "https://github.com/dotnet/roslyn/issues/4383")] [Fact] public void DecimalConstInit001() { var source = @" using System; using System.Collections.Generic; public static class Module1 { public static void Main() { Console.WriteLine(ClassWithStaticField.Dictionary[""String3""]); } } public class ClassWithStaticField { public const decimal DecimalConstant = 375; private static Dictionary<String, Single> DictionaryField = new Dictionary<String, Single> { {""String1"", 1.0F}, {""String2"", 2.0F}, {""String3"", 3.0F} }; public static Dictionary<String, Single> Dictionary { get { return DictionaryField; } } } "; CompileAndVerify(source, expectedOutput: "3"). VerifyIL("ClassWithStaticField..cctor", @" { // Code size 74 (0x4a) .maxstack 4 IL_0000: ldc.i4 0x177 IL_0005: newobj ""decimal..ctor(int)"" IL_000a: stsfld ""decimal ClassWithStaticField.DecimalConstant"" IL_000f: newobj ""System.Collections.Generic.Dictionary<string, float>..ctor()"" IL_0014: dup IL_0015: ldstr ""String1"" IL_001a: ldc.r4 1 IL_001f: callvirt ""void System.Collections.Generic.Dictionary<string, float>.Add(string, float)"" IL_0024: dup IL_0025: ldstr ""String2"" IL_002a: ldc.r4 2 IL_002f: callvirt ""void System.Collections.Generic.Dictionary<string, float>.Add(string, float)"" IL_0034: dup IL_0035: ldstr ""String3"" IL_003a: ldc.r4 3 IL_003f: callvirt ""void System.Collections.Generic.Dictionary<string, float>.Add(string, float)"" IL_0044: stsfld ""System.Collections.Generic.Dictionary<string, float> ClassWithStaticField.DictionaryField"" IL_0049: ret } "); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void DecimalConstInit002() { var source1 = @" class C { const decimal d1 = 0.1m; } "; var source2 = @" class C { static readonly decimal d1 = 0.1m; } "; var expectedIL = @" { // Code size 16 (0x10) .maxstack 5 IL_0000: ldc.i4.1 IL_0001: ldc.i4.0 IL_0002: ldc.i4.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.1 IL_0005: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_000a: stsfld ""decimal C.d1"" IL_000f: ret } "; CompileAndVerify(source1).VerifyIL("C..cctor", expectedIL); CompileAndVerify(source2).VerifyIL("C..cctor", expectedIL); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void DecimalConstInit003() { var source1 = @" class C { const decimal d1 = 0.0m; } "; var source2 = @" class C { static readonly decimal d1 = 0.0m; } "; var expectedIL = @" { // Code size 16 (0x10) .maxstack 5 IL_0000: ldc.i4.0 IL_0001: ldc.i4.0 IL_0002: ldc.i4.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.1 IL_0005: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_000a: stsfld ""decimal C.d1"" IL_000f: ret } "; CompileAndVerify(source1).VerifyIL("C..cctor", expectedIL); CompileAndVerify(source2).VerifyIL("C..cctor", expectedIL); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void DecimalConstInit004() { var source1 = @" class C { const decimal d1 = default; const decimal d2 = 0; const decimal d3 = 0m; } "; var source2 = @" class C { static readonly decimal d1 = default; static readonly decimal d2 = 0; static readonly decimal d3 = 0m; } "; var options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All); CompileAndVerify(source1, symbolValidator: validator, options: options); CompileAndVerify(source2, symbolValidator: validator, options: options); void validator(ModuleSymbol module) { var type = module.ContainingAssembly.GetTypeByMetadataName("C"); Assert.Null(type.GetMember(".cctor")); } } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void StaticLambdaConstructorAlwaysEmitted() { var source = @" class C { void M() { System.Action a1 = () => { }; } } "; CompileAndVerify(source). VerifyIL("C.<>c..cctor", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: newobj ""C.<>c..ctor()"" IL_0005: stsfld ""C.<>c C.<>c.<>9"" IL_000a: ret } "); } [WorkItem(217748, "https://devdiv.visualstudio.com/DevDiv/_workitems?_a=edit&id=217748")] [Fact] public void BadExpressionConstructor() { string source = @"class C { static dynamic F() => 0; dynamic d = F() * 2; }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyEmitDiagnostics( // (4,17): error CS0656: Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create' // dynamic d = F() * 2; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "F()").WithArguments("Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo", "Create").WithLocation(4, 17)); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void SkipSynthesizedStaticConstructor_01() { string source = @" #nullable enable class C { static int i = 0; static bool b = false; }"; CompileAndVerify( source, symbolValidator: validator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); void validator(ModuleSymbol module) { var type = module.ContainingAssembly.GetTypeByMetadataName("C"); Assert.Null(type.GetMember(".cctor")); } } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void SkipSynthesizedStaticConstructor_02() { string source = @" #nullable enable class C { static string s = null!; }"; CompileAndVerify( source, symbolValidator: validator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); void validator(ModuleSymbol module) { var type = module.ContainingAssembly.GetTypeByMetadataName("C"); Assert.Null(type.GetMember(".cctor")); } } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void SkipSynthesizedStaticConstructor_03() { string source = @" #nullable enable class C { static (int, object) pair = (0, null!); }"; CompileAndVerify(source).VerifyIL("C..cctor()", @"{ // Code size 13 (0xd) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: ldnull IL_0002: newobj ""System.ValueTuple<int, object>..ctor(int, object)"" IL_0007: stsfld ""System.ValueTuple<int, object> C.pair"" IL_000c: ret }"); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void SkipSynthesizedStaticConstructor_04() { string source = @" #nullable enable class C { static (int, object) pair1 = default; static (int, object) pair2 = default((int, object)); static (int, object) pair3 = default!; static (int, object) pair4 = default((int, object))!; }"; // note: we could make the synthesized constructor smarter and realize that // nothing needs to be emitted for these initializers. // but it doesn't serve any realistic scenarios at this time. CompileAndVerify(source).VerifyIL("C..cctor()", @" { // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void SkipSynthesizedStaticConstructor_05() { string source = @" #nullable enable class C { static C instance = default!; }"; CompileAndVerify( source, symbolValidator: validator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); void validator(ModuleSymbol module) { var type = module.ContainingAssembly.GetTypeByMetadataName("C"); Assert.Null(type.GetMember(".cctor")); } } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void SkipSynthesizedStaticConstructor_06() { string source = @" #nullable enable struct S { public int x; public int y; } class C { static S field1 = default; static S field2 = default(S); static S field3 = new S(); }"; // note: we could make the synthesized constructor smarter and realize that // nothing needs to be emitted for these initializers. // but it doesn't serve any realistic scenarios at this time. CompileAndVerify(source).VerifyIL("C..cctor()", @" { // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void SkipSynthesizedStaticConstructor_08() { string source = @" #nullable enable class C { static int x = 1; }"; CompileAndVerify(source).VerifyIL("C..cctor()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: stsfld ""int C.x"" IL_0006: ret }"); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void SkipSynthesizedStaticConstructor_09() { string source = @" #nullable enable struct S { public int x; } class C { static S? s1 = null; static S? s2 = default(S?); }"; CompileAndVerify( source, symbolValidator: validator, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); void validator(ModuleSymbol module) { var type = module.ContainingAssembly.GetTypeByMetadataName("C"); Assert.Null(type.GetMember(".cctor")); } } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void SkipSynthesizedStaticConstructor_10() { string source = @" #nullable enable struct S { public int x; } class C { static S? s1 = default; }"; // note: we could make the synthesized constructor smarter and realize that // nothing needs to be emitted for these initializers. // but it doesn't serve any realistic scenarios at this time. CompileAndVerify(source).VerifyIL("C..cctor()", @" { // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void SkipSynthesizedStaticConstructor_11() { string source = @" #nullable enable struct S { public int x; } class C { static S? s1 = new S?(); }"; // note: we could make the synthesized constructor smarter and realize that // nothing needs to be emitted for these initializers. // but it doesn't serve any realistic scenarios at this time. CompileAndVerify(source).VerifyIL("C..cctor()", @" { // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void SkipSynthesizedStaticConstructor_12() { string source = @" #nullable enable struct S { public int x; } class C { static S? s1 = default(S); }"; CompileAndVerify(source).VerifyIL("C..cctor()", @" { // Code size 20 (0x14) .maxstack 1 .locals init (S V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloc.0 IL_0009: newobj ""S?..ctor(S)"" IL_000e: stsfld ""S? C.s1"" IL_0013: ret }"); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void SkipSynthesizedStaticConstructor_13() { string source = @" #nullable enable struct S { public int x; } class C { static S? s1 = new S(); }"; CompileAndVerify(source).VerifyIL("C..cctor()", @" { // Code size 20 (0x14) .maxstack 1 .locals init (S V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloc.0 IL_0009: newobj ""S?..ctor(S)"" IL_000e: stsfld ""S? C.s1"" IL_0013: ret }"); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void SkipSynthesizedStaticConstructor_14() { string source = @" #nullable enable struct S { public int x; } class C { static object s1 = default(S); }"; CompileAndVerify(source).VerifyIL("C..cctor()", @" { // Code size 20 (0x14) .maxstack 1 .locals init (S V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloc.0 IL_0009: box ""S"" IL_000e: stsfld ""object C.s1"" IL_0013: ret }"); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void SkipSynthesizedStaticConstructor_15() { string source = @" #nullable enable struct S { public int x; } class C { static object s1 = new S(); }"; CompileAndVerify(source).VerifyIL("C..cctor()", @" { // Code size 20 (0x14) .maxstack 1 .locals init (S V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloc.0 IL_0009: box ""S"" IL_000e: stsfld ""object C.s1"" IL_0013: ret }"); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void SkipSynthesizedStaticConstructor_16() { string source = @" #nullable enable struct S { public int x; } class C { static object s1 = default(S?); static object s2 = (S?)null; static object s3 = new S?(); }"; // note: we could make the synthesized constructor smarter and realize that // nothing needs to be emitted for these initializers. // but it doesn't serve any realistic scenarios at this time. CompileAndVerify(source).VerifyIL("C..cctor()", @" { // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void SkipSynthesizedStaticConstructor_17() { string source = @" unsafe class C { static System.IntPtr s1 = (System.IntPtr)0; static System.UIntPtr s2 = (System.UIntPtr)0; static void* s3 = (void*)0; }"; // note: we could make the synthesized constructor smarter and realize that // nothing needs to be emitted for the `(void*)0` initializer. // but it doesn't serve any realistic scenarios at this time. CompileAndVerify(source, options: TestOptions.UnsafeDebugDll, verify: Verification.Skipped).VerifyIL("C..cctor()", @" { // Code size 31 (0x1f) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: call ""System.IntPtr System.IntPtr.op_Explicit(int)"" IL_0006: stsfld ""System.IntPtr C.s1"" IL_000b: ldc.i4.0 IL_000c: conv.i8 IL_000d: call ""System.UIntPtr System.UIntPtr.op_Explicit(ulong)"" IL_0012: stsfld ""System.UIntPtr C.s2"" IL_0017: ldc.i4.0 IL_0018: conv.i IL_0019: stsfld ""void* C.s3"" IL_001e: ret }"); } [WorkItem(543606, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543606")] [ConditionalFact(typeof(DesktopOnly))] public void StaticNullInitializerHasNoEffectOnTypeIL() { var source1 = @" #nullable enable class C { static string s1; }"; var source2 = @" #nullable enable class C { static string s1 = null!; }"; var expectedIL = @" .class private auto ansi beforefieldinit C extends [mscorlib]System.Object { // Fields .field private static string s1 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 01 00 00 ) // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x207f // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method C::.ctor } // end of class C "; CompileAndVerify(source1).VerifyTypeIL("C", expectedIL); CompileAndVerify(source2).VerifyTypeIL("C", expectedIL); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void ExplicitStaticConstructor_01() { string source = @" #nullable enable class C { static string x = null!; static C() { } }"; CompileAndVerify(source).VerifyIL("C..cctor()", @" { // Code size 1 (0x1) .maxstack 0 IL_0000: ret }"); } [WorkItem(42985, "https://github.com/dotnet/roslyn/issues/42985")] [Fact] public void ExplicitStaticConstructor_02() { string source = @" #nullable enable class C { static string x; static C() { x = null!; } }"; CompileAndVerify(source).VerifyIL("C..cctor()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldnull IL_0001: stsfld ""string C.x"" IL_0006: ret }"); } [Fact, WorkItem(55797, "https://github.com/dotnet/roslyn/issues/55797")] public void TwoParameterlessConstructors() { string source = @" public class C { public C() : Garbage() { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,12): error CS0501: 'C.C()' must declare a body because it is not marked abstract, extern, or partial // public C() : Garbage() Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "C").WithArguments("C.C()").WithLocation(4, 12), // (4,18): error CS1018: Keyword 'this' or 'base' expected // public C() : Garbage() Diagnostic(ErrorCode.ERR_ThisOrBaseExpected, "Garbage").WithLocation(4, 18), // (4,18): error CS1002: ; expected // public C() : Garbage() Diagnostic(ErrorCode.ERR_SemicolonExpected, "Garbage").WithLocation(4, 18), // (4,18): error CS1520: Method must have a return type // public C() : Garbage() Diagnostic(ErrorCode.ERR_MemberNeedsType, "Garbage").WithLocation(4, 18), // (4,18): error CS0121: The call is ambiguous between the following methods or properties: 'C.C()' and 'C.C()' // public C() : Garbage() Diagnostic(ErrorCode.ERR_AmbigCall, "").WithArguments("C.C()", "C.C()").WithLocation(4, 18) ); } [Fact, WorkItem(55797, "https://github.com/dotnet/roslyn/issues/55797")] public void TwoParameterlessConstructors_2() { string source = @" public class C { public C() : this() { } public C() { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,18): error CS0121: The call is ambiguous between the following methods or properties: 'C.C()' and 'C.C()' // public C() : this() Diagnostic(ErrorCode.ERR_AmbigCall, "this").WithArguments("C.C()", "C.C()").WithLocation(4, 18), // (7,12): error CS0111: Type 'C' already defines a member called 'C' with the same parameter types // public C() Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "C").WithArguments("C", "C").WithLocation(7, 12) ); } [Fact, WorkItem(55797, "https://github.com/dotnet/roslyn/issues/55797")] public void TwoParameterlessConstructors_3() { string source = @" public class C { public C() : this() { } public C2() { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,18): error CS0121: The call is ambiguous between the following methods or properties: 'C.C()' and 'C.C()' // public C() : this() Diagnostic(ErrorCode.ERR_AmbigCall, "this").WithArguments("C.C()", "C.C()").WithLocation(4, 18), // (7,12): error CS1520: Method must have a return type // public C2() Diagnostic(ErrorCode.ERR_MemberNeedsType, "C2").WithLocation(7, 12) ); } [Fact, WorkItem(55797, "https://github.com/dotnet/roslyn/issues/55797")] public void TwoParameterlessConstructors_Struct() { string source = @" public struct C { public C() : this() { } public C2() { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,18): error CS0121: The call is ambiguous between the following methods or properties: 'C.C()' and 'C.C()' // public C() : this() Diagnostic(ErrorCode.ERR_AmbigCall, "this").WithArguments("C.C()", "C.C()").WithLocation(4, 18), // (7,12): error CS1520: Method must have a return type // public C2() Diagnostic(ErrorCode.ERR_MemberNeedsType, "C2").WithLocation(7, 12) ); } } }
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/Compilers/Core/Portable/InternalUtilities/TextKeyedCache.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; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using System.Threading; namespace Roslyn.Utilities { internal class TextKeyedCache<T> where T : class { // immutable tuple - text and corresponding item // reference type because we want atomic assignments private class SharedEntryValue { public readonly string Text; public readonly T Item; public SharedEntryValue(string Text, T item) { this.Text = Text; this.Item = item; } } // TODO: Need to tweak the size with more scenarios. // for now this is what works well enough with // Roslyn C# compiler project // Size of local cache. private const int LocalSizeBits = 11; private const int LocalSize = (1 << LocalSizeBits); private const int LocalSizeMask = LocalSize - 1; // max size of shared cache. private const int SharedSizeBits = 16; private const int SharedSize = (1 << SharedSizeBits); private const int SharedSizeMask = SharedSize - 1; // size of bucket in shared cache. (local cache has bucket size 1). private const int SharedBucketBits = 4; private const int SharedBucketSize = (1 << SharedBucketBits); private const int SharedBucketSizeMask = SharedBucketSize - 1; // local cache // simple fast and not threadsafe cache // with limited size and "last add wins" expiration policy private readonly (string Text, int HashCode, T Item)[] _localTable = new (string Text, int HashCode, T Item)[LocalSize]; // shared threadsafe cache // slightly slower than local cache // we read this cache when having a miss in local cache // writes to local cache will update shared cache as well. private static readonly (int HashCode, SharedEntryValue Entry)[] s_sharedTable = new (int HashCode, SharedEntryValue Entry)[SharedSize]; // store a reference to shared cache locally // accessing a static field of a generic type could be nontrivial private readonly (int HashCode, SharedEntryValue Entry)[] _sharedTableInst = s_sharedTable; private readonly StringTable _strings; // random - used for selecting a victim in the shared cache. // TODO: consider whether a counter is random enough private Random? _random; internal TextKeyedCache() : this(null) { } // implement Poolable object pattern #region "Poolable" private TextKeyedCache(ObjectPool<TextKeyedCache<T>>? pool) { _pool = pool; _strings = new StringTable(); } private readonly ObjectPool<TextKeyedCache<T>>? _pool; private static readonly ObjectPool<TextKeyedCache<T>> s_staticPool = CreatePool(); private static ObjectPool<TextKeyedCache<T>> CreatePool() { var pool = new ObjectPool<TextKeyedCache<T>>( pool => new TextKeyedCache<T>(pool), Environment.ProcessorCount * 4); return pool; } public static TextKeyedCache<T> GetInstance() { return s_staticPool.Allocate(); } public void Free() { // leave cache content in the cache, just return it to the pool // Array.Clear(this.localTable, 0, this.localTable.Length); // Array.Clear(sharedTable, 0, sharedTable.Length); _pool?.Free(this); } #endregion // Poolable internal T? FindItem(char[] chars, int start, int len, int hashCode) { // get direct element reference to avoid extra range checks ref var localSlot = ref _localTable[LocalIdxFromHash(hashCode)]; var text = localSlot.Text; if (text != null && localSlot.HashCode == hashCode) { if (StringTable.TextEquals(text, chars.AsSpan(start, len))) { return localSlot.Item; } } SharedEntryValue? e = FindSharedEntry(chars, start, len, hashCode); if (e != null) { localSlot.HashCode = hashCode; localSlot.Text = e.Text; var tk = e.Item; localSlot.Item = tk; return tk; } return null!; } private SharedEntryValue? FindSharedEntry(char[] chars, int start, int len, int hashCode) { var arr = _sharedTableInst; int idx = SharedIdxFromHash(hashCode); SharedEntryValue? e = null; int hash; // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode for (int i = 1; i < SharedBucketSize + 1; i++) { (hash, e) = arr[idx]; if (e != null) { if (hash == hashCode && StringTable.TextEquals(e.Text, chars.AsSpan(start, len))) { break; } // this is not e we are looking for e = null; } else { // once we see unfilled entry, the rest of the bucket will be empty break; } idx = (idx + i) & SharedSizeMask; } return e; } internal void AddItem(char[] chars, int start, int len, int hashCode, T item) { var text = _strings.Add(chars, start, len); // add to the shared table first (in case someone looks for same item) var e = new SharedEntryValue(text, item); AddSharedEntry(hashCode, e); // add to the local table too ref var localSlot = ref _localTable[LocalIdxFromHash(hashCode)]; localSlot.HashCode = hashCode; localSlot.Text = text; localSlot.Item = item; } private void AddSharedEntry(int hashCode, SharedEntryValue e) { var arr = _sharedTableInst; int idx = SharedIdxFromHash(hashCode); // try finding an empty spot in the bucket // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode int curIdx = idx; for (int i = 1; i < SharedBucketSize + 1; i++) { if (arr[curIdx].Entry == null) { idx = curIdx; goto foundIdx; } curIdx = (curIdx + i) & SharedSizeMask; } // or pick a random victim within the bucket range // and replace with new entry var i1 = NextRandom() & SharedBucketSizeMask; idx = (idx + ((i1 * i1 + i1) / 2)) & SharedSizeMask; foundIdx: arr[idx].HashCode = hashCode; Volatile.Write(ref arr[idx].Entry, e); } private static int LocalIdxFromHash(int hash) { return hash & LocalSizeMask; } private static int SharedIdxFromHash(int hash) { // we can afford to mix some more hash bits here return (hash ^ (hash >> LocalSizeBits)) & SharedSizeMask; } private int NextRandom() { var r = _random; if (r != null) { return r.Next(); } r = new Random(); _random = r; return r.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.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using System.Threading; namespace Roslyn.Utilities { internal class TextKeyedCache<T> where T : class { // immutable tuple - text and corresponding item // reference type because we want atomic assignments private class SharedEntryValue { public readonly string Text; public readonly T Item; public SharedEntryValue(string Text, T item) { this.Text = Text; this.Item = item; } } // TODO: Need to tweak the size with more scenarios. // for now this is what works well enough with // Roslyn C# compiler project // Size of local cache. private const int LocalSizeBits = 11; private const int LocalSize = (1 << LocalSizeBits); private const int LocalSizeMask = LocalSize - 1; // max size of shared cache. private const int SharedSizeBits = 16; private const int SharedSize = (1 << SharedSizeBits); private const int SharedSizeMask = SharedSize - 1; // size of bucket in shared cache. (local cache has bucket size 1). private const int SharedBucketBits = 4; private const int SharedBucketSize = (1 << SharedBucketBits); private const int SharedBucketSizeMask = SharedBucketSize - 1; // local cache // simple fast and not threadsafe cache // with limited size and "last add wins" expiration policy private readonly (string Text, int HashCode, T Item)[] _localTable = new (string Text, int HashCode, T Item)[LocalSize]; // shared threadsafe cache // slightly slower than local cache // we read this cache when having a miss in local cache // writes to local cache will update shared cache as well. private static readonly (int HashCode, SharedEntryValue Entry)[] s_sharedTable = new (int HashCode, SharedEntryValue Entry)[SharedSize]; // store a reference to shared cache locally // accessing a static field of a generic type could be nontrivial private readonly (int HashCode, SharedEntryValue Entry)[] _sharedTableInst = s_sharedTable; private readonly StringTable _strings; // random - used for selecting a victim in the shared cache. // TODO: consider whether a counter is random enough private Random? _random; internal TextKeyedCache() : this(null) { } // implement Poolable object pattern #region "Poolable" private TextKeyedCache(ObjectPool<TextKeyedCache<T>>? pool) { _pool = pool; _strings = new StringTable(); } private readonly ObjectPool<TextKeyedCache<T>>? _pool; private static readonly ObjectPool<TextKeyedCache<T>> s_staticPool = CreatePool(); private static ObjectPool<TextKeyedCache<T>> CreatePool() { var pool = new ObjectPool<TextKeyedCache<T>>( pool => new TextKeyedCache<T>(pool), Environment.ProcessorCount * 4); return pool; } public static TextKeyedCache<T> GetInstance() { return s_staticPool.Allocate(); } public void Free() { // leave cache content in the cache, just return it to the pool // Array.Clear(this.localTable, 0, this.localTable.Length); // Array.Clear(sharedTable, 0, sharedTable.Length); _pool?.Free(this); } #endregion // Poolable internal T? FindItem(char[] chars, int start, int len, int hashCode) { // get direct element reference to avoid extra range checks ref var localSlot = ref _localTable[LocalIdxFromHash(hashCode)]; var text = localSlot.Text; if (text != null && localSlot.HashCode == hashCode) { if (StringTable.TextEquals(text, chars.AsSpan(start, len))) { return localSlot.Item; } } SharedEntryValue? e = FindSharedEntry(chars, start, len, hashCode); if (e != null) { localSlot.HashCode = hashCode; localSlot.Text = e.Text; var tk = e.Item; localSlot.Item = tk; return tk; } return null!; } private SharedEntryValue? FindSharedEntry(char[] chars, int start, int len, int hashCode) { var arr = _sharedTableInst; int idx = SharedIdxFromHash(hashCode); SharedEntryValue? e = null; int hash; // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode for (int i = 1; i < SharedBucketSize + 1; i++) { (hash, e) = arr[idx]; if (e != null) { if (hash == hashCode && StringTable.TextEquals(e.Text, chars.AsSpan(start, len))) { break; } // this is not e we are looking for e = null; } else { // once we see unfilled entry, the rest of the bucket will be empty break; } idx = (idx + i) & SharedSizeMask; } return e; } internal void AddItem(char[] chars, int start, int len, int hashCode, T item) { var text = _strings.Add(chars, start, len); // add to the shared table first (in case someone looks for same item) var e = new SharedEntryValue(text, item); AddSharedEntry(hashCode, e); // add to the local table too ref var localSlot = ref _localTable[LocalIdxFromHash(hashCode)]; localSlot.HashCode = hashCode; localSlot.Text = text; localSlot.Item = item; } private void AddSharedEntry(int hashCode, SharedEntryValue e) { var arr = _sharedTableInst; int idx = SharedIdxFromHash(hashCode); // try finding an empty spot in the bucket // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode int curIdx = idx; for (int i = 1; i < SharedBucketSize + 1; i++) { if (arr[curIdx].Entry == null) { idx = curIdx; goto foundIdx; } curIdx = (curIdx + i) & SharedSizeMask; } // or pick a random victim within the bucket range // and replace with new entry var i1 = NextRandom() & SharedBucketSizeMask; idx = (idx + ((i1 * i1 + i1) / 2)) & SharedSizeMask; foundIdx: arr[idx].HashCode = hashCode; Volatile.Write(ref arr[idx].Entry, e); } private static int LocalIdxFromHash(int hash) { return hash & LocalSizeMask; } private static int SharedIdxFromHash(int hash) { // we can afford to mix some more hash bits here return (hash ^ (hash >> LocalSizeBits)) & SharedSizeMask; } private int NextRandom() { var r = _random; if (r != null) { return r.Next(); } r = new Random(); _random = r; return r.Next(); } } }
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/Compilers/CSharp/Portable/Symbols/FunctionPointers/FunctionPointerParameterSymbol.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.Collections.Immutable; using System.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class FunctionPointerParameterSymbol : ParameterSymbol { private readonly FunctionPointerMethodSymbol _containingSymbol; public FunctionPointerParameterSymbol(TypeWithAnnotations typeWithAnnotations, RefKind refKind, int ordinal, FunctionPointerMethodSymbol containingSymbol, ImmutableArray<CustomModifier> refCustomModifiers) { TypeWithAnnotations = typeWithAnnotations; RefKind = refKind; Ordinal = ordinal; _containingSymbol = containingSymbol; RefCustomModifiers = refCustomModifiers; } public override TypeWithAnnotations TypeWithAnnotations { get; } public override RefKind RefKind { get; } public override int Ordinal { get; } public override Symbol ContainingSymbol => _containingSymbol; public override ImmutableArray<CustomModifier> RefCustomModifiers { get; } public override bool Equals(Symbol other, TypeCompareKind compareKind) { if (ReferenceEquals(this, other)) { return true; } if (!(other is FunctionPointerParameterSymbol param)) { return false; } return Equals(param, compareKind); } internal bool Equals(FunctionPointerParameterSymbol other, TypeCompareKind compareKind) => other.Ordinal == Ordinal && _containingSymbol.Equals(other._containingSymbol, compareKind); internal bool MethodEqualityChecks(FunctionPointerParameterSymbol other, TypeCompareKind compareKind) => FunctionPointerTypeSymbol.RefKindEquals(compareKind, RefKind, other.RefKind) && ((compareKind & TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds) != 0 || RefCustomModifiers.SequenceEqual(other.RefCustomModifiers)) && TypeWithAnnotations.Equals(other.TypeWithAnnotations, compareKind); public override int GetHashCode() { return Hash.Combine(_containingSymbol.GetHashCode(), Ordinal + 1); } internal int MethodHashCode() => Hash.Combine(TypeWithAnnotations.GetHashCode(), FunctionPointerTypeSymbol.GetRefKindForHashCode(RefKind).GetHashCode()); public override ImmutableArray<Location> Locations => ImmutableArray<Location>.Empty; public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => ImmutableArray<SyntaxReference>.Empty; public override bool IsDiscard => false; public override bool IsParams => false; public override bool IsImplicitlyDeclared => true; internal override MarshalPseudoCustomAttributeData? MarshallingInformation => null; internal override bool IsMetadataOptional => false; internal override bool IsMetadataIn => RefKind == RefKind.In; internal override bool IsMetadataOut => RefKind == RefKind.Out; internal override ConstantValue? ExplicitDefaultConstantValue => null; internal override bool IsIDispatchConstant => false; internal override bool IsIUnknownConstant => false; internal override bool IsCallerFilePath => false; internal override bool IsCallerLineNumber => false; internal override bool IsCallerMemberName => false; internal override int CallerArgumentExpressionParameterIndex => -1; internal override FlowAnalysisAnnotations FlowAnalysisAnnotations => FlowAnalysisAnnotations.None; internal override ImmutableHashSet<string> NotNullIfParameterNotNull => ImmutableHashSet<string>.Empty; internal override ImmutableArray<int> InterpolatedStringHandlerArgumentIndexes => ImmutableArray<int>.Empty; internal override bool HasInterpolatedStringHandlerArgumentError => 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.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class FunctionPointerParameterSymbol : ParameterSymbol { private readonly FunctionPointerMethodSymbol _containingSymbol; public FunctionPointerParameterSymbol(TypeWithAnnotations typeWithAnnotations, RefKind refKind, int ordinal, FunctionPointerMethodSymbol containingSymbol, ImmutableArray<CustomModifier> refCustomModifiers) { TypeWithAnnotations = typeWithAnnotations; RefKind = refKind; Ordinal = ordinal; _containingSymbol = containingSymbol; RefCustomModifiers = refCustomModifiers; } public override TypeWithAnnotations TypeWithAnnotations { get; } public override RefKind RefKind { get; } public override int Ordinal { get; } public override Symbol ContainingSymbol => _containingSymbol; public override ImmutableArray<CustomModifier> RefCustomModifiers { get; } public override bool Equals(Symbol other, TypeCompareKind compareKind) { if (ReferenceEquals(this, other)) { return true; } if (!(other is FunctionPointerParameterSymbol param)) { return false; } return Equals(param, compareKind); } internal bool Equals(FunctionPointerParameterSymbol other, TypeCompareKind compareKind) => other.Ordinal == Ordinal && _containingSymbol.Equals(other._containingSymbol, compareKind); internal bool MethodEqualityChecks(FunctionPointerParameterSymbol other, TypeCompareKind compareKind) => FunctionPointerTypeSymbol.RefKindEquals(compareKind, RefKind, other.RefKind) && ((compareKind & TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds) != 0 || RefCustomModifiers.SequenceEqual(other.RefCustomModifiers)) && TypeWithAnnotations.Equals(other.TypeWithAnnotations, compareKind); public override int GetHashCode() { return Hash.Combine(_containingSymbol.GetHashCode(), Ordinal + 1); } internal int MethodHashCode() => Hash.Combine(TypeWithAnnotations.GetHashCode(), FunctionPointerTypeSymbol.GetRefKindForHashCode(RefKind).GetHashCode()); public override ImmutableArray<Location> Locations => ImmutableArray<Location>.Empty; public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => ImmutableArray<SyntaxReference>.Empty; public override bool IsDiscard => false; public override bool IsParams => false; public override bool IsImplicitlyDeclared => true; internal override MarshalPseudoCustomAttributeData? MarshallingInformation => null; internal override bool IsMetadataOptional => false; internal override bool IsMetadataIn => RefKind == RefKind.In; internal override bool IsMetadataOut => RefKind == RefKind.Out; internal override ConstantValue? ExplicitDefaultConstantValue => null; internal override bool IsIDispatchConstant => false; internal override bool IsIUnknownConstant => false; internal override bool IsCallerFilePath => false; internal override bool IsCallerLineNumber => false; internal override bool IsCallerMemberName => false; internal override int CallerArgumentExpressionParameterIndex => -1; internal override FlowAnalysisAnnotations FlowAnalysisAnnotations => FlowAnalysisAnnotations.None; internal override ImmutableHashSet<string> NotNullIfParameterNotNull => ImmutableHashSet<string>.Empty; internal override ImmutableArray<int> InterpolatedStringHandlerArgumentIndexes => ImmutableArray<int>.Empty; internal override bool HasInterpolatedStringHandlerArgumentError => false; } }
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/VisualStudio/Core/Impl/Options/OptionBinding.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.ComponentModel; using Microsoft.CodeAnalysis.Options; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { internal class OptionBinding<T> : INotifyPropertyChanged { private readonly OptionStore _optionStore; private readonly Option2<T> _key; public event PropertyChangedEventHandler PropertyChanged; public OptionBinding(OptionStore optionStore, Option2<T> key) { _optionStore = optionStore; _key = key; _optionStore.OptionChanged += (sender, e) => { if (e.Option == _key) { PropertyChanged?.Raise(this, new PropertyChangedEventArgs(nameof(Value))); } }; } public T Value { get { return _optionStore.GetOption(_key); } set { _optionStore.SetOption(_key, 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. #nullable disable using System.ComponentModel; using Microsoft.CodeAnalysis.Options; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { internal class OptionBinding<T> : INotifyPropertyChanged { private readonly OptionStore _optionStore; private readonly Option2<T> _key; public event PropertyChangedEventHandler PropertyChanged; public OptionBinding(OptionStore optionStore, Option2<T> key) { _optionStore = optionStore; _key = key; _optionStore.OptionChanged += (sender, e) => { if (e.Option == _key) { PropertyChanged?.Raise(this, new PropertyChangedEventArgs(nameof(Value))); } }; } public T Value { get { return _optionStore.GetOption(_key); } set { _optionStore.SetOption(_key, value); } } } }
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/Features/Core/Portable/NavigateTo/NavigateToSearcher.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; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.NavigateTo { internal class NavigateToSearcher { private readonly INavigateToSearcherHost _host; private readonly Solution _solution; private readonly IAsynchronousOperationListener _asyncListener; private readonly INavigateToSearchCallback _callback; private readonly string _searchPattern; private readonly bool _searchCurrentDocument; private readonly IImmutableSet<string> _kinds; private readonly Document? _currentDocument; private readonly IStreamingProgressTracker _progress; private readonly Document? _activeDocument; private readonly ImmutableArray<Document> _visibleDocuments; private NavigateToSearcher( INavigateToSearcherHost host, Solution solution, IAsynchronousOperationListener asyncListener, INavigateToSearchCallback callback, string searchPattern, bool searchCurrentDocument, IImmutableSet<string> kinds) { _host = host; _solution = solution; _asyncListener = asyncListener; _callback = callback; _searchPattern = searchPattern; _searchCurrentDocument = searchCurrentDocument; _kinds = kinds; _progress = new StreamingProgressTracker((current, maximum, ct) => { callback.ReportProgress(current, maximum); return new ValueTask(); }); var docTrackingService = _solution.Workspace.Services.GetRequiredService<IDocumentTrackingService>(); // If the workspace is tracking documents, use that to prioritize our search // order. That way we provide results for the documents the user is working // on faster than the rest of the solution. _activeDocument = docTrackingService.GetActiveDocument(_solution); _visibleDocuments = docTrackingService.GetVisibleDocuments(_solution) .WhereAsArray(d => d != _activeDocument); if (_searchCurrentDocument) { _currentDocument = _activeDocument; } } public static NavigateToSearcher Create( Solution solution, IAsynchronousOperationListener asyncListener, INavigateToSearchCallback callback, string searchPattern, bool searchCurrentDocument, IImmutableSet<string> kinds, CancellationToken disposalToken, INavigateToSearcherHost? host = null) { host ??= new DefaultNavigateToSearchHost(solution, asyncListener, disposalToken); return new NavigateToSearcher(host, solution, asyncListener, callback, searchPattern, searchCurrentDocument, kinds); } internal async Task SearchAsync(CancellationToken cancellationToken) { var isFullyLoaded = true; try { using var navigateToSearch = Logger.LogBlock(FunctionId.NavigateTo_Search, KeyValueLogMessage.Create(LogType.UserAction), cancellationToken); using var asyncToken = _asyncListener.BeginAsyncOperation(GetType() + ".Search"); // We consider ourselves fully loaded when both the project system has completed loaded us, and we've // totally hydrated the oop side. Until that happens, we'll attempt to return cached data from languages // that support that. isFullyLoaded = await _host.IsFullyLoadedAsync(cancellationToken).ConfigureAwait(false); await SearchAllProjectsAsync(isFullyLoaded, cancellationToken).ConfigureAwait(false); } catch (OperationCanceledException) { } finally { // providing this extra information will make UI to show indication to users // that result might not contain full data _callback.Done(isFullyLoaded); } } private async Task SearchAllProjectsAsync(bool isFullyLoaded, CancellationToken cancellationToken) { var orderedProjects = GetOrderedProjectsToProcess(); var (itemsReported, projectResults) = await ProcessProjectsAsync(orderedProjects, isFullyLoaded, cancellationToken).ConfigureAwait(false); // If we're fully loaded then we're done at this point. All the searches would have been against the latest // computed data and we don't need to do anything else. if (isFullyLoaded) return; // We weren't fully loaded *but* we reported some items to the user, then consider that good enough for now. // The user will have some results they can use, and (in the case that we actually examined the cache for // data) we will tell the user that the results may be incomplete/inaccurate and they should try again soon. if (itemsReported > 0) return; // We didn't have any items reported *and* we weren't fully loaded. If it turns out that some of our // projects were using cached data then we can try searching them again, but this tell them to use the // latest data. The ensures the user at least gets some result instead of nothing. var projectsUsingCache = projectResults.SelectAsArray(t => t.location == NavigateToSearchLocation.Cache, t => t.project); await ProcessProjectsAsync(ImmutableArray.Create(projectsUsingCache), isFullyLoaded: true, cancellationToken).ConfigureAwait(false); } /// <summary> /// Returns a sequence of groups of projects to process. The sequence is in priority order, and all projects in /// a particular group should be processed before the next group. This allows us to associate CPU resources in /// likely areas the user wants, while also still allowing for good parallelization. Specifically, we consider /// the active-document the most important to get results for, as some users use navigate-to to navigate within /// the doc they are editing. So we want those results to appear as quick as possible, without the search for /// them contending with the searches for other projects for CPU time. /// </summary> private ImmutableArray<ImmutableArray<Project>> GetOrderedProjectsToProcess() { // If we're only searching the current doc, we don't need to examine anything else but that. if (_searchCurrentDocument) { // Note: _currentDocument may still be null. Just because the user asked to search current document // doesn't mean we were able to map the view to an active doc inside Roslyn. In this case, we just // don't search anything. var project = _currentDocument?.Project; return project == null ? ImmutableArray<ImmutableArray<Project>>.Empty : ImmutableArray.Create(ImmutableArray.Create(project)); } using var result = TemporaryArray<ImmutableArray<Project>>.Empty; using var _ = PooledHashSet<Project>.GetInstance(out var processedProjects); // First, if there's an active document, search that project first, prioritizing that active document and // all visible documents from it. if (_activeDocument != null) { processedProjects.Add(_activeDocument.Project); result.Add(ImmutableArray.Create(_activeDocument.Project)); } // Next process all visible docs that were not from the active project. using var buffer = TemporaryArray<Project>.Empty; foreach (var doc in _visibleDocuments) { if (processedProjects.Add(doc.Project)) buffer.Add(doc.Project); } if (buffer.Count > 0) result.Add(buffer.ToImmutableAndClear()); // Finally, process the remainder of projects foreach (var project in _solution.Projects) { if (processedProjects.Add(project)) buffer.Add(project); } if (buffer.Count > 0) result.Add(buffer.ToImmutableAndClear()); return result.ToImmutableAndClear(); } /// <summary> /// Given a search within a particular project, this returns any documents within that project that should take /// precedence when searching. This allows results to get to the user more quickly for common cases (like using /// nav-to to find results in the file you currently have open /// </summary> private ImmutableArray<Document> GetPriorityDocuments(Project project) { using var _ = ArrayBuilder<Document>.GetInstance(out var result); if (_activeDocument?.Project == project) result.Add(_activeDocument); foreach (var doc in _visibleDocuments) { if (doc.Project == project) result.Add(doc); } result.RemoveDuplicates(); return result.ToImmutable(); } private async Task<(int itemsReported, ImmutableArray<(Project project, NavigateToSearchLocation location)>)> ProcessProjectsAsync( ImmutableArray<ImmutableArray<Project>> orderedProjects, bool isFullyLoaded, CancellationToken cancellationToken) { await _progress.AddItemsAsync(orderedProjects.Sum(p => p.Length), cancellationToken).ConfigureAwait(false); using var _ = ArrayBuilder<(Project project, NavigateToSearchLocation location)>.GetInstance(out var result); var seenItems = new HashSet<INavigateToSearchResult>(NavigateToSearchResultComparer.Instance); foreach (var projectGroup in orderedProjects) result.AddRange(await Task.WhenAll(projectGroup.Select(p => Task.Run(() => SearchAsync(p, isFullyLoaded, seenItems, cancellationToken)))).ConfigureAwait(false)); return (seenItems.Count, result.ToImmutable()); } private async Task<(Project project, NavigateToSearchLocation location)> SearchAsync( Project project, bool isFullyLoaded, HashSet<INavigateToSearchResult> seenItems, CancellationToken cancellationToken) { try { var location = await SearchCoreAsync(project, isFullyLoaded, seenItems, cancellationToken).ConfigureAwait(false); return (project, location); } finally { await _progress.ItemCompletedAsync(cancellationToken).ConfigureAwait(false); } } private async Task<NavigateToSearchLocation> SearchCoreAsync( Project project, bool isFullyLoaded, HashSet<INavigateToSearchResult> seenItems, CancellationToken cancellationToken) { // If they don't even support the service, then always show them as having done the // complete search. That way we don't call back into this project ever. var service = _host.GetNavigateToSearchService(project); if (service == null) return NavigateToSearchLocation.Latest; if (_searchCurrentDocument) { Contract.ThrowIfNull(_currentDocument); return await service.SearchDocumentAsync( _currentDocument, _searchPattern, _kinds, OnResultFound, isFullyLoaded, cancellationToken).ConfigureAwait(false); } else { return await service.SearchProjectAsync( project, GetPriorityDocuments(project), _searchPattern, _kinds, OnResultFound, isFullyLoaded, cancellationToken).ConfigureAwait(false); } Task OnResultFound(INavigateToSearchResult result) { // If we're seeing a dupe in another project, then filter it out here. The results from // the individual projects will already contain the information about all the projects // leading to a better condensed view that doesn't look like it contains duplicate info. lock (seenItems) { if (!seenItems.Add(result)) return Task.CompletedTask; } return _callback.AddItemAsync(project, result, 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; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.NavigateTo { internal class NavigateToSearcher { private readonly INavigateToSearcherHost _host; private readonly Solution _solution; private readonly IAsynchronousOperationListener _asyncListener; private readonly INavigateToSearchCallback _callback; private readonly string _searchPattern; private readonly bool _searchCurrentDocument; private readonly IImmutableSet<string> _kinds; private readonly Document? _currentDocument; private readonly IStreamingProgressTracker _progress; private readonly Document? _activeDocument; private readonly ImmutableArray<Document> _visibleDocuments; private NavigateToSearcher( INavigateToSearcherHost host, Solution solution, IAsynchronousOperationListener asyncListener, INavigateToSearchCallback callback, string searchPattern, bool searchCurrentDocument, IImmutableSet<string> kinds) { _host = host; _solution = solution; _asyncListener = asyncListener; _callback = callback; _searchPattern = searchPattern; _searchCurrentDocument = searchCurrentDocument; _kinds = kinds; _progress = new StreamingProgressTracker((current, maximum, ct) => { callback.ReportProgress(current, maximum); return new ValueTask(); }); var docTrackingService = _solution.Workspace.Services.GetRequiredService<IDocumentTrackingService>(); // If the workspace is tracking documents, use that to prioritize our search // order. That way we provide results for the documents the user is working // on faster than the rest of the solution. _activeDocument = docTrackingService.GetActiveDocument(_solution); _visibleDocuments = docTrackingService.GetVisibleDocuments(_solution) .WhereAsArray(d => d != _activeDocument); if (_searchCurrentDocument) { _currentDocument = _activeDocument; } } public static NavigateToSearcher Create( Solution solution, IAsynchronousOperationListener asyncListener, INavigateToSearchCallback callback, string searchPattern, bool searchCurrentDocument, IImmutableSet<string> kinds, CancellationToken disposalToken, INavigateToSearcherHost? host = null) { host ??= new DefaultNavigateToSearchHost(solution, asyncListener, disposalToken); return new NavigateToSearcher(host, solution, asyncListener, callback, searchPattern, searchCurrentDocument, kinds); } internal async Task SearchAsync(CancellationToken cancellationToken) { var isFullyLoaded = true; try { using var navigateToSearch = Logger.LogBlock(FunctionId.NavigateTo_Search, KeyValueLogMessage.Create(LogType.UserAction), cancellationToken); using var asyncToken = _asyncListener.BeginAsyncOperation(GetType() + ".Search"); // We consider ourselves fully loaded when both the project system has completed loaded us, and we've // totally hydrated the oop side. Until that happens, we'll attempt to return cached data from languages // that support that. isFullyLoaded = await _host.IsFullyLoadedAsync(cancellationToken).ConfigureAwait(false); await SearchAllProjectsAsync(isFullyLoaded, cancellationToken).ConfigureAwait(false); } catch (OperationCanceledException) { } finally { // providing this extra information will make UI to show indication to users // that result might not contain full data _callback.Done(isFullyLoaded); } } private async Task SearchAllProjectsAsync(bool isFullyLoaded, CancellationToken cancellationToken) { var orderedProjects = GetOrderedProjectsToProcess(); var (itemsReported, projectResults) = await ProcessProjectsAsync(orderedProjects, isFullyLoaded, cancellationToken).ConfigureAwait(false); // If we're fully loaded then we're done at this point. All the searches would have been against the latest // computed data and we don't need to do anything else. if (isFullyLoaded) return; // We weren't fully loaded *but* we reported some items to the user, then consider that good enough for now. // The user will have some results they can use, and (in the case that we actually examined the cache for // data) we will tell the user that the results may be incomplete/inaccurate and they should try again soon. if (itemsReported > 0) return; // We didn't have any items reported *and* we weren't fully loaded. If it turns out that some of our // projects were using cached data then we can try searching them again, but this tell them to use the // latest data. The ensures the user at least gets some result instead of nothing. var projectsUsingCache = projectResults.SelectAsArray(t => t.location == NavigateToSearchLocation.Cache, t => t.project); await ProcessProjectsAsync(ImmutableArray.Create(projectsUsingCache), isFullyLoaded: true, cancellationToken).ConfigureAwait(false); } /// <summary> /// Returns a sequence of groups of projects to process. The sequence is in priority order, and all projects in /// a particular group should be processed before the next group. This allows us to associate CPU resources in /// likely areas the user wants, while also still allowing for good parallelization. Specifically, we consider /// the active-document the most important to get results for, as some users use navigate-to to navigate within /// the doc they are editing. So we want those results to appear as quick as possible, without the search for /// them contending with the searches for other projects for CPU time. /// </summary> private ImmutableArray<ImmutableArray<Project>> GetOrderedProjectsToProcess() { // If we're only searching the current doc, we don't need to examine anything else but that. if (_searchCurrentDocument) { // Note: _currentDocument may still be null. Just because the user asked to search current document // doesn't mean we were able to map the view to an active doc inside Roslyn. In this case, we just // don't search anything. var project = _currentDocument?.Project; return project == null ? ImmutableArray<ImmutableArray<Project>>.Empty : ImmutableArray.Create(ImmutableArray.Create(project)); } using var result = TemporaryArray<ImmutableArray<Project>>.Empty; using var _ = PooledHashSet<Project>.GetInstance(out var processedProjects); // First, if there's an active document, search that project first, prioritizing that active document and // all visible documents from it. if (_activeDocument != null) { processedProjects.Add(_activeDocument.Project); result.Add(ImmutableArray.Create(_activeDocument.Project)); } // Next process all visible docs that were not from the active project. using var buffer = TemporaryArray<Project>.Empty; foreach (var doc in _visibleDocuments) { if (processedProjects.Add(doc.Project)) buffer.Add(doc.Project); } if (buffer.Count > 0) result.Add(buffer.ToImmutableAndClear()); // Finally, process the remainder of projects foreach (var project in _solution.Projects) { if (processedProjects.Add(project)) buffer.Add(project); } if (buffer.Count > 0) result.Add(buffer.ToImmutableAndClear()); return result.ToImmutableAndClear(); } /// <summary> /// Given a search within a particular project, this returns any documents within that project that should take /// precedence when searching. This allows results to get to the user more quickly for common cases (like using /// nav-to to find results in the file you currently have open /// </summary> private ImmutableArray<Document> GetPriorityDocuments(Project project) { using var _ = ArrayBuilder<Document>.GetInstance(out var result); if (_activeDocument?.Project == project) result.Add(_activeDocument); foreach (var doc in _visibleDocuments) { if (doc.Project == project) result.Add(doc); } result.RemoveDuplicates(); return result.ToImmutable(); } private async Task<(int itemsReported, ImmutableArray<(Project project, NavigateToSearchLocation location)>)> ProcessProjectsAsync( ImmutableArray<ImmutableArray<Project>> orderedProjects, bool isFullyLoaded, CancellationToken cancellationToken) { await _progress.AddItemsAsync(orderedProjects.Sum(p => p.Length), cancellationToken).ConfigureAwait(false); using var _ = ArrayBuilder<(Project project, NavigateToSearchLocation location)>.GetInstance(out var result); var seenItems = new HashSet<INavigateToSearchResult>(NavigateToSearchResultComparer.Instance); foreach (var projectGroup in orderedProjects) result.AddRange(await Task.WhenAll(projectGroup.Select(p => Task.Run(() => SearchAsync(p, isFullyLoaded, seenItems, cancellationToken)))).ConfigureAwait(false)); return (seenItems.Count, result.ToImmutable()); } private async Task<(Project project, NavigateToSearchLocation location)> SearchAsync( Project project, bool isFullyLoaded, HashSet<INavigateToSearchResult> seenItems, CancellationToken cancellationToken) { try { var location = await SearchCoreAsync(project, isFullyLoaded, seenItems, cancellationToken).ConfigureAwait(false); return (project, location); } finally { await _progress.ItemCompletedAsync(cancellationToken).ConfigureAwait(false); } } private async Task<NavigateToSearchLocation> SearchCoreAsync( Project project, bool isFullyLoaded, HashSet<INavigateToSearchResult> seenItems, CancellationToken cancellationToken) { // If they don't even support the service, then always show them as having done the // complete search. That way we don't call back into this project ever. var service = _host.GetNavigateToSearchService(project); if (service == null) return NavigateToSearchLocation.Latest; if (_searchCurrentDocument) { Contract.ThrowIfNull(_currentDocument); return await service.SearchDocumentAsync( _currentDocument, _searchPattern, _kinds, OnResultFound, isFullyLoaded, cancellationToken).ConfigureAwait(false); } else { return await service.SearchProjectAsync( project, GetPriorityDocuments(project), _searchPattern, _kinds, OnResultFound, isFullyLoaded, cancellationToken).ConfigureAwait(false); } Task OnResultFound(INavigateToSearchResult result) { // If we're seeing a dupe in another project, then filter it out here. The results from // the individual projects will already contain the information about all the projects // leading to a better condensed view that doesn't look like it contains duplicate info. lock (seenItems) { if (!seenItems.Add(result)) return Task.CompletedTask; } return _callback.AddItemAsync(project, result, cancellationToken); } } } }
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/EditorFeatures/CSharpTest/EditAndContinue/BreakpointSpansTests.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 System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.EditAndContinue; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.Debugging { [Trait(Traits.Feature, Traits.Features.DebuggingBreakpoints)] public class BreakpointSpansTests { #region Helpers private static void TestSpan(string markup, ParseOptions options = null) => Test(markup, isMissing: false, isLine: false, options: options); private static void TestMissing(string markup) => Test(markup, isMissing: true, isLine: false); private static void TestLine(string markup) => Test(markup, isMissing: false, isLine: true); private static void Test(string markup, bool isMissing, bool isLine, ParseOptions options = null) { MarkupTestFile.GetPositionAndSpan( markup, out var source, out var position, out TextSpan? expectedSpan); var tree = SyntaxFactory.ParseSyntaxTree(source, options); var hasBreakpoint = BreakpointSpans.TryGetBreakpointSpan( tree, position.Value, CancellationToken.None, out var breakpointSpan); if (isLine) { Assert.True(hasBreakpoint); Assert.True(breakpointSpan.Length == 0); } else if (isMissing) { Assert.False(hasBreakpoint); } else { Assert.True(hasBreakpoint); Assert.Equal(expectedSpan.Value, breakpointSpan); } } /// <summary> /// Verifies all breakpoint spans of the declaration node marked by $$ in <paramref name="markup"/> /// and it's breakpoint span envelope (span that contains all breakpoint span of the declaration). /// /// Only test declarations that have a single possible body (e.g. <see cref="VariableDeclaratorSyntax"/>, /// not <see cref="FieldDeclarationSyntax"/> or <see cref="VariableDeclarationSyntax"/>). /// </summary> private static void VerifyAllSpansInDeclaration<TDeclaration>(string markup) where TDeclaration : SyntaxNode { MarkupTestFile.GetPositionAndSpans(markup, out var source, out var position, out ImmutableArray<TextSpan> expectedSpans); var tree = SyntaxFactory.ParseSyntaxTree(source); var root = tree.GetRoot(); var declarationNode = root.FindToken(position).Parent.FirstAncestorOrSelf<TDeclaration>(); var actualSpans = GetBreakpointSequence(declarationNode, position).ToArray(); AssertEx.Equal(expectedSpans, actualSpans, itemSeparator: "\r\n", itemInspector: span => "[|" + source.Substring(span.Start, span.Length) + "|]"); var expectedEnvelope = expectedSpans.IsEmpty ? default : TextSpan.FromBounds(expectedSpans[0].Start, expectedSpans[^1].End); Assert.NotNull(declarationNode); var actualEnvelope = BreakpointSpans.GetEnvelope(declarationNode); Assert.Equal(expectedEnvelope, actualEnvelope); } public static IEnumerable<TextSpan> GetBreakpointSequence(SyntaxNode root, int position) { TextSpan lastSpan = default; var endPosition = root.Span.End; for (var p = position; p < endPosition; p++) { if (BreakpointSpans.TryGetClosestBreakpointSpan(root, p, out var span) && span.Start > lastSpan.Start) { lastSpan = span; yield return span; } } } #endregion [Fact] public void GetBreakpointSequence1() { VerifyAllSpansInDeclaration<MethodDeclarationSyntax>(@" class C { $$void Goo() [|{|] [|int d = 5;|] [|int a = 1|], [|b = 2|], [|c = 3|]; for ([|int i = 0|], [|j = 1|], [|k = 2|]; [|i < 10|]; [|i++|], [|j++|], [|k--|]) [|while (b > 0)|] [|{|] [|if (c < b)|] try [|{|] [|System.Console.WriteLine(a);|] [|}|] [|catch (Exception e)|] [|{|] [|System.Console.WriteLine(e);|] [|}|] finally [|{|] [|}|] else [|if (b < 10)|] [|System.Console.WriteLine(b);|] else [|System.Console.WriteLine(c);|] [|}|] [|}|] }"); } [Fact] public void GetBreakpointSequence2() { VerifyAllSpansInDeclaration<MethodDeclarationSyntax>(@" class C { $$void Goo() [|{|] do [|{|] label: [|i++;|] [|var l = new List<int>() { F(), F(), };|] [|break;|] [|continue;|] [|}|] [|while (a);|] [|goto label;|] [|}|] }"); } [Fact] public void GetBreakpointSequence3() { VerifyAllSpansInDeclaration<MethodDeclarationSyntax>(@" class C { $$int Goo() [|{|] [|switch(a)|] { case 1: case 2: [|break;|] case 3: [|goto case 4;|] case 4: [|throw new Exception();|] [|goto default;|] default: [|return 1;|] } [|return 2;|] [|}|] }"); } [Fact] public void GetBreakpointSequence4() { VerifyAllSpansInDeclaration<MethodDeclarationSyntax>(@" class C { $$IEnumerable<int> Goo() [|{|] [|yield return 1;|] [|foreach|] ([|var f|] [|in|] [|Goo()|]) [|{|] [|using (z)|] using ([|var q = null|]) using ([|var u = null|], [|v = null|]) [|{|] [|while (a)|] [|yield return 2;|] [|}|] [|}|] fixed([|int* a = new int[1]|], [|b = new int[1]|], [|c = new int[1]|]) [|{|][|}|] [|yield break;|] [|}|] }"); } [Fact] public void GetBreakpointSequence5() { VerifyAllSpansInDeclaration<MethodDeclarationSyntax>(@" class C { $$IEnumerable<int> Goo() [|{|][|while(t)|][|{|][|}|][|}|] }"); } [Fact] public void GetBreakpointSequence6() { VerifyAllSpansInDeclaration<MethodDeclarationSyntax>(@" class C { $$IEnumerable<int> Goo() [|{|] checked [|{|] const int a = 1; const int b = 2; unchecked [|{|] unsafe [|{|] [|lock(l)|] [|{|] [|;|] [|}|] [|}|] [|}|] [|}|] [|}|] }"); } #region Switch Expression [Fact] public void SwitchExpression_All() { VerifyAllSpansInDeclaration<MethodDeclarationSyntax>(@" class C { $$IEnumerable<int> Goo() [|{|] [|_ = M2( c switch { (1) _ [|when f|] => [|M(0)|], (3) _ [|when f|] => [|M(1)|], (1, 2) _ [|when f|] => [|M(0)|], (3, 4) _ [|when f|] => [|M(2)|], _ => [|M(4)|], }, M(5));|] [|}|] }"); } [Fact] public void SwitchExpression01() { TestSpan( @"class C { void Goo() { $$ [|_ = e switch { 1 when f => 2, 3 when g => 4, _ => 5, };|] } }"); } [Fact] public void SwitchExpression02() { TestSpan( @"class C { void Goo() { [|_ = e switch $${ 1 when f => 2, 3 when g => 4, _ => 5, };|] } }"); } [Fact] public void SwitchExpression03() { TestSpan( @"class C { void Goo() { _ = e switch {$$ 1 [|when f|] => 2, 3 when g => 4, _ => 5, }; } }"); } [Fact] public void SwitchExpression04() { TestSpan( @"class C { void Goo() { _ = e switch { 1 [|when f|] $$=> 2, 3 when g => 4, _ => 5, }; } }"); } [Fact] public void SwitchExpression05() { TestSpan( @"class C { void Goo() { _ = e switch { 1 when f =$$> [|2|], 3 when g => 4, _ => 5, }; } }"); } [Fact] public void SwitchExpression06() { TestSpan( @"class C { void Goo() { _ = e switch { 1 when f => [|2|],$$ 3 when g => 4, _ => 5, }; } }"); } [Fact] public void SwitchExpression07() { TestSpan( @"class C { void Goo() { _ = e switch { 1 when f => 2, $$ 3 [|when g|] => 4, _ => 5, }; } }"); } [Fact] public void SwitchExpression08() { TestSpan( @"class C { void Goo() { _ = e switch { 1 when f => 2, 3 when g => [|4|],$$ _ => 5, }; } }"); } [Fact] public void SwitchExpression09() { TestSpan( @"class C { void Goo() { _ = e switch { 1 when f => 2, 3 when g => 4, $$ _ => [|5|], }; } }"); } [Fact] public void SwitchExpression10() { TestSpan( @"class C { void Goo() { _ = e switch { 1 when f => 2, 3 when g => 4, _ => [|5|],$$ }; } }"); } [Fact] public void SwitchExpression11() { TestSpan( @"class C { void Goo() { _ = e switch { 1 when f => 2, 3 when g => 4, _ => [|5|], $$}; } }"); } [Fact] public void SwitchExpression12() { TestSpan( @"class C { void Goo() { [|_ = e switch { 1 when f => 2, 3 when g => 4, _ => 5, }$$;|] } }"); } #endregion #region For and ForEach [Fact] public void ForStatementInitializer1a() { TestSpan( @"class C { void Goo() { $$ for ([|i = 0|], j = 0; i < 10 && j < 10; i++, j++) { } } }"); } [Fact] public void ForStatementInitializer1b() { TestSpan( @"class C { void Goo() { f$$or ([|i = 0|], j = 0; i < 10 && j < 10; i++, j++) { } } }"); } [Fact] public void ForStatementInitializer1c() { TestSpan( @"class C { void Goo() { for ([|i $$= 0|], j = 0; i < 10 && j < 10; i++, j++) { } } }"); } [Fact] public void ForStatementInitializer1d() { TestSpan( @"class C { void Goo() { for $$ ( [|i = 0|], j = 0; i < 10 && j < 10; i++, j++) { } } }"); } [Fact] public void ForStatementInitializer2() { TestSpan( @"class C { void Goo() { for (i = 0, [|$$j = 0|]; i < 10 && j < 10; i++, j++) { } } }"); } [Fact] public void ForStatementInitializer3() => TestSpan("class C { void M() { for([|i = 0$$|]; ; }; }"); [Fact] public void ForStatementCondition() { TestSpan( @"class C { void Goo() { for (i = 0, j = 0; [|i < 10 && j < $$10|]; i++, j++) { } } }"); } [Fact] public void ForStatementIncrementor1() { TestSpan( @"class C { void Goo() { for (i = 0, j = 0; i < 10 && j < 10; [|i+$$+|], j++) { } } }"); } [Fact] public void ForStatementIncrementor2() { TestSpan( @"class C { void Goo() { for (i = 0, j = 0; i < 10 && j < 10; i++, [|$$j++|]) { } } }"); } [Fact] public void ForEachStatementExpression() { TestSpan( @"class C { void Goo() { foreach (var v in [|Goo().B$$ar()|]) { } } }"); } [Fact] public void ForEachDeconstructionStatementExpression() { TestSpan( @"class C { void Goo() { foreach (var (x, y) in [|Goo().B$$ar()|]) { } } }"); } #endregion #region Lambdas [Fact] public void SimpleLambdaBody() { TestSpan( @"class C { void Goo() { Func<string> f = s => [|G$$oo()|]; } }"); } [Fact] public void ParenthesizedLambdaBody() { TestSpan( @"class C { void Goo() { Func<string> f = (s, i) => [|G$$oo()|]; } }"); } [Fact] public void AnonymousMethod1() { TestSpan( @"class C { void Goo() { Func<int> f = delegate [|$${|] return 1; }; } }"); } [Fact] public void AnonymousMethod2() { TestSpan( @"class C { void Goo() { Func<int> f = delegate { [|$$return 1;|] }; } }"); } #endregion #region Queries [Fact] public void FirstFromClauseExpression() { TestSpan( @"class C { void Goo() { [|var q = from x in bl$$ah() from y in quux().z() select y;|] } }"); } [Fact] public void SecondFromClauseExpression() { TestSpan( @"class C { void Goo() { var q = from x in blah() from y in [|quux().z$$()|] select y; } }"); } [Fact] public void FromInQueryContinuation1() { TestSpan( @"class C { void Goo() { var q = from x in blah() from y in quux().z() group x by y into g from m in [|g.C$$ount()|] select m.Blah(); } }"); } [Fact] public void FromInQueryContinuation2() { TestSpan( @"class C { void Goo() { var q = from x in blah() from y in quux().z() group x by y into g $$ from m in [|g.Count()|] select m.Blah(); } }"); } [Fact] public void JoinClauseLeftExpression() { TestSpan( @"class C { void Goo() { var q = from x in blah() join a in alpha on [|left().exp$$r()|] equals right().expr() select y; } }"); } [Fact] public void JoinClauseRightExpression() { TestSpan( @"class C { void Goo() { var q = from x in blah() join a in alpha on left().expr() equals [|righ$$t().expr()|] select y; } }"); } [Fact] public void LetClauseExpression() { TestSpan( @"class C { void Goo() { var q = from x in blah() join a in alpha on left().expr() equals right.expr() let a = [|expr().$$expr()|] select y; } }"); } [Fact] public void WhereClauseExpression() { TestSpan( @"class C { void Goo() { var q = from x in blah() join a in alpha on left().expr() equals right.expr() where [|expr().$$expr()|] select y; } }"); } [Fact] public void WhereClauseKeyword() { TestSpan( @"class C { void Goo() { var q = from x in blah() whe$$re [|expr().expr()|] select y; } }"); } [Fact] public void SimpleOrdering1() { TestSpan( @"class C { void Goo() { var q = from x in blah() join a in alpha on left().expr() equals right.expr() orderby [|expr().$$expr()|] select y; } }"); } [Fact] public void SimpleOrdering2() { TestSpan( @"class C { void Goo() { var q = from x in blah() join a in alpha on left().expr() equals right.expr() orderby goo, [|expr().$$expr()|] select y; } }"); } [Fact] public void AscendingOrdering1() { TestSpan( @"class C { void Goo() { var q = from x in blah() join a in alpha on left().expr() equals right.expr() orderby [|expr().$$expr()|] ascending select y; } }"); } [Fact] public void AscendingOrdering2() { TestSpan( @"class C { void Goo() { var q = from x in blah() join a in alpha on left().expr() equals right.expr() orderby goo, [|expr().$$expr()|] ascending select y; } }"); } [Fact] public void DescendingOrdering1() { TestSpan( @"class C { void Goo() { var q = from x in blah() join a in alpha on left().expr() equals right.expr() orderby [|expr().$$expr()|] descending select y; } }"); } [Fact] public void DescendingOrdering2() { TestSpan( @"class C { void Goo() { var q = from x in blah() join a in alpha on left().expr() equals right.expr() orderby goo, [|expr().$$expr()|] descending select y; } }"); } [Fact] public void OrderByKeyword() => TestSpan("class C { void M() { from string s in null ord$$erby [|s.A|] ascending } }"); [Fact] public void AscendingKeyword() => TestSpan("class C { void M() { from string s in null orderby [|s.A|] $$ascending } }"); [Fact] public void SelectExpression() { TestSpan( @"class C { void Goo() { var q = from x in blah() join a in alpha on left().expr() equals right.expr() orderby goo, expr().expr() descending select [|y.$$blah()|]; } }"); } [Fact] public void AnonymousTypeAfterSelect() { TestSpan( @"class C { public void () { var q = from c in categories join p in products on c equals p.Category into ps select [|new { Category = c, $$Products = ps }|]; } }"); } [Fact] public void GroupExpression() { TestSpan( @"class C { void Goo() { var q = from x in blah() join a in alpha on left().expr() equals right.expr() orderby goo, expr().expr() descending group [|bar()$$.goo()|] by blah().zap() select y.blah(); } }"); } [Fact] public void GroupByKeyword() { TestSpan( @"class C { void Goo() { var q = from x in blah() join a in alpha on left().expr() equals right.expr() orderby goo, expr().expr() descending group [|bar().goo()|] b$$y blah().zap() select y.blah(); } }"); } [Fact] public void GroupByExpression() { TestSpan( @"class C { void Goo() { var q = from x in blah() join a in alpha on left().expr() equals right.expr() orderby goo, expr().expr() descending group bar().goo() by [|blah()$$.zap()|] select y.blah(); } }"); } [Fact] public void InFrontOfFirstFromClause() { TestSpan( @"class C { void Goo() { [|var q = $$ from x in blah() from y in zap() let m = quux() join a in alpha on left().expr() equals right.expr() orderby goo, expr().expr() descending group bar().goo() by blah().zap() into g select y.blah();|] } }"); } [Fact] public void InFrontOfSecondFromClause() { TestSpan( @"class C { void Goo() { var q = from x in blah() $$ from y in [|zap()|] let m = quux() join a in alpha on left().expr() equals right.expr() orderby goo, expr().expr() descending group bar().goo() by blah().zap() into g select y.blah(); } }"); } [Fact] public void InFrontOfLetClause() { TestSpan( @"class C { void Goo() { var q = from x in blah() from y in zap() $$ let m = [|quux()|] join a in alpha on left().expr() equals right.expr() orderby goo, expr().expr() descending group bar().goo() by blah().zap() into g select y.blah(); } }"); } [Fact] public void InFrontOfJoinClause() { TestSpan( @"class C { void Goo() { var q = from x in blah() from y in zap() let m = quux() $$ join a in alpha on [|left().expr()|] equals right.expr() orderby goo, expr().expr() descending group bar().goo() by blah().zap() into g select y.blah(); } }"); } [Fact] public void InFrontOfOrderByClause() { TestSpan( @"class C { void Goo() { var q = from x in blah() from y in zap() let m = quux() join a in alpha on left().expr() equals right.expr() $$ orderby [|goo|], expr().expr() descending group bar().goo() by blah().zap() into g select y.blah(); } }"); } [Fact] public void InFrontOfGroupByClause() { TestSpan( @"class C { void Goo() { var q = from x in blah() from y in zap() let m = quux() join a in alpha on left().expr() equals right.expr() orderby goo, expr().expr() descending $$ group [|bar().goo()|] by blah().zap() into g select y.blah(); }"); } [Fact] public void InFrontOfSelectClause() { TestSpan( @"class C { void Goo() { var q = from x in blah() from y in zap() let m = quux() join a in alpha on left().expr() equals right.expr() orderby goo, expr().expr() descending group bar().goo() by blah().zap() into g $$ select [|y.blah()|]; }"); } [Fact] public void Select1() { TestSpan( @"class C { IEnumerable<int> Goo() => from x in new[] { 1 } select [|$$x|]; } "); } [Fact] public void Select_NoLambda1() { TestSpan( @"class C { IEnumerable<int> Goo() => [|from x in new[] { 1 } where x > 0 select $$x|]; } "); } [Fact] public void Select_NoLambda2() { TestSpan( @"class C { IEnumerable<int> Goo() => [|from x in new[] { 1 } select x into y orderby y select $$y|]; } "); } [Fact] public void GroupBy1() { TestSpan( @"class C { IEnumerable<int> Goo() => from x in new[] { 1 } group x by [|$$x|]; } "); } [Fact] public void GroupBy_NoLambda1() { TestSpan( @"class C { IEnumerable<int> Goo() => [|from x in new[] { 1 } group $$x by x|]; } "); } [Fact] public void GroupBy_NoLambda2() { TestSpan( @"class C { IEnumerable<int> Goo() => [|from x in new[] { 1 } group $$x by x + 1 into y group y by y.Key + 2|]; } "); } [Fact] public void GroupBy_NoLambda3() { TestSpan( @"class C { IEnumerable<int> Goo() => [|from x in new[] { 1 } group x by x + 1 into y group $$y by y.Key + 2|]; } "); } #endregion #region Field and Veriable Declarators [Fact] public void FieldDeclarator_WithoutInitializer_All() { VerifyAllSpansInDeclaration<VariableDeclaratorSyntax>( @"class C { int $$i, j; }"); } [Fact] public void FieldDeclarator_WithoutInitializer1() { TestMissing( @"class C { int $$i; }"); } [Fact] public void FieldDeclarator_WithoutInitializer2() { TestMissing( @"class C { pri$$vate int i; }"); } [Fact] public void FieldDeclarator_SingleVariable_Initializer_All1() { VerifyAllSpansInDeclaration<VariableDeclaratorSyntax>( @"class C { [Goo] private int $$i; }"); } [Fact] public void FieldDeclarator_SingleVariable_Initializer_All2() { VerifyAllSpansInDeclaration<VariableDeclaratorSyntax>( @"class C { [Goo] [|int $$i = 0;|] }"); } [Fact] public void FieldDeclarator_SingleVariable_Initializer_All3() { VerifyAllSpansInDeclaration<VariableDeclaratorSyntax>( @"class C { [Goo] [|private int $$i = 0;|] }"); } [Fact] public void FieldDeclarator_MultiVariable_Initializer_All1() { VerifyAllSpansInDeclaration<VariableDeclaratorSyntax>( @"class C { [Goo] [|private int $$i = 0|], j = 2; }"); } [Fact] public void FieldDeclarator_MultiVariable_Initializer_All2() { VerifyAllSpansInDeclaration<VariableDeclaratorSyntax>( @"class C { [Goo] [|int $$i = 0|], j = 2; }"); } [Fact] public void FieldDeclarator_MultiVariable_Initializer_All3() { VerifyAllSpansInDeclaration<VariableDeclaratorSyntax>( @"class C { [Goo] private int i = 0, [|$$j = 0|]; }"); } [Fact] public void FieldDeclarator_Initializer1() { TestSpan( @"class C { [|int $$i = 1;|] }"); } [Fact] public void FieldDeclarator_Initializer2() { TestSpan( @"class C { [|private int $$i = 1;|] }"); } [Fact] public void FieldDeclarator_Initializer3() { TestSpan( @"class C { [Goo] [|private int $$i = 0;|] }"); } [Fact] public void FieldDeclarator_Initializer4() { TestSpan( @"class C { [|pri$$vate int i = 1;|] }"); } [Fact] public void FieldDeclarator_Initializer5() { TestSpan( @"class C { $$ [|private int i = 3;|] }"); } [Fact] public void ConstVariableDeclarator0() => TestMissing("class C { void Goo() { const int a = $$1; } }"); [Fact] public void ConstVariableDeclarator1() => TestMissing("class C { void Goo() { const $$int a = 1; } }"); [Fact] public void ConstVariableDeclarator2() => TestMissing("class C { void Goo() { $$const int a = 1; } }"); [Fact] public void ConstFieldVariableDeclarator_All() { VerifyAllSpansInDeclaration<VariableDeclaratorSyntax>( @"class C { [Goo] private const int i = 0, j, $$k = 0; }"); } [Fact] public void ConstFieldVariableDeclarator0() => TestMissing("class C { const int a = $$1; }"); [Fact] public void ConstFieldVariableDeclarator1() => TestMissing("class C { const $$int a = 1; }"); [Fact] public void ConstFieldVariableDeclarator2() => TestMissing("class C { $$const int a = 1; }"); [Fact] [WorkItem(538777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538777")] public void VariableDeclarator0() => TestMissing("class C { void Goo() { int$$ } }"); [Fact] public void VariableDeclarator1() { TestMissing( @"class C { void Goo() { int $$i; } }"); } [Fact] public void VariableDeclarator2a() { TestSpan( @"class C { void Goo() { [|int $$i = 0;|] } }"); } [Fact] public void VariableDeclarator2b() { TestSpan( @"class C { void Goo() { $$ [|int i = 0;|] } }"); } [Fact] public void VariableDeclarator2c() { TestSpan( @"class C { void Goo() { [|$$int i = 0;|] } }"); } [Fact] public void VariableDeclarator3a() { TestSpan( @"class C { void Goo() { int i = 0, [|$$j = 3|]; } }"); } [Fact] public void VariableDeclarator3b() { TestSpan( @"class C { void Goo() { [|int i = 0|], $$j; } }"); } [Fact] public void VariableDeclarator3c() { TestSpan( @"class C { void Goo() { int $$i, [|j = 0|]; } }"); } [Fact] public void VariableDeclarator4() { TestSpan( @"class C { void Goo() { int i = 0, [|j = $$1|]; } }"); } [Fact] public void VariableDeclarator5() { TestSpan( @"class C { [|int $$i = 0;|] }"); } [Fact] public void VariableDeclarator6() { TestSpan( @"class C { [|int i = 0|], $$j; }"); } [Fact] public void VariableDeclarator7() { TestSpan( @"class C { private int i = 0, [|j = $$1|]; }"); } [Fact] public void VariableDeclarator8() { TestSpan( @"class C { [|priv$$ate int i = 0|], j = 1; }"); } [Fact] public void VariableDeclarator9() { TestSpan( @"class C { $$ [|private int i = 0|], j = 1; }"); } [Fact] public void VariableDeclarator10() => TestSpan("class C { void M() { [|int i = 0$$;|] } }"); [Fact] public void VariableDeclarator_Separators0() { TestSpan( @"class C { void Goo() { $$ [|int i = 0|], j = 1, k = 2; } }"); } [Fact] public void VariableDeclarator_Separators1() { TestSpan( @"class C { void Goo() { [|int i = 0|]$$, j = 1, k = 2; } }"); } [Fact] public void VariableDeclarator_Separators2() { TestSpan( @"class C { void Goo() { int i = 0, [|j = 1|]$$, k = 2; } }"); } [Fact] public void VariableDeclarator_Separators3() { TestSpan( @"class C { void Goo() { int i = 0, j = 1,$$ [|k = 2|]; } }"); } [Fact] public void VariableDeclarator_Separators4() { TestSpan( @"class C { void Goo() { int i = 0, j = 1, [|k = 2|]$$; } }"); } [Fact] public void VariableDeclarator_Separators5() { TestSpan( @"class C { void Goo() { [|int i = 0|], j = 1, k = 2;$$ } }"); } [Fact] public void VariableDeclarator_Separators6() { TestSpan( @"class C { void Goo() { int i = 1, j, $$k, [|l = 2|]; } }"); } [Fact] public void VariableDeclarator_Separators7() { TestSpan( @"class C { void Goo() { int i$$, j, k, [|l = 2|]; } }"); } [Fact] public void VariableDeclarator_Separators8() { TestSpan( @"class C { void Goo() { [|int i = 2|], j, k, l$$; } }"); } [Fact] public void VariableDeclarator_Separators9() { TestSpan( @"class C { void Goo() { int i, j, [|k = 1|], m, l = 2;$$ } }"); } [Fact] public void EventFieldDeclarator1() { TestSpan( @"class C { $$ [|public event EventHandler MyEvent = delegate { };|] }"); } [Fact] public void EventFieldDeclarator2() { TestSpan( @"class C { [|pub$$lic event EventHandler MyEvent = delegate { };|] }"); } [Fact] public void EventFieldDeclarator3() { TestSpan( @"class C { [|public ev$$ent EventHandler MyEvent = delegate { };|] }"); } [Fact] public void EventFieldDeclarator4() { TestSpan( @"class C { [|public event EventHan$$dler MyEvent = delegate { };|] }"); } [Fact] public void EventFieldDeclarator5() { TestSpan( @"class C { [|public event EventHandler MyE$$vent = delegate { };|] }"); } [Fact] public void EventFieldDeclarator6() { TestSpan( @"class C { [|public event EventHandler MyEvent $$= delegate { };|] }"); } [Fact] public void EventFieldDeclarator7() { TestSpan( @"class C { [|public event EventHandler MyEvent = del$$egate { };|] }"); } [Fact] public void EventFieldDeclarator8() { TestSpan( @"class C { public event EventHandler MyEvent = delegate [|{|] $$ }; }"); } #endregion [Fact] public void EventAccessorAdd() => TestSpan("class C { eve$$nt Action Goo { add [|{|] } remove { } } }"); [Fact] public void EventAccessorAdd2() => TestSpan("class C { event Action Goo { ad$$d [|{|] } remove { } } }"); [Fact] public void EventAccessorRemove() => TestSpan("class C { event Action Goo { add { } $$remove [|{|] } } }"); [Fact] public void ElseClauseWithBlock() { TestSpan( @"class C { void Goo() { if (bar) { } el$$se [|{|] } } }"); } [Fact] public void ElseClauseWithStatement() { TestSpan( @"class C { void Goo() { if (bar) { } el$$se [|Goo();|] } }"); } [Fact] public void ElseIf() { TestSpan( @"class C { void Goo() { if (bar) { } el$$se [|if (baz)|] Goo(); } }"); } [Fact] public void EmptyCatch() { TestSpan( @"class C { void Goo() { try { } [|cat$$ch|] { } } }"); } [Fact] public void CatchWithType() { TestSpan( @"class C { void Goo() { try { } [|cat$$ch(Exception)|] { } } }"); } [Fact] public void CatchWithTypeInType() { TestSpan( @"class C { void Goo() { try { } [|catch(Exce$$ption)|] { } } }"); } [Fact] public void CatchWithTypeAndNameInType() { TestSpan( @"class C { void Goo() { try { } [|catch(Exce$$ption e)|] { } } }"); } [Fact] public void CatchWithTypeAndNameInName() { TestSpan( @"class C { void Goo() { try { } [|catch(Exception $$e)|] { } } }"); } [Fact] public void Filter1() { TestSpan( @"class C { void Goo() { try { } $$catch(Exception e) [|when (e.Message != null)|] { } } }"); } [Fact] public void Filter3() { TestSpan( @"class C { void Goo() { try { } catch(Exception e)$$ [|when (e.Message != null)|] { } } }"); } [Fact] public void Filter4() { TestSpan( @"class C { void Goo() { try { } catch(Exception e) [|when$$ (e.Message != null)|] { } } }"); } [Fact] public void Filter5() { TestSpan( @"class C { void Goo() { try { } catch(Exception e) [|when (e.Message != null)|] $$ { } } }"); } [Fact] public void SimpleFinally() { TestSpan( @"class C { void Goo() { try { } final$$ly [|{|] } } }"); } [Fact] public void FinallyWithCatch() { TestSpan( @"class C { void Goo() { try { } catch { } final$$ly [|{|] } } }"); } [Fact] public void SwitchLabelWithBlock() { TestSpan( @"class C { void Goo() { switch (goo) { case $$1: [|{|] } } } }"); } [Fact] public void SwitchLabelWithStatement() { TestSpan( @"class C { void Goo() { switch (goo) { cas$$e 1: [|goo();|] } } }"); } [Fact] public void SwitchLabelWithStatement2() { TestSpan( @"class C { void Goo() { switch (goo) { cas$$e 1: [|goo();|] bar(); } } }"); } [Fact] public void SwitchLabelWithoutStatement() => TestSpan("class C { void M() { [|switch |]{ case 1$$: } } }"); [Fact] public void MultipleLabelsOnFirstLabel() { TestSpan( @"class C { void Goo() { switch (goo) { cas$$e 1: case 2: [|goo();|] case 3: default: bar(); } } }"); } [Fact] public void MultipleLabelsOnSecondLabel() { TestSpan( @"class C { void Goo() { switch (goo) { case 1: cas$$e 2: [|goo();|] case 3: default: bar(); } } }"); } [Fact] public void MultipleLabelsOnLabelWithDefault() { TestSpan( @"class C { void Goo() { switch (goo) { case 1: case 2: goo(); cas$$e 3: default: [|bar();|] } } }"); } [Fact] public void MultipleLabelsOnDefault() { TestSpan( @"class C { void Goo() { switch (goo) { case 1: case 2: goo(); case 3: default:$$ [|bar();|] } } }"); } [Fact] public void BlockBeforeStartToken() { TestSpan( @"class C { void Goo() [|$${|] } }"); } [Fact] public void BlockBeforeStartToken2() { TestSpan( @"class C { void Goo() $$ [|{|] } }"); } [Fact] public void BlockAfterStartToken() { TestSpan( @"class C { void Goo() [|{$$|] } }"); } [Fact] public void BlockAfterStartToken2() { TestSpan( @"class C { void Goo() [|{|] $$ } }"); } [Fact] public void BlockBeforeEndToken1() { TestSpan( @"class C { void Goo() { $$[|}|] }"); } [Fact] public void BlockBeforeEndToken2() { TestSpan( @"class C { void Goo() { $$ [|}|] }"); } [Fact] public void BlockAfterEndToken1() { TestSpan( @"class C { void Goo() { [|}|]$$ }"); } [Fact] public void BlockAfterEndToken2() { TestSpan( @"class C { void Goo() { [|}|] $$ }"); } [Fact] public void SingleDeclarationOnType() { TestMissing( @"class C { void Goo() { i$$nt i; } }"); } [Fact] public void MultipleDeclarationsOnType() { TestSpan( @"class C { void Goo() { [|i$$nt i = 0|], j = 1; } }"); } [Fact] public void Label() { TestSpan( @"class C { void Goo() { go$$o: [|bar();|] } }"); } [Fact] public void WhileInWhile() { TestSpan( @"class C { void Goo() { [|w$$hile (expr)|] { } } }"); } [Fact] public void WhileInExpr() { TestSpan( @"class C { void Goo() { [|while (ex$$pr)|] { } } }"); } [Fact] public void OnWhileBlock() { TestSpan( @"class C { void Goo() { while (expr) $$ [|{|] } } }"); } [Fact] public void OnDoKeyword() { TestSpan( @"class C { void Goo() { d$$o [|{|] } while(expr); } }"); } [Fact] public void OnDoBlock() { TestSpan( @"class C { void Goo() { do $$ [|{|] } while(expr); } }"); } [Fact] public void OnDoWhile() { TestSpan( @"class C { void Goo() { do { } [|wh$$ile(expr);|] } }"); } [Fact] public void OnDoWhile_MissingSemicolon() { TestSpan( @"class C { void Goo() { do { } [|wh$$ile(expr)|] } }"); } [Fact] public void OnDoExpression() { TestSpan( @"class C { void Goo() { do { } [|while(ex$$pr);|] } }"); } [Fact] public void OnForWithDeclaration1() { TestSpan( @"class C { void Goo() { f$$or ([|int i = 0|], j = 1; i < 10 && j < 10; i++, j++) { } } }"); } [Fact] public void OnForWithDeclaration2() { TestSpan( @"class C { void Goo() { f$$or ([|int i = 0|]; i < 10 && j < 10; i++, j++) { } } }"); } [Fact] public void OnForWithCondition() { TestSpan( @"class C { void Goo() { f$$or (; [|i < 10 && j < 10|]; i++, j++) { } } }"); } [Fact] public void OnForWithIncrementor1() { TestSpan( @"class C { void Goo() { f$$or (; ; [|i++|], j++) { } } }"); } [Fact] public void OnForWithIncrementor2() { TestSpan( @"class C { void Goo() { f$$or (; ; [|i++|]) { } } }"); } [Fact] public void OnEmptyFor() { TestSpan( @"class C { void Goo() { f$$or (; ; ) [|{|] } } }"); } [Fact] public void OnForEachKeyword1() { TestSpan( @"class C { void Goo() { $$ [|foreach|] (var v in expr().blah()) { } } }"); } [Fact] public void OnForEachKeyword2() { TestSpan( @"class C { void Goo() { [|fo$$reach|] (var v in expr().blah()) { } } }"); } [Fact] public void OnForEachKeyword3() { TestSpan( @"class C { void Goo() { [|foreach|] $$ (var v in expr().blah()) { } } }"); } [Fact] public void OnForEachKeyword4() { TestSpan( @"class C { void Goo() { [|foreach|] $$ (var v in expr().blah()) { } } }"); } [Fact] public void OnForEachKeyword5() { TestSpan( @"class C { void Goo() { [|foreach|] $$(var v in expr().blah()) { } } }"); } [Fact] public void OnForEachType1() { TestSpan( @"class C { void Goo() { foreach ( $$ [|var v|] in expr().blah()) { } } }"); } [Fact] public void OnForEachType2() { TestSpan( @"class C { void Goo() { foreach ([|v$$ar v|] in expr().blah()) { } } }"); } [Fact] public void OnForEachIdentifier() { TestSpan( @"class C { void Goo() { foreach ([|var v$$v|] in expr().blah()) { } } }"); } [Fact] public void OnForEachIn1() { TestSpan( @"class C { void Goo() { foreach (var v [|i$$n|] expr().blah()) { } } }"); } [Fact] public void OnForEachIn2() { TestSpan( @"class C { void Goo() { foreach (var v $$ [|in|] expr().blah()) { } } }"); } [Fact] public void OnForEachIn3() { TestSpan( @"class C { void Goo() { foreach (var v [|in|] $$ expr().blah()) { } } }"); } [Fact] public void OnForEachExpr1() { TestSpan( @"class C { void Goo() { foreach (var v in [|expr($$).blah()|]) { } } }"); } [Fact] public void OnForEachExpr2() { TestSpan( @"class C { void Goo() { foreach (var v in [|expr().blah()|] $$ ) { } } }"); } [Fact] public void OnForEachExpr3() { TestSpan( @"class C { void Goo() { foreach (var v in $$ [|expr().blah()|] ) { } } }"); } [Fact] public void OnForEachStatement() { TestSpan( @"class C { void Goo() { [|foreach|](var v in expr().blah()) $$ { } } }"); } [Fact] public void OnForEachBlock1() { TestSpan( @"class C { void Goo() { foreach (var v in expr().blah()) $$ [|{|] } } }"); } [Fact] public void OnForEachDeconstructionKeyword1() { TestSpan( @"class C { void Goo() { $$ [|foreach|] (var (x, y) in expr().blah()) { } } }"); } [Fact] public void OnForEachDeconstructionKeyword2() { TestSpan( @"class C { void Goo() { [|fo$$reach|] (var (x, y) in expr().blah()) { } } }"); } [Fact] public void OnForEachDeconstructionKeyword3() { TestSpan( @"class C { void Goo() { [|foreach|] $$ (var (x, y) in expr().blah()) { } } }"); } [Fact] public void OnForEachDeconstructionKeyword4() { TestSpan( @"class C { void Goo() { [|foreach|] $$ (var (x, y) in expr().blah()) { } } }"); } [Fact] public void OnForEachDeconstructionKeyword5() { TestSpan( @"class C { void Goo() { [|foreach|] $$(var (x, y) in expr().blah()) { } } }"); } [Fact] public void OnForEachDeconstructionType1() { TestSpan( @"class C { void Goo() { foreach ( $$ [|var (x, y)|] in expr().blah()) { } } }"); } [Fact] public void OnForEachDeconstructionType2() { TestSpan( @"class C { void Goo() { foreach ([|v$$ar (x, y)|] in expr().blah()) { } } }"); } [Fact] public void OnForEachDeconstructionIdentifier() { TestSpan( @"class C { void Goo() { foreach ([|var (v$$v, y)|] in expr().blah()) { } } }"); } [Fact] public void OnForEachDeconstructionIn1() { TestSpan( @"class C { void Goo() { foreach (var (x, y) [|i$$n|] expr().blah()) { } } }"); } [Fact] public void OnForEachDeconstructionIn2() { TestSpan( @"class C { void Goo() { foreach (var (x, y) $$ [|in|] expr().blah()) { } } }"); } [Fact] public void OnForEachDeconstructionIn3() { TestSpan( @"class C { void Goo() { foreach (var (x, y) [|in|] $$ expr().blah()) { } } }"); } [Fact] public void OnForEachDeconstructionExpr1() { TestSpan( @"class C { void Goo() { foreach (var (x, y) in [|expr($$).blah()|]) { } } }"); } [Fact] public void OnForEachDeconstructionExpr2() { TestSpan( @"class C { void Goo() { foreach (var (x, y) in [|expr().blah()|] $$ ) { } } }"); } [Fact] public void OnForEachDeconstructionExpr3() { TestSpan( @"class C { void Goo() { foreach (var (x, y) in $$ [|expr().blah()|] ) { } } }"); } [Fact] public void OnForEachDeconstructionStatement() { TestSpan( @"class C { void Goo() { [|foreach|](var (x, y) in expr().blah()) $$ { } } }"); } [Fact] public void OnForEachDeconstructionBlock1() { TestSpan( @"class C { void Goo() { foreach (var (x, y) in expr().blah()) $$ [|{|] } } }"); } [Fact] public void OnUsingWithDecl1() { TestSpan( @"class C { void Goo() { us$$ing ([|var v = goo()|]) { } } }"); } [Fact] public void OnUsingWithDecl2() { TestSpan( @"class C { void Goo() { us$$ing ([|var v = goo()|], x = bar()) { } } }"); } [Fact] public void OnUsingWithDeclType() { TestSpan( @"class C { void Goo() { using ([|v$$ar v = goo()|]) { } } }"); } [Fact] public void OnUsingWithDeclIdentifier1() { TestSpan( @"class C { void Goo() { using ([|var v$$v = goo()|]) { } } }"); } [Fact] public void OnUsingWithDeclIdentifier2() { TestSpan( @"class C { void Goo() { using ([|var vv = goo()|]) $$ { } } }"); } [Fact] public void OnUsingWithDeclIdentifier3() { TestSpan( @"class C { void Goo() { $$ using ([|var vv = goo()|]) { } } }"); } [Fact] public void OnUsingWithDeclExpression() { TestSpan( @"class C { void Goo() { using ([|var vv = go$$o()|]) { } } }"); } [Fact] public void OnUsingWithExpression1() { TestSpan( @"class C { void Goo() { [|usi$$ng (goo().bar())|] { } } }"); } [Fact] public void OnUsingWithExpression2() { TestSpan( @"class C { void Goo() { [|using (goo$$().bar())|] { } } }"); } [Fact] public void OnFixed1() { TestSpan( @"class C { void Goo() { fi$$xed ([|int* i = &j|]) { } } }"); } [Fact] public void OnFixed2() { TestSpan( @"class C { void Goo() { fi$$xed ([|int* i = &j|], k = &m) { } } }"); } [Fact] public void OnFixed3() { TestSpan( @"class C { void Goo() { fixed ([|i$$nt* i = &j|]) { } } }"); } [Fact] public void OnFixed4() { TestSpan( @"class C { void Goo() { fixed ([|int* $$i = &j|]) { } } }"); } [Fact] public void OnFixed5() { TestSpan( @"class C { void Goo() { fixed ([|int* i $$= &j|]) { } } }"); } [Fact] public void OnFixed6() { TestSpan( @"class C { void Goo() { fixed ([|int* i = &$$j|]) { } } }"); } [Fact] public void OnChecked1() { TestSpan( @"class C { void Goo() { che$$cked [|{|] } } }"); } [Fact] public void OnUnchecked1() { TestSpan( @"class C { void Goo() { unche$$cked [|{|] } } }"); } [Fact] public void OnUnsafe1() { TestSpan( @"class C { void Goo() { uns$$afe [|{|] } } }"); } [Fact] public void OnLock1() { TestSpan( @"class C { void Goo() { [|lo$$ck (expr)|] { } } }"); } [Fact] public void OnLock2() { TestSpan( @"class C { void Goo() { [|lock (ex$$pr)|] { } } }"); } [Fact] public void OnIf1() { TestSpan( @"class C { void Goo() { [|i$$f (goo().bar())|] { } } }"); } [Fact] public void OnIf2() { TestSpan( @"class C { void Goo() { [|if (go$$o().bar())|] { } } }"); } [Fact] public void OnIfBlock() { TestSpan( @"class C { void Goo() { if (goo().bar()) $$ [|{|] } } }"); } [Fact] public void OnSwitch1() { TestSpan( @"class C { void Goo() { [|swi$$tch (expr)|] { default: goo(); } } }"); } [Fact] public void OnSwitch2() { TestSpan( @"class C { void Goo() { [|switch (ex$$pr)|] { default: goo(); } } }"); } [Fact] public void OnSwitch3() { TestSpan( @"class C { void Goo() { [|switch (expr)|] $$ { default: goo(); } } }"); } [Fact] public void OnSwitch4() { TestSpan( @"class C { void Goo() { [|switch (expr)|] { default: goo(); $$ } } }"); } [Fact] public void OnTry1() { TestSpan( @"class C { void Goo() { t$$ry [|{|] } finally { } } }"); } [Fact] public void OnTry2() { TestSpan( @"class C { void Goo() { try $$ [|{|] } finally { } } }"); } [Fact] public void OnGotoStatement1() { TestSpan( @"class C { void Goo() { [|g$$oto goo;|] } }"); } [Fact] public void OnGotoStatement2() { TestSpan( @"class C { void Goo() { [|goto go$$o;|] } }"); } [Fact] public void OnGotoCaseStatement1() { TestSpan( @"class C { void Goo() { switch (expr) { case 1: [|go$$to case 2;|] } } }"); } [Fact] public void OnGotoCaseStatement2() { TestSpan( @"class C { void Goo() { switch (expr) { case 1: [|goto ca$$se 2;|] } } }"); } [Fact] public void OnGotoCaseStatement3() { TestSpan( @"class C { void Goo() { switch (expr) { case 1: [|goto case $$2;|] } } }"); } [Fact] public void OnGotoDefault1() { TestSpan( @"class C { void Goo() { switch (expr) { case 1: [|go$$to default;|] } } }"); } [Fact] public void OnGotoDefault2() { TestSpan( @"class C { void Goo() { switch (expr) { case 1: [|goto defau$$lt;|] } } }"); } [Fact] public void OnBreak1() { TestSpan( @"class C { void Goo() { while (true) { [|bre$$ak;|] } } }"); } [Fact] public void OnContinue1() { TestSpan( @"class C { void Goo() { while (true) { [|cont$$inue;|] } } }"); } [Fact] public void OnReturn1() { TestSpan( @"class C { void Goo() { [|retu$$rn;|] } }"); } [Fact] public void OnReturn2() { TestSpan( @"class C { void Goo() { [|retu$$rn expr();|] } }"); } [Fact] public void OnReturn3() { TestSpan( @"class C { void Goo() { [|return expr$$().bar();|] } }"); } [Fact] public void OnYieldReturn1() { TestSpan( @"class C { void Goo() { [|yi$$eld return goo().bar();|] } }"); } [Fact] public void OnYieldReturn2() { TestSpan( @"class C { void Goo() { [|yield re$$turn goo().bar();|] } }"); } [Fact] public void OnYieldReturn3() { TestSpan( @"class C { void Goo() { [|yield return goo()$$.bar();|] } }"); } [Fact] public void OnYieldBreak1() { TestSpan( @"class C { void Goo() { [|yi$$eld break;|] } }"); } [Fact] public void OnYieldBreak2() { TestSpan( @"class C { void Goo() { [|yield brea$$k;|] } }"); } [Fact] public void OnThrow1() { TestSpan( @"class C { void Goo() { [|th$$row;|] } }"); } [Fact] public void OnThrow2() { TestSpan( @"class C { void Goo() { [|thr$$ow new Goo();|] } }"); } [Fact] public void OnThrow3() { TestSpan( @"class C { void Goo() { [|throw ne$$w Goo();|] } }"); } [Fact] public void OnThrow4() { TestSpan( @"class C { void Goo() { [|throw new Go$$o();|] } }"); } [Fact] public void OnExpressionStatement1() { TestSpan( @"class C { void Goo() { [|goo().$$bar();|] } }"); } [Fact] public void OnEmptyStatement1() { TestSpan( @"class C { void Goo() { [|$$;|] } }"); } [Fact] public void OnEmptyStatement2() { TestSpan( @"class C { void Goo() { while (true) { $$ [|;|] } } }"); } [Fact] public void OnPropertyAccessor1() { TestSpan( @"class C { int Goo { g$$et [|{|] } } }"); } [Fact] public void OnPropertyAccessor2() { TestSpan( @"class C { int Goo { [|g$$et;|] } }"); } [Fact] public void OnPropertyAccessor3() { TestSpan( @"class C { int Goo { get { } s$$et [|{|] } } }"); } [Fact] public void OnPropertyAccessor4() { TestSpan( @"class C { int Goo { [|s$$et;|] } }"); } [Fact] [WorkItem(48504, "https://github.com/dotnet/roslyn/issues/48504")] public void OnPropertyAccessor5() { TestSpan( @"class C { int Goo { [|in$$it;|] } }"); } [Fact] public void OnProperty1() { TestSpan( @"class C { int G$$oo { get [|{|] } set { } } }"); } [Fact] public void OnProperty2() { TestSpan( @"class C { int G$$oo { [|get;|] set {} } }"); } [WorkItem(932711, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/932711")] [Fact] public void OnPropertyWithInitializer() { TestSpan( @"class C { public int Id { get; set; } = [|int.Pa$$rse(""42"")|]; }"); TestSpan( @"class C { public int$$ Id { [|get;|] set; } = int.Parse(""42""); }"); TestSpan( @"class C { public int Id { get; [|set;|] $$} = int.Parse(""42""); }"); TestSpan( @"class C { public int Id { get; [|set;|] }$$ = int.Parse(""42""); }"); TestSpan( @"class C { public int Id { get; set; } =$$ [|int.Parse(""42"")|]; }"); } [Fact] public void OnPropertyExpressionBody1() { TestSpan( @"class C { public int Id => [|12$$3|]; }"); } [Fact] public void OnPropertyExpressionBody2() { TestSpan( @"class C { public int Id $$=> [|123|]; }"); } [Fact] public void OnPropertyExpressionBody3() { TestSpan( @"class C { $$public int Id => [|123|]; }"); } [Fact] public void OnPropertyExpressionBody4() { TestSpan( @"class C { public int Id => [|123|]; $$ }"); } [Fact] public void OnIndexerExpressionBody1() { TestSpan( @"class C { public int this[int a] => [|12$$3|]; }"); } [Fact] public void OnIndexer1() { TestSpan( @"class C { int this[int$$ a] { get [|{|] } set { } } }"); } [Fact] public void OnIndexer2() { TestSpan( @"class C { int this[int$$ a] { [|get;|] set { } } }"); } [Fact] public void OnIndexerExpressionBody2() { TestSpan( @"class C { public int this[int a] $$=> [|123|]; }"); } [Fact] public void OnIndexerExpressionBody3() { TestSpan( @"class C { $$public int this[int a] => [|123|]; }"); } [Fact] public void OnIndexerExpressionBody4() { TestSpan( @"class C { public int this[int a] => [|123|]; $$ }"); } [Fact] public void OnIndexerExpressionBody5() { TestSpan( @"class C { public int this[int $$a] => [|123|]; }"); } [Fact] public void OnMethod1() { TestSpan( @"class C { v$$oid Goo() [|{|] } }"); } [Fact] public void OnMethod2() { TestSpan( @"class C { void G$$oo() [|{|] } }"); } [Fact] public void OnMethod3() { TestSpan( @"class C { void Goo(in$$t i) [|{|] } }"); } [Fact] public void OnMethod4() { TestSpan( @"class C { void Goo(int $$i) [|{|] } }"); } [Fact] public void OnMethod5() { TestSpan( @"class C { void Goo(int i = g$$oo) [|{|] } }"); } [Fact] public void OnMethodWithExpressionBody1() { TestSpan( @"class C { v$$oid Goo() => [|123|]; }"); } [Fact] public void OnMethodWithExpressionBody2() { TestSpan( @"class C { void Goo() =>$$ [|123|]; }"); } [Fact] public void OnMethodWithExpressionBody3() { TestSpan( @"class C { void Goo() => [|123|]; $$ }"); } [Fact] public void OnMethodWithExpressionBody4() { TestSpan( @"class C { void Goo() => [|12$$3|]; }"); } [Fact] public void MissingOnMethod() { TestMissing( @"class C { void Goo($$); }"); } #region Constructors [Fact] public void InstanceConstructor_NoInitializer_BlockBody_All() { VerifyAllSpansInDeclaration<ConstructorDeclarationSyntax>( @"class C { [Attribute1, Attribute2][Attribute3][|$$public C()|] [|{|] [|}|] }"); } [Fact] public void InstanceConstructor_NoInitializer_BlockBody() { // a sequence point for base constructor call TestSpan( @"class C { [|pub$$lic C()|] { } }"); } [Fact] public void InstanceConstructor_NoInitializer_ExpressionBody_All() { VerifyAllSpansInDeclaration<ConstructorDeclarationSyntax>( @"class C { [Attribute1, Attribute2][Attribute3][|$$public C()|] => [|x = 1|]; }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void InstanceConstructor_NoInitializer_ExpressionBody1() { // a sequence point for base constructor call TestSpan( @"class C { [|pub$$lic C()|] => F(); }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void InstanceConstructor_NoInitializer_ExpressionBody2() { // a sequence point for base constructor call TestSpan( @"class C { [|public C()|] $$=> x = 1); }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void InstanceConstructor_NoInitializer_ExpressionBody3() { // a sequence point for base constructor call TestSpan( @"class C { public C() =$$> [|x = 1|]; }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void InstanceConstructor_NoInitializer_ExpressionBody4() { // a sequence point for base constructor call TestSpan( @"class C { public C() => [|$$x = 1|]; }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void InstanceConstructor_NoInitializer_ExpressionBody5() { TestSpan( @"class C { public C() => [|x =$$ 1|]; }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void InstanceConstructor_NoInitializer_ExpressionBody6() { TestSpan( @"class C { public C() => [|x = 1|]$$; }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void InstanceConstructor_NoInitializer_ExpressionBody7() { TestSpan( @"class C { public C() => [|x = 1|];$$ }"); } [Fact] public void InstanceConstructor_NoInitializer_Attributes() { TestSpan( @"class C { [Attribute1,$$ Attribute2] [Attribute3] [|public C()|] { } }"); } [Fact] public void InstanceConstructor_BaseInitializer_BlockBody_All() { VerifyAllSpansInDeclaration<ConstructorDeclarationSyntax>( @"class C { [Attribute1, Attribute2][Attribute3]$$public C() : [|base(42)|] [|{|][|}|] }"); } [Fact] public void InstanceConstructor_BaseInitializer_BlockBody() { // a sequence point for base constructor call TestSpan( @"class C { pub$$lic C() : [|base(42)|] { } }"); } [Fact] public void InstanceConstructor_BaseInitializer_ExpressionBody_All() { VerifyAllSpansInDeclaration<ConstructorDeclarationSyntax>( @"class C { [Attribute1, Attribute2][Attribute3]$$public C() : [|base(42)|] => [|x = 1|]; }"); } [Fact] public void InstanceConstructor_BaseInitializer_ExpressionBody1() { // a sequence point for base constructor call TestSpan( @"class C { pub$$lic C() : [|base(42)|] => F(); }"); } [Fact] public void InstanceConstructor_BaseInitializer_ExpressionBody2() { // a sequence point for base constructor call TestSpan( @"class C { public C() : [|base(42)|] $$=> F(); }"); } [Fact] public void InstanceConstructor_BaseInitializer_ExpressionBody3() { // a sequence point for base constructor call TestSpan( @"class C { public C() : base(42) =$$> [|F()|]; }"); } [Fact] public void InstanceConstructor_BaseInitializer_ExpressionBody4() { // a sequence point for base constructor call TestSpan( @"class C { public C() : base(42) => [|$$F()|]; }"); } [Fact] public void InstanceConstructor_ThisInitializer() { // a sequence point for this constructor call TestSpan( @"class C { pub$$lic C() : [|this(42)|] { } }"); } [Fact] public void StaticConstructor_BlockBody_All() { VerifyAllSpansInDeclaration<ConstructorDeclarationSyntax>( @"class C { [Attribute1, Attribute2][Attribute3]$$static public C() [|{|] [|}|] }"); } [Fact] public void StaticConstructor_BlockBody() { TestSpan( @"class C { $$static C() [|{|] } }"); } [Fact] public void StaticConstructor_ExpressionBody_All() { VerifyAllSpansInDeclaration<ConstructorDeclarationSyntax>( @"class C { [Attribute1, Attribute2][Attribute3]$$static public C() => [|x = 1|]; }"); } [Fact] public void StaticConstructor_ExpressionBody() { TestSpan( @"class C { static C() => [|$$F()|]; }"); } [Fact] public void InstanceConstructorInitializer() { // a sequence point for this constructor call TestSpan( @"class Derived : Base { public Derived() : [|this($$42)|] { } }"); } [WorkItem(543968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543968")] [Fact] public void ConstructorInitializer() { // a sequence point for base constructor call TestSpan( @"class Derived : Base { public Derived() : [|base($$42)|] { } } "); } [Fact] public void OnStaticConstructor() { TestSpan( @"class C { st$$atic C() [|{|] } }"); } #endregion [Fact] public void OnDestructor() { TestSpan( @"class C { ~C$$() [|{|] } }"); } [Fact] public void OnOperator() { TestSpan( @"class C { public static int op$$erator+(C c1, C c2) [|{|] } }"); } [Fact] public void OnOperatorWithExpressionBody1() { TestSpan( @"class C { public static int op$$erator+(C c1, C c2) => [|c1|]; }"); } [Fact] public void OnOperatorWithExpressionBody2() { TestSpan( @"class C { public static int operator+(C c1, C c2) =>$$ [|c1|]; }"); } [Fact] public void OnOperatorWithExpressionBody3() { TestSpan( @"class C { public static int operator+(C c1, C c2) => [|c1|]; $$ }"); } [Fact] public void OnOperatorWithExpressionBody4() { TestSpan( @"class C { public static int operator+(C c1, C c2) => [|c$$1|]; }"); } [Fact] public void OnConversionOperator() { TestSpan( @"class C { public static op$$erator DateTime(C c1) [|{|] } }"); } [Fact] public void OnConversionOperatorWithExpressionBody1() { TestSpan( @"class C { public static op$$erator DateTime(C c1) => [|DataTime.Now|]; }"); } [Fact] public void OnConversionOperatorWithExpressionBody2() { TestSpan( @"class C { public static operator DateTime(C c1) =>$$ [|DataTime.Now|]; }"); } [Fact] public void OnConversionOperatorWithExpressionBody3() { TestSpan( @"class C { public static operator DateTime(C c1) => [|DataTime.Now|];$$ }"); } [Fact] public void OnConversionOperatorWithExpressionBody4() { TestSpan( @"class C { public static operator DateTime(C c1) => [|DataTime$$.Now|]; }"); } [WorkItem(3557, "DevDiv_Projects/Roslyn")] [Fact] public void InFrontOfAttribute() { TestSpan( @"class C { $$ [method: Obsolete] void Goo() [|{|] } }"); } [WorkItem(538058, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538058")] [Fact] public void InInactivePPRegion() { TestLine( @" #if blahblah $$gooby #endif"); } [WorkItem(538777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538777")] [Fact] public void WithIncompleteDeclaration() { TestMissing( @" clas C { void Goo() { $$ int } }"); } [WorkItem(937290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/937290")] [Fact] public void OnGetter() { TestSpan( @"class C { public int $$Id { [|get;|] set; } }"); TestSpan( @"class C { public int Id { [|g$$et;|] set; } }"); TestSpan( @"class C { public int Id { g$$et [|{|] return 42; } set {} } }"); TestSpan( @"class C { public int$$ Id { get [|{|] return 42; } set {} } }"); } [WorkItem(937290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/937290")] [Fact] public void OnSetter() { TestSpan( @"class C { public int Id { get; [|se$$t;|] } }"); TestSpan( @"class C { public int Id { get; [|set;|] $$ } }"); TestSpan( @"class C { public int $$Id { [|set;|] get; } }"); TestSpan( @"class C { public int Id { get { return 42; } s$$et [|{|] } } }"); TestSpan( @"class C { public int Id { get { return 42; } set { [|}|] $$} }"); } [Fact] public void WhenClause_1() { TestSpan( @"class C { string s; bool b; void Goo() { switch (s) { $$ case string s [|when b|]: break; } } }"); } [Fact] public void WhenClause_2() { TestSpan( @"class C { string s; bool b; void Goo() { switch (s) { case string s [|whe$$n b|]: break; } } }"); } [Fact] public void WhenClause_3() { TestSpan( @"class C { string s; bool b; void Goo() { switch (s) { case string s [|when b|]:$$ break; } } }"); } [Fact] public void PatternSwitchCase_1() { TestSpan( @"class C { string s; bool b; void Goo() { switch (s) { $$ case string s: default: [|break;|] } } }"); } [Fact] public void PatternSwitchCase_2() { TestSpan( @"class C { string s; bool b; void Goo() { switch (s) { $$case string s: default: [|break;|] } } }"); } [Fact] public void PatternSwitchCase_3() { TestSpan( @"class C { string s; bool b; void Goo() { switch (s) { case string s:$$ default: [|break;|] } } }"); } [Fact] public void DeconstructionDeclarationStatement_1() { TestSpan( @"class C { void Goo() { $$ [|var (x, y) = (1, 2);|] } }"); } [Fact] public void DeconstructionDeclarationStatement_2() { TestSpan( @"class C { void Goo() { [|var (x, y) = $$(1, 2);|] } }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void OnAccessorExpressionBody1() { TestSpan( @"class C { public int Id { get => [|12$$3|]; } }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void OnAccessorExpressionBody2() { TestSpan( @"class C { public int Id { get $$=> [|123|]; } }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void OnAccessorExpressionBody3() { TestSpan( @"class C { $$public int Id { get => [|123|]; } }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void OnAccessorExpressionBody4() { TestSpan( @"class C { public int Id { get => [|123|]; $$ } }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void OnAccessorExpressionBody5() { TestSpan( @"class C { $$ public event Action Goo { add => [|123|]; remove => 456; } }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void OnAccessorExpressionBody6() { TestSpan( @"class C { public event Action Goo { add => [|123|];$$ remove => 456; } }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void OnAccessorExpressionBody7() { TestSpan( @"class C { public event Action Goo { add => 123; $$remove => [|456|]; } }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void OnAccessorExpressionBody8() { TestSpan( @"class C { public event Action Goo { add => 123; remove => [|456|]; }$$ }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void OnDtorExpressionBody1() { TestSpan( @"class C { $$ public ~C() => [|x = 1|]; }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void OnDtorExpressionBody2() { TestSpan( @"class C { public ~C() => $$[|x = 1|]; }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void OnDtorExpressionBody3() { TestSpan( @"class C { public ~C() => [|x =$$ 1|]; }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void OnDtorExpressionBody4() { TestSpan( @"class C { public ~C() => [|x = 1|]$$; }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void OnDtorExpressionBody5() { TestSpan( @"class C { public ~C() => [|x = 1|];$$ }"); } [Fact, WorkItem(14437, "https://github.com/dotnet/roslyn/issues/14437")] public void OnLocalFunctionDecl_1() { TestSpan( @"class C { static void M() { $$ int Local(object[] a) [|{|] return a.Length; } } }"); } [Fact, WorkItem(14437, "https://github.com/dotnet/roslyn/issues/14437")] public void OnLocalFunctionDecl_2() { TestSpan( @"class C { static void M() { int Local(object[] a)$$ [|{|] return a.Length; } } }"); } [Fact, WorkItem(14437, "https://github.com/dotnet/roslyn/issues/14437")] public void OnLocalFunctionDecl_3() { TestSpan( @"class C { static void M() { int Local(object[] a) $$ [|{|] return a.Length; } } }"); } [Fact, WorkItem(14437, "https://github.com/dotnet/roslyn/issues/14437")] public void OnLocalFunctionDecl_4() { TestSpan( @"class C { static void M() { $$ int Local(object[] a) => [|a.Length|]; } }"); } [Fact, WorkItem(14437, "https://github.com/dotnet/roslyn/issues/14437")] public void OnLocalFunctionDecl_5() { TestSpan( @"class C { static void M() { int Local(object$$[] a) => [|a.Length|]; } }"); } [Fact, WorkItem(14437, "https://github.com/dotnet/roslyn/issues/14437")] public void OnLocalFunctionDecl_6() { TestSpan( @"class C { static void M() { int Local(object[] a) => [|a.Length|];$$ } }"); } [Fact, WorkItem(98990, "https://developercommunity.visualstudio.com/content/problem/98990/cant-set-breakpoint.html")] public void IncompleteExpressionStatement() { TestSpan( @"class C { void Goo() { [|$$aaa|] } }"); } #region Top Level Statements [Fact] public void TopLevelStatements() { VerifyAllSpansInDeclaration<CompilationUnitSyntax>(@" $$[|int d = 5;|] [|int a = 1|], [|b = 2|], [|c = 3|]; for ([|int i = 0|], [|j = 1|], [|k = 2|]; [|i < 10|]; [|i++|], [|j++|], [|k--|]) [|while (b > 0)|] [|{|] [|if (c < b)|] try [|{|] [|System.Console.WriteLine(a);|] [|}|] [|catch (Exception e)|] [|{|] [|System.Console.WriteLine(e);|] [|}|] finally [|{|] [|}|] else [|if (b < 10)|] [|System.Console.WriteLine(b);|] else [|System.Console.WriteLine(c);|] [|}|] "); } #endregion } }
// Licensed to the .NET Foundation under one or more 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 System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.EditAndContinue; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.Debugging { [Trait(Traits.Feature, Traits.Features.DebuggingBreakpoints)] public class BreakpointSpansTests { #region Helpers private static void TestSpan(string markup, ParseOptions options = null) => Test(markup, isMissing: false, isLine: false, options: options); private static void TestMissing(string markup) => Test(markup, isMissing: true, isLine: false); private static void TestLine(string markup) => Test(markup, isMissing: false, isLine: true); private static void Test(string markup, bool isMissing, bool isLine, ParseOptions options = null) { MarkupTestFile.GetPositionAndSpan( markup, out var source, out var position, out TextSpan? expectedSpan); var tree = SyntaxFactory.ParseSyntaxTree(source, options); var hasBreakpoint = BreakpointSpans.TryGetBreakpointSpan( tree, position.Value, CancellationToken.None, out var breakpointSpan); if (isLine) { Assert.True(hasBreakpoint); Assert.True(breakpointSpan.Length == 0); } else if (isMissing) { Assert.False(hasBreakpoint); } else { Assert.True(hasBreakpoint); Assert.Equal(expectedSpan.Value, breakpointSpan); } } /// <summary> /// Verifies all breakpoint spans of the declaration node marked by $$ in <paramref name="markup"/> /// and it's breakpoint span envelope (span that contains all breakpoint span of the declaration). /// /// Only test declarations that have a single possible body (e.g. <see cref="VariableDeclaratorSyntax"/>, /// not <see cref="FieldDeclarationSyntax"/> or <see cref="VariableDeclarationSyntax"/>). /// </summary> private static void VerifyAllSpansInDeclaration<TDeclaration>(string markup) where TDeclaration : SyntaxNode { MarkupTestFile.GetPositionAndSpans(markup, out var source, out var position, out ImmutableArray<TextSpan> expectedSpans); var tree = SyntaxFactory.ParseSyntaxTree(source); var root = tree.GetRoot(); var declarationNode = root.FindToken(position).Parent.FirstAncestorOrSelf<TDeclaration>(); var actualSpans = GetBreakpointSequence(declarationNode, position).ToArray(); AssertEx.Equal(expectedSpans, actualSpans, itemSeparator: "\r\n", itemInspector: span => "[|" + source.Substring(span.Start, span.Length) + "|]"); var expectedEnvelope = expectedSpans.IsEmpty ? default : TextSpan.FromBounds(expectedSpans[0].Start, expectedSpans[^1].End); Assert.NotNull(declarationNode); var actualEnvelope = BreakpointSpans.GetEnvelope(declarationNode); Assert.Equal(expectedEnvelope, actualEnvelope); } public static IEnumerable<TextSpan> GetBreakpointSequence(SyntaxNode root, int position) { TextSpan lastSpan = default; var endPosition = root.Span.End; for (var p = position; p < endPosition; p++) { if (BreakpointSpans.TryGetClosestBreakpointSpan(root, p, out var span) && span.Start > lastSpan.Start) { lastSpan = span; yield return span; } } } #endregion [Fact] public void GetBreakpointSequence1() { VerifyAllSpansInDeclaration<MethodDeclarationSyntax>(@" class C { $$void Goo() [|{|] [|int d = 5;|] [|int a = 1|], [|b = 2|], [|c = 3|]; for ([|int i = 0|], [|j = 1|], [|k = 2|]; [|i < 10|]; [|i++|], [|j++|], [|k--|]) [|while (b > 0)|] [|{|] [|if (c < b)|] try [|{|] [|System.Console.WriteLine(a);|] [|}|] [|catch (Exception e)|] [|{|] [|System.Console.WriteLine(e);|] [|}|] finally [|{|] [|}|] else [|if (b < 10)|] [|System.Console.WriteLine(b);|] else [|System.Console.WriteLine(c);|] [|}|] [|}|] }"); } [Fact] public void GetBreakpointSequence2() { VerifyAllSpansInDeclaration<MethodDeclarationSyntax>(@" class C { $$void Goo() [|{|] do [|{|] label: [|i++;|] [|var l = new List<int>() { F(), F(), };|] [|break;|] [|continue;|] [|}|] [|while (a);|] [|goto label;|] [|}|] }"); } [Fact] public void GetBreakpointSequence3() { VerifyAllSpansInDeclaration<MethodDeclarationSyntax>(@" class C { $$int Goo() [|{|] [|switch(a)|] { case 1: case 2: [|break;|] case 3: [|goto case 4;|] case 4: [|throw new Exception();|] [|goto default;|] default: [|return 1;|] } [|return 2;|] [|}|] }"); } [Fact] public void GetBreakpointSequence4() { VerifyAllSpansInDeclaration<MethodDeclarationSyntax>(@" class C { $$IEnumerable<int> Goo() [|{|] [|yield return 1;|] [|foreach|] ([|var f|] [|in|] [|Goo()|]) [|{|] [|using (z)|] using ([|var q = null|]) using ([|var u = null|], [|v = null|]) [|{|] [|while (a)|] [|yield return 2;|] [|}|] [|}|] fixed([|int* a = new int[1]|], [|b = new int[1]|], [|c = new int[1]|]) [|{|][|}|] [|yield break;|] [|}|] }"); } [Fact] public void GetBreakpointSequence5() { VerifyAllSpansInDeclaration<MethodDeclarationSyntax>(@" class C { $$IEnumerable<int> Goo() [|{|][|while(t)|][|{|][|}|][|}|] }"); } [Fact] public void GetBreakpointSequence6() { VerifyAllSpansInDeclaration<MethodDeclarationSyntax>(@" class C { $$IEnumerable<int> Goo() [|{|] checked [|{|] const int a = 1; const int b = 2; unchecked [|{|] unsafe [|{|] [|lock(l)|] [|{|] [|;|] [|}|] [|}|] [|}|] [|}|] [|}|] }"); } #region Switch Expression [Fact] public void SwitchExpression_All() { VerifyAllSpansInDeclaration<MethodDeclarationSyntax>(@" class C { $$IEnumerable<int> Goo() [|{|] [|_ = M2( c switch { (1) _ [|when f|] => [|M(0)|], (3) _ [|when f|] => [|M(1)|], (1, 2) _ [|when f|] => [|M(0)|], (3, 4) _ [|when f|] => [|M(2)|], _ => [|M(4)|], }, M(5));|] [|}|] }"); } [Fact] public void SwitchExpression01() { TestSpan( @"class C { void Goo() { $$ [|_ = e switch { 1 when f => 2, 3 when g => 4, _ => 5, };|] } }"); } [Fact] public void SwitchExpression02() { TestSpan( @"class C { void Goo() { [|_ = e switch $${ 1 when f => 2, 3 when g => 4, _ => 5, };|] } }"); } [Fact] public void SwitchExpression03() { TestSpan( @"class C { void Goo() { _ = e switch {$$ 1 [|when f|] => 2, 3 when g => 4, _ => 5, }; } }"); } [Fact] public void SwitchExpression04() { TestSpan( @"class C { void Goo() { _ = e switch { 1 [|when f|] $$=> 2, 3 when g => 4, _ => 5, }; } }"); } [Fact] public void SwitchExpression05() { TestSpan( @"class C { void Goo() { _ = e switch { 1 when f =$$> [|2|], 3 when g => 4, _ => 5, }; } }"); } [Fact] public void SwitchExpression06() { TestSpan( @"class C { void Goo() { _ = e switch { 1 when f => [|2|],$$ 3 when g => 4, _ => 5, }; } }"); } [Fact] public void SwitchExpression07() { TestSpan( @"class C { void Goo() { _ = e switch { 1 when f => 2, $$ 3 [|when g|] => 4, _ => 5, }; } }"); } [Fact] public void SwitchExpression08() { TestSpan( @"class C { void Goo() { _ = e switch { 1 when f => 2, 3 when g => [|4|],$$ _ => 5, }; } }"); } [Fact] public void SwitchExpression09() { TestSpan( @"class C { void Goo() { _ = e switch { 1 when f => 2, 3 when g => 4, $$ _ => [|5|], }; } }"); } [Fact] public void SwitchExpression10() { TestSpan( @"class C { void Goo() { _ = e switch { 1 when f => 2, 3 when g => 4, _ => [|5|],$$ }; } }"); } [Fact] public void SwitchExpression11() { TestSpan( @"class C { void Goo() { _ = e switch { 1 when f => 2, 3 when g => 4, _ => [|5|], $$}; } }"); } [Fact] public void SwitchExpression12() { TestSpan( @"class C { void Goo() { [|_ = e switch { 1 when f => 2, 3 when g => 4, _ => 5, }$$;|] } }"); } #endregion #region For and ForEach [Fact] public void ForStatementInitializer1a() { TestSpan( @"class C { void Goo() { $$ for ([|i = 0|], j = 0; i < 10 && j < 10; i++, j++) { } } }"); } [Fact] public void ForStatementInitializer1b() { TestSpan( @"class C { void Goo() { f$$or ([|i = 0|], j = 0; i < 10 && j < 10; i++, j++) { } } }"); } [Fact] public void ForStatementInitializer1c() { TestSpan( @"class C { void Goo() { for ([|i $$= 0|], j = 0; i < 10 && j < 10; i++, j++) { } } }"); } [Fact] public void ForStatementInitializer1d() { TestSpan( @"class C { void Goo() { for $$ ( [|i = 0|], j = 0; i < 10 && j < 10; i++, j++) { } } }"); } [Fact] public void ForStatementInitializer2() { TestSpan( @"class C { void Goo() { for (i = 0, [|$$j = 0|]; i < 10 && j < 10; i++, j++) { } } }"); } [Fact] public void ForStatementInitializer3() => TestSpan("class C { void M() { for([|i = 0$$|]; ; }; }"); [Fact] public void ForStatementCondition() { TestSpan( @"class C { void Goo() { for (i = 0, j = 0; [|i < 10 && j < $$10|]; i++, j++) { } } }"); } [Fact] public void ForStatementIncrementor1() { TestSpan( @"class C { void Goo() { for (i = 0, j = 0; i < 10 && j < 10; [|i+$$+|], j++) { } } }"); } [Fact] public void ForStatementIncrementor2() { TestSpan( @"class C { void Goo() { for (i = 0, j = 0; i < 10 && j < 10; i++, [|$$j++|]) { } } }"); } [Fact] public void ForEachStatementExpression() { TestSpan( @"class C { void Goo() { foreach (var v in [|Goo().B$$ar()|]) { } } }"); } [Fact] public void ForEachDeconstructionStatementExpression() { TestSpan( @"class C { void Goo() { foreach (var (x, y) in [|Goo().B$$ar()|]) { } } }"); } #endregion #region Lambdas [Fact] public void SimpleLambdaBody() { TestSpan( @"class C { void Goo() { Func<string> f = s => [|G$$oo()|]; } }"); } [Fact] public void ParenthesizedLambdaBody() { TestSpan( @"class C { void Goo() { Func<string> f = (s, i) => [|G$$oo()|]; } }"); } [Fact] public void AnonymousMethod1() { TestSpan( @"class C { void Goo() { Func<int> f = delegate [|$${|] return 1; }; } }"); } [Fact] public void AnonymousMethod2() { TestSpan( @"class C { void Goo() { Func<int> f = delegate { [|$$return 1;|] }; } }"); } #endregion #region Queries [Fact] public void FirstFromClauseExpression() { TestSpan( @"class C { void Goo() { [|var q = from x in bl$$ah() from y in quux().z() select y;|] } }"); } [Fact] public void SecondFromClauseExpression() { TestSpan( @"class C { void Goo() { var q = from x in blah() from y in [|quux().z$$()|] select y; } }"); } [Fact] public void FromInQueryContinuation1() { TestSpan( @"class C { void Goo() { var q = from x in blah() from y in quux().z() group x by y into g from m in [|g.C$$ount()|] select m.Blah(); } }"); } [Fact] public void FromInQueryContinuation2() { TestSpan( @"class C { void Goo() { var q = from x in blah() from y in quux().z() group x by y into g $$ from m in [|g.Count()|] select m.Blah(); } }"); } [Fact] public void JoinClauseLeftExpression() { TestSpan( @"class C { void Goo() { var q = from x in blah() join a in alpha on [|left().exp$$r()|] equals right().expr() select y; } }"); } [Fact] public void JoinClauseRightExpression() { TestSpan( @"class C { void Goo() { var q = from x in blah() join a in alpha on left().expr() equals [|righ$$t().expr()|] select y; } }"); } [Fact] public void LetClauseExpression() { TestSpan( @"class C { void Goo() { var q = from x in blah() join a in alpha on left().expr() equals right.expr() let a = [|expr().$$expr()|] select y; } }"); } [Fact] public void WhereClauseExpression() { TestSpan( @"class C { void Goo() { var q = from x in blah() join a in alpha on left().expr() equals right.expr() where [|expr().$$expr()|] select y; } }"); } [Fact] public void WhereClauseKeyword() { TestSpan( @"class C { void Goo() { var q = from x in blah() whe$$re [|expr().expr()|] select y; } }"); } [Fact] public void SimpleOrdering1() { TestSpan( @"class C { void Goo() { var q = from x in blah() join a in alpha on left().expr() equals right.expr() orderby [|expr().$$expr()|] select y; } }"); } [Fact] public void SimpleOrdering2() { TestSpan( @"class C { void Goo() { var q = from x in blah() join a in alpha on left().expr() equals right.expr() orderby goo, [|expr().$$expr()|] select y; } }"); } [Fact] public void AscendingOrdering1() { TestSpan( @"class C { void Goo() { var q = from x in blah() join a in alpha on left().expr() equals right.expr() orderby [|expr().$$expr()|] ascending select y; } }"); } [Fact] public void AscendingOrdering2() { TestSpan( @"class C { void Goo() { var q = from x in blah() join a in alpha on left().expr() equals right.expr() orderby goo, [|expr().$$expr()|] ascending select y; } }"); } [Fact] public void DescendingOrdering1() { TestSpan( @"class C { void Goo() { var q = from x in blah() join a in alpha on left().expr() equals right.expr() orderby [|expr().$$expr()|] descending select y; } }"); } [Fact] public void DescendingOrdering2() { TestSpan( @"class C { void Goo() { var q = from x in blah() join a in alpha on left().expr() equals right.expr() orderby goo, [|expr().$$expr()|] descending select y; } }"); } [Fact] public void OrderByKeyword() => TestSpan("class C { void M() { from string s in null ord$$erby [|s.A|] ascending } }"); [Fact] public void AscendingKeyword() => TestSpan("class C { void M() { from string s in null orderby [|s.A|] $$ascending } }"); [Fact] public void SelectExpression() { TestSpan( @"class C { void Goo() { var q = from x in blah() join a in alpha on left().expr() equals right.expr() orderby goo, expr().expr() descending select [|y.$$blah()|]; } }"); } [Fact] public void AnonymousTypeAfterSelect() { TestSpan( @"class C { public void () { var q = from c in categories join p in products on c equals p.Category into ps select [|new { Category = c, $$Products = ps }|]; } }"); } [Fact] public void GroupExpression() { TestSpan( @"class C { void Goo() { var q = from x in blah() join a in alpha on left().expr() equals right.expr() orderby goo, expr().expr() descending group [|bar()$$.goo()|] by blah().zap() select y.blah(); } }"); } [Fact] public void GroupByKeyword() { TestSpan( @"class C { void Goo() { var q = from x in blah() join a in alpha on left().expr() equals right.expr() orderby goo, expr().expr() descending group [|bar().goo()|] b$$y blah().zap() select y.blah(); } }"); } [Fact] public void GroupByExpression() { TestSpan( @"class C { void Goo() { var q = from x in blah() join a in alpha on left().expr() equals right.expr() orderby goo, expr().expr() descending group bar().goo() by [|blah()$$.zap()|] select y.blah(); } }"); } [Fact] public void InFrontOfFirstFromClause() { TestSpan( @"class C { void Goo() { [|var q = $$ from x in blah() from y in zap() let m = quux() join a in alpha on left().expr() equals right.expr() orderby goo, expr().expr() descending group bar().goo() by blah().zap() into g select y.blah();|] } }"); } [Fact] public void InFrontOfSecondFromClause() { TestSpan( @"class C { void Goo() { var q = from x in blah() $$ from y in [|zap()|] let m = quux() join a in alpha on left().expr() equals right.expr() orderby goo, expr().expr() descending group bar().goo() by blah().zap() into g select y.blah(); } }"); } [Fact] public void InFrontOfLetClause() { TestSpan( @"class C { void Goo() { var q = from x in blah() from y in zap() $$ let m = [|quux()|] join a in alpha on left().expr() equals right.expr() orderby goo, expr().expr() descending group bar().goo() by blah().zap() into g select y.blah(); } }"); } [Fact] public void InFrontOfJoinClause() { TestSpan( @"class C { void Goo() { var q = from x in blah() from y in zap() let m = quux() $$ join a in alpha on [|left().expr()|] equals right.expr() orderby goo, expr().expr() descending group bar().goo() by blah().zap() into g select y.blah(); } }"); } [Fact] public void InFrontOfOrderByClause() { TestSpan( @"class C { void Goo() { var q = from x in blah() from y in zap() let m = quux() join a in alpha on left().expr() equals right.expr() $$ orderby [|goo|], expr().expr() descending group bar().goo() by blah().zap() into g select y.blah(); } }"); } [Fact] public void InFrontOfGroupByClause() { TestSpan( @"class C { void Goo() { var q = from x in blah() from y in zap() let m = quux() join a in alpha on left().expr() equals right.expr() orderby goo, expr().expr() descending $$ group [|bar().goo()|] by blah().zap() into g select y.blah(); }"); } [Fact] public void InFrontOfSelectClause() { TestSpan( @"class C { void Goo() { var q = from x in blah() from y in zap() let m = quux() join a in alpha on left().expr() equals right.expr() orderby goo, expr().expr() descending group bar().goo() by blah().zap() into g $$ select [|y.blah()|]; }"); } [Fact] public void Select1() { TestSpan( @"class C { IEnumerable<int> Goo() => from x in new[] { 1 } select [|$$x|]; } "); } [Fact] public void Select_NoLambda1() { TestSpan( @"class C { IEnumerable<int> Goo() => [|from x in new[] { 1 } where x > 0 select $$x|]; } "); } [Fact] public void Select_NoLambda2() { TestSpan( @"class C { IEnumerable<int> Goo() => [|from x in new[] { 1 } select x into y orderby y select $$y|]; } "); } [Fact] public void GroupBy1() { TestSpan( @"class C { IEnumerable<int> Goo() => from x in new[] { 1 } group x by [|$$x|]; } "); } [Fact] public void GroupBy_NoLambda1() { TestSpan( @"class C { IEnumerable<int> Goo() => [|from x in new[] { 1 } group $$x by x|]; } "); } [Fact] public void GroupBy_NoLambda2() { TestSpan( @"class C { IEnumerable<int> Goo() => [|from x in new[] { 1 } group $$x by x + 1 into y group y by y.Key + 2|]; } "); } [Fact] public void GroupBy_NoLambda3() { TestSpan( @"class C { IEnumerable<int> Goo() => [|from x in new[] { 1 } group x by x + 1 into y group $$y by y.Key + 2|]; } "); } #endregion #region Field and Veriable Declarators [Fact] public void FieldDeclarator_WithoutInitializer_All() { VerifyAllSpansInDeclaration<VariableDeclaratorSyntax>( @"class C { int $$i, j; }"); } [Fact] public void FieldDeclarator_WithoutInitializer1() { TestMissing( @"class C { int $$i; }"); } [Fact] public void FieldDeclarator_WithoutInitializer2() { TestMissing( @"class C { pri$$vate int i; }"); } [Fact] public void FieldDeclarator_SingleVariable_Initializer_All1() { VerifyAllSpansInDeclaration<VariableDeclaratorSyntax>( @"class C { [Goo] private int $$i; }"); } [Fact] public void FieldDeclarator_SingleVariable_Initializer_All2() { VerifyAllSpansInDeclaration<VariableDeclaratorSyntax>( @"class C { [Goo] [|int $$i = 0;|] }"); } [Fact] public void FieldDeclarator_SingleVariable_Initializer_All3() { VerifyAllSpansInDeclaration<VariableDeclaratorSyntax>( @"class C { [Goo] [|private int $$i = 0;|] }"); } [Fact] public void FieldDeclarator_MultiVariable_Initializer_All1() { VerifyAllSpansInDeclaration<VariableDeclaratorSyntax>( @"class C { [Goo] [|private int $$i = 0|], j = 2; }"); } [Fact] public void FieldDeclarator_MultiVariable_Initializer_All2() { VerifyAllSpansInDeclaration<VariableDeclaratorSyntax>( @"class C { [Goo] [|int $$i = 0|], j = 2; }"); } [Fact] public void FieldDeclarator_MultiVariable_Initializer_All3() { VerifyAllSpansInDeclaration<VariableDeclaratorSyntax>( @"class C { [Goo] private int i = 0, [|$$j = 0|]; }"); } [Fact] public void FieldDeclarator_Initializer1() { TestSpan( @"class C { [|int $$i = 1;|] }"); } [Fact] public void FieldDeclarator_Initializer2() { TestSpan( @"class C { [|private int $$i = 1;|] }"); } [Fact] public void FieldDeclarator_Initializer3() { TestSpan( @"class C { [Goo] [|private int $$i = 0;|] }"); } [Fact] public void FieldDeclarator_Initializer4() { TestSpan( @"class C { [|pri$$vate int i = 1;|] }"); } [Fact] public void FieldDeclarator_Initializer5() { TestSpan( @"class C { $$ [|private int i = 3;|] }"); } [Fact] public void ConstVariableDeclarator0() => TestMissing("class C { void Goo() { const int a = $$1; } }"); [Fact] public void ConstVariableDeclarator1() => TestMissing("class C { void Goo() { const $$int a = 1; } }"); [Fact] public void ConstVariableDeclarator2() => TestMissing("class C { void Goo() { $$const int a = 1; } }"); [Fact] public void ConstFieldVariableDeclarator_All() { VerifyAllSpansInDeclaration<VariableDeclaratorSyntax>( @"class C { [Goo] private const int i = 0, j, $$k = 0; }"); } [Fact] public void ConstFieldVariableDeclarator0() => TestMissing("class C { const int a = $$1; }"); [Fact] public void ConstFieldVariableDeclarator1() => TestMissing("class C { const $$int a = 1; }"); [Fact] public void ConstFieldVariableDeclarator2() => TestMissing("class C { $$const int a = 1; }"); [Fact] [WorkItem(538777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538777")] public void VariableDeclarator0() => TestMissing("class C { void Goo() { int$$ } }"); [Fact] public void VariableDeclarator1() { TestMissing( @"class C { void Goo() { int $$i; } }"); } [Fact] public void VariableDeclarator2a() { TestSpan( @"class C { void Goo() { [|int $$i = 0;|] } }"); } [Fact] public void VariableDeclarator2b() { TestSpan( @"class C { void Goo() { $$ [|int i = 0;|] } }"); } [Fact] public void VariableDeclarator2c() { TestSpan( @"class C { void Goo() { [|$$int i = 0;|] } }"); } [Fact] public void VariableDeclarator3a() { TestSpan( @"class C { void Goo() { int i = 0, [|$$j = 3|]; } }"); } [Fact] public void VariableDeclarator3b() { TestSpan( @"class C { void Goo() { [|int i = 0|], $$j; } }"); } [Fact] public void VariableDeclarator3c() { TestSpan( @"class C { void Goo() { int $$i, [|j = 0|]; } }"); } [Fact] public void VariableDeclarator4() { TestSpan( @"class C { void Goo() { int i = 0, [|j = $$1|]; } }"); } [Fact] public void VariableDeclarator5() { TestSpan( @"class C { [|int $$i = 0;|] }"); } [Fact] public void VariableDeclarator6() { TestSpan( @"class C { [|int i = 0|], $$j; }"); } [Fact] public void VariableDeclarator7() { TestSpan( @"class C { private int i = 0, [|j = $$1|]; }"); } [Fact] public void VariableDeclarator8() { TestSpan( @"class C { [|priv$$ate int i = 0|], j = 1; }"); } [Fact] public void VariableDeclarator9() { TestSpan( @"class C { $$ [|private int i = 0|], j = 1; }"); } [Fact] public void VariableDeclarator10() => TestSpan("class C { void M() { [|int i = 0$$;|] } }"); [Fact] public void VariableDeclarator_Separators0() { TestSpan( @"class C { void Goo() { $$ [|int i = 0|], j = 1, k = 2; } }"); } [Fact] public void VariableDeclarator_Separators1() { TestSpan( @"class C { void Goo() { [|int i = 0|]$$, j = 1, k = 2; } }"); } [Fact] public void VariableDeclarator_Separators2() { TestSpan( @"class C { void Goo() { int i = 0, [|j = 1|]$$, k = 2; } }"); } [Fact] public void VariableDeclarator_Separators3() { TestSpan( @"class C { void Goo() { int i = 0, j = 1,$$ [|k = 2|]; } }"); } [Fact] public void VariableDeclarator_Separators4() { TestSpan( @"class C { void Goo() { int i = 0, j = 1, [|k = 2|]$$; } }"); } [Fact] public void VariableDeclarator_Separators5() { TestSpan( @"class C { void Goo() { [|int i = 0|], j = 1, k = 2;$$ } }"); } [Fact] public void VariableDeclarator_Separators6() { TestSpan( @"class C { void Goo() { int i = 1, j, $$k, [|l = 2|]; } }"); } [Fact] public void VariableDeclarator_Separators7() { TestSpan( @"class C { void Goo() { int i$$, j, k, [|l = 2|]; } }"); } [Fact] public void VariableDeclarator_Separators8() { TestSpan( @"class C { void Goo() { [|int i = 2|], j, k, l$$; } }"); } [Fact] public void VariableDeclarator_Separators9() { TestSpan( @"class C { void Goo() { int i, j, [|k = 1|], m, l = 2;$$ } }"); } [Fact] public void EventFieldDeclarator1() { TestSpan( @"class C { $$ [|public event EventHandler MyEvent = delegate { };|] }"); } [Fact] public void EventFieldDeclarator2() { TestSpan( @"class C { [|pub$$lic event EventHandler MyEvent = delegate { };|] }"); } [Fact] public void EventFieldDeclarator3() { TestSpan( @"class C { [|public ev$$ent EventHandler MyEvent = delegate { };|] }"); } [Fact] public void EventFieldDeclarator4() { TestSpan( @"class C { [|public event EventHan$$dler MyEvent = delegate { };|] }"); } [Fact] public void EventFieldDeclarator5() { TestSpan( @"class C { [|public event EventHandler MyE$$vent = delegate { };|] }"); } [Fact] public void EventFieldDeclarator6() { TestSpan( @"class C { [|public event EventHandler MyEvent $$= delegate { };|] }"); } [Fact] public void EventFieldDeclarator7() { TestSpan( @"class C { [|public event EventHandler MyEvent = del$$egate { };|] }"); } [Fact] public void EventFieldDeclarator8() { TestSpan( @"class C { public event EventHandler MyEvent = delegate [|{|] $$ }; }"); } #endregion [Fact] public void EventAccessorAdd() => TestSpan("class C { eve$$nt Action Goo { add [|{|] } remove { } } }"); [Fact] public void EventAccessorAdd2() => TestSpan("class C { event Action Goo { ad$$d [|{|] } remove { } } }"); [Fact] public void EventAccessorRemove() => TestSpan("class C { event Action Goo { add { } $$remove [|{|] } } }"); [Fact] public void ElseClauseWithBlock() { TestSpan( @"class C { void Goo() { if (bar) { } el$$se [|{|] } } }"); } [Fact] public void ElseClauseWithStatement() { TestSpan( @"class C { void Goo() { if (bar) { } el$$se [|Goo();|] } }"); } [Fact] public void ElseIf() { TestSpan( @"class C { void Goo() { if (bar) { } el$$se [|if (baz)|] Goo(); } }"); } [Fact] public void EmptyCatch() { TestSpan( @"class C { void Goo() { try { } [|cat$$ch|] { } } }"); } [Fact] public void CatchWithType() { TestSpan( @"class C { void Goo() { try { } [|cat$$ch(Exception)|] { } } }"); } [Fact] public void CatchWithTypeInType() { TestSpan( @"class C { void Goo() { try { } [|catch(Exce$$ption)|] { } } }"); } [Fact] public void CatchWithTypeAndNameInType() { TestSpan( @"class C { void Goo() { try { } [|catch(Exce$$ption e)|] { } } }"); } [Fact] public void CatchWithTypeAndNameInName() { TestSpan( @"class C { void Goo() { try { } [|catch(Exception $$e)|] { } } }"); } [Fact] public void Filter1() { TestSpan( @"class C { void Goo() { try { } $$catch(Exception e) [|when (e.Message != null)|] { } } }"); } [Fact] public void Filter3() { TestSpan( @"class C { void Goo() { try { } catch(Exception e)$$ [|when (e.Message != null)|] { } } }"); } [Fact] public void Filter4() { TestSpan( @"class C { void Goo() { try { } catch(Exception e) [|when$$ (e.Message != null)|] { } } }"); } [Fact] public void Filter5() { TestSpan( @"class C { void Goo() { try { } catch(Exception e) [|when (e.Message != null)|] $$ { } } }"); } [Fact] public void SimpleFinally() { TestSpan( @"class C { void Goo() { try { } final$$ly [|{|] } } }"); } [Fact] public void FinallyWithCatch() { TestSpan( @"class C { void Goo() { try { } catch { } final$$ly [|{|] } } }"); } [Fact] public void SwitchLabelWithBlock() { TestSpan( @"class C { void Goo() { switch (goo) { case $$1: [|{|] } } } }"); } [Fact] public void SwitchLabelWithStatement() { TestSpan( @"class C { void Goo() { switch (goo) { cas$$e 1: [|goo();|] } } }"); } [Fact] public void SwitchLabelWithStatement2() { TestSpan( @"class C { void Goo() { switch (goo) { cas$$e 1: [|goo();|] bar(); } } }"); } [Fact] public void SwitchLabelWithoutStatement() => TestSpan("class C { void M() { [|switch |]{ case 1$$: } } }"); [Fact] public void MultipleLabelsOnFirstLabel() { TestSpan( @"class C { void Goo() { switch (goo) { cas$$e 1: case 2: [|goo();|] case 3: default: bar(); } } }"); } [Fact] public void MultipleLabelsOnSecondLabel() { TestSpan( @"class C { void Goo() { switch (goo) { case 1: cas$$e 2: [|goo();|] case 3: default: bar(); } } }"); } [Fact] public void MultipleLabelsOnLabelWithDefault() { TestSpan( @"class C { void Goo() { switch (goo) { case 1: case 2: goo(); cas$$e 3: default: [|bar();|] } } }"); } [Fact] public void MultipleLabelsOnDefault() { TestSpan( @"class C { void Goo() { switch (goo) { case 1: case 2: goo(); case 3: default:$$ [|bar();|] } } }"); } [Fact] public void BlockBeforeStartToken() { TestSpan( @"class C { void Goo() [|$${|] } }"); } [Fact] public void BlockBeforeStartToken2() { TestSpan( @"class C { void Goo() $$ [|{|] } }"); } [Fact] public void BlockAfterStartToken() { TestSpan( @"class C { void Goo() [|{$$|] } }"); } [Fact] public void BlockAfterStartToken2() { TestSpan( @"class C { void Goo() [|{|] $$ } }"); } [Fact] public void BlockBeforeEndToken1() { TestSpan( @"class C { void Goo() { $$[|}|] }"); } [Fact] public void BlockBeforeEndToken2() { TestSpan( @"class C { void Goo() { $$ [|}|] }"); } [Fact] public void BlockAfterEndToken1() { TestSpan( @"class C { void Goo() { [|}|]$$ }"); } [Fact] public void BlockAfterEndToken2() { TestSpan( @"class C { void Goo() { [|}|] $$ }"); } [Fact] public void SingleDeclarationOnType() { TestMissing( @"class C { void Goo() { i$$nt i; } }"); } [Fact] public void MultipleDeclarationsOnType() { TestSpan( @"class C { void Goo() { [|i$$nt i = 0|], j = 1; } }"); } [Fact] public void Label() { TestSpan( @"class C { void Goo() { go$$o: [|bar();|] } }"); } [Fact] public void WhileInWhile() { TestSpan( @"class C { void Goo() { [|w$$hile (expr)|] { } } }"); } [Fact] public void WhileInExpr() { TestSpan( @"class C { void Goo() { [|while (ex$$pr)|] { } } }"); } [Fact] public void OnWhileBlock() { TestSpan( @"class C { void Goo() { while (expr) $$ [|{|] } } }"); } [Fact] public void OnDoKeyword() { TestSpan( @"class C { void Goo() { d$$o [|{|] } while(expr); } }"); } [Fact] public void OnDoBlock() { TestSpan( @"class C { void Goo() { do $$ [|{|] } while(expr); } }"); } [Fact] public void OnDoWhile() { TestSpan( @"class C { void Goo() { do { } [|wh$$ile(expr);|] } }"); } [Fact] public void OnDoWhile_MissingSemicolon() { TestSpan( @"class C { void Goo() { do { } [|wh$$ile(expr)|] } }"); } [Fact] public void OnDoExpression() { TestSpan( @"class C { void Goo() { do { } [|while(ex$$pr);|] } }"); } [Fact] public void OnForWithDeclaration1() { TestSpan( @"class C { void Goo() { f$$or ([|int i = 0|], j = 1; i < 10 && j < 10; i++, j++) { } } }"); } [Fact] public void OnForWithDeclaration2() { TestSpan( @"class C { void Goo() { f$$or ([|int i = 0|]; i < 10 && j < 10; i++, j++) { } } }"); } [Fact] public void OnForWithCondition() { TestSpan( @"class C { void Goo() { f$$or (; [|i < 10 && j < 10|]; i++, j++) { } } }"); } [Fact] public void OnForWithIncrementor1() { TestSpan( @"class C { void Goo() { f$$or (; ; [|i++|], j++) { } } }"); } [Fact] public void OnForWithIncrementor2() { TestSpan( @"class C { void Goo() { f$$or (; ; [|i++|]) { } } }"); } [Fact] public void OnEmptyFor() { TestSpan( @"class C { void Goo() { f$$or (; ; ) [|{|] } } }"); } [Fact] public void OnForEachKeyword1() { TestSpan( @"class C { void Goo() { $$ [|foreach|] (var v in expr().blah()) { } } }"); } [Fact] public void OnForEachKeyword2() { TestSpan( @"class C { void Goo() { [|fo$$reach|] (var v in expr().blah()) { } } }"); } [Fact] public void OnForEachKeyword3() { TestSpan( @"class C { void Goo() { [|foreach|] $$ (var v in expr().blah()) { } } }"); } [Fact] public void OnForEachKeyword4() { TestSpan( @"class C { void Goo() { [|foreach|] $$ (var v in expr().blah()) { } } }"); } [Fact] public void OnForEachKeyword5() { TestSpan( @"class C { void Goo() { [|foreach|] $$(var v in expr().blah()) { } } }"); } [Fact] public void OnForEachType1() { TestSpan( @"class C { void Goo() { foreach ( $$ [|var v|] in expr().blah()) { } } }"); } [Fact] public void OnForEachType2() { TestSpan( @"class C { void Goo() { foreach ([|v$$ar v|] in expr().blah()) { } } }"); } [Fact] public void OnForEachIdentifier() { TestSpan( @"class C { void Goo() { foreach ([|var v$$v|] in expr().blah()) { } } }"); } [Fact] public void OnForEachIn1() { TestSpan( @"class C { void Goo() { foreach (var v [|i$$n|] expr().blah()) { } } }"); } [Fact] public void OnForEachIn2() { TestSpan( @"class C { void Goo() { foreach (var v $$ [|in|] expr().blah()) { } } }"); } [Fact] public void OnForEachIn3() { TestSpan( @"class C { void Goo() { foreach (var v [|in|] $$ expr().blah()) { } } }"); } [Fact] public void OnForEachExpr1() { TestSpan( @"class C { void Goo() { foreach (var v in [|expr($$).blah()|]) { } } }"); } [Fact] public void OnForEachExpr2() { TestSpan( @"class C { void Goo() { foreach (var v in [|expr().blah()|] $$ ) { } } }"); } [Fact] public void OnForEachExpr3() { TestSpan( @"class C { void Goo() { foreach (var v in $$ [|expr().blah()|] ) { } } }"); } [Fact] public void OnForEachStatement() { TestSpan( @"class C { void Goo() { [|foreach|](var v in expr().blah()) $$ { } } }"); } [Fact] public void OnForEachBlock1() { TestSpan( @"class C { void Goo() { foreach (var v in expr().blah()) $$ [|{|] } } }"); } [Fact] public void OnForEachDeconstructionKeyword1() { TestSpan( @"class C { void Goo() { $$ [|foreach|] (var (x, y) in expr().blah()) { } } }"); } [Fact] public void OnForEachDeconstructionKeyword2() { TestSpan( @"class C { void Goo() { [|fo$$reach|] (var (x, y) in expr().blah()) { } } }"); } [Fact] public void OnForEachDeconstructionKeyword3() { TestSpan( @"class C { void Goo() { [|foreach|] $$ (var (x, y) in expr().blah()) { } } }"); } [Fact] public void OnForEachDeconstructionKeyword4() { TestSpan( @"class C { void Goo() { [|foreach|] $$ (var (x, y) in expr().blah()) { } } }"); } [Fact] public void OnForEachDeconstructionKeyword5() { TestSpan( @"class C { void Goo() { [|foreach|] $$(var (x, y) in expr().blah()) { } } }"); } [Fact] public void OnForEachDeconstructionType1() { TestSpan( @"class C { void Goo() { foreach ( $$ [|var (x, y)|] in expr().blah()) { } } }"); } [Fact] public void OnForEachDeconstructionType2() { TestSpan( @"class C { void Goo() { foreach ([|v$$ar (x, y)|] in expr().blah()) { } } }"); } [Fact] public void OnForEachDeconstructionIdentifier() { TestSpan( @"class C { void Goo() { foreach ([|var (v$$v, y)|] in expr().blah()) { } } }"); } [Fact] public void OnForEachDeconstructionIn1() { TestSpan( @"class C { void Goo() { foreach (var (x, y) [|i$$n|] expr().blah()) { } } }"); } [Fact] public void OnForEachDeconstructionIn2() { TestSpan( @"class C { void Goo() { foreach (var (x, y) $$ [|in|] expr().blah()) { } } }"); } [Fact] public void OnForEachDeconstructionIn3() { TestSpan( @"class C { void Goo() { foreach (var (x, y) [|in|] $$ expr().blah()) { } } }"); } [Fact] public void OnForEachDeconstructionExpr1() { TestSpan( @"class C { void Goo() { foreach (var (x, y) in [|expr($$).blah()|]) { } } }"); } [Fact] public void OnForEachDeconstructionExpr2() { TestSpan( @"class C { void Goo() { foreach (var (x, y) in [|expr().blah()|] $$ ) { } } }"); } [Fact] public void OnForEachDeconstructionExpr3() { TestSpan( @"class C { void Goo() { foreach (var (x, y) in $$ [|expr().blah()|] ) { } } }"); } [Fact] public void OnForEachDeconstructionStatement() { TestSpan( @"class C { void Goo() { [|foreach|](var (x, y) in expr().blah()) $$ { } } }"); } [Fact] public void OnForEachDeconstructionBlock1() { TestSpan( @"class C { void Goo() { foreach (var (x, y) in expr().blah()) $$ [|{|] } } }"); } [Fact] public void OnUsingWithDecl1() { TestSpan( @"class C { void Goo() { us$$ing ([|var v = goo()|]) { } } }"); } [Fact] public void OnUsingWithDecl2() { TestSpan( @"class C { void Goo() { us$$ing ([|var v = goo()|], x = bar()) { } } }"); } [Fact] public void OnUsingWithDeclType() { TestSpan( @"class C { void Goo() { using ([|v$$ar v = goo()|]) { } } }"); } [Fact] public void OnUsingWithDeclIdentifier1() { TestSpan( @"class C { void Goo() { using ([|var v$$v = goo()|]) { } } }"); } [Fact] public void OnUsingWithDeclIdentifier2() { TestSpan( @"class C { void Goo() { using ([|var vv = goo()|]) $$ { } } }"); } [Fact] public void OnUsingWithDeclIdentifier3() { TestSpan( @"class C { void Goo() { $$ using ([|var vv = goo()|]) { } } }"); } [Fact] public void OnUsingWithDeclExpression() { TestSpan( @"class C { void Goo() { using ([|var vv = go$$o()|]) { } } }"); } [Fact] public void OnUsingWithExpression1() { TestSpan( @"class C { void Goo() { [|usi$$ng (goo().bar())|] { } } }"); } [Fact] public void OnUsingWithExpression2() { TestSpan( @"class C { void Goo() { [|using (goo$$().bar())|] { } } }"); } [Fact] public void OnFixed1() { TestSpan( @"class C { void Goo() { fi$$xed ([|int* i = &j|]) { } } }"); } [Fact] public void OnFixed2() { TestSpan( @"class C { void Goo() { fi$$xed ([|int* i = &j|], k = &m) { } } }"); } [Fact] public void OnFixed3() { TestSpan( @"class C { void Goo() { fixed ([|i$$nt* i = &j|]) { } } }"); } [Fact] public void OnFixed4() { TestSpan( @"class C { void Goo() { fixed ([|int* $$i = &j|]) { } } }"); } [Fact] public void OnFixed5() { TestSpan( @"class C { void Goo() { fixed ([|int* i $$= &j|]) { } } }"); } [Fact] public void OnFixed6() { TestSpan( @"class C { void Goo() { fixed ([|int* i = &$$j|]) { } } }"); } [Fact] public void OnChecked1() { TestSpan( @"class C { void Goo() { che$$cked [|{|] } } }"); } [Fact] public void OnUnchecked1() { TestSpan( @"class C { void Goo() { unche$$cked [|{|] } } }"); } [Fact] public void OnUnsafe1() { TestSpan( @"class C { void Goo() { uns$$afe [|{|] } } }"); } [Fact] public void OnLock1() { TestSpan( @"class C { void Goo() { [|lo$$ck (expr)|] { } } }"); } [Fact] public void OnLock2() { TestSpan( @"class C { void Goo() { [|lock (ex$$pr)|] { } } }"); } [Fact] public void OnIf1() { TestSpan( @"class C { void Goo() { [|i$$f (goo().bar())|] { } } }"); } [Fact] public void OnIf2() { TestSpan( @"class C { void Goo() { [|if (go$$o().bar())|] { } } }"); } [Fact] public void OnIfBlock() { TestSpan( @"class C { void Goo() { if (goo().bar()) $$ [|{|] } } }"); } [Fact] public void OnSwitch1() { TestSpan( @"class C { void Goo() { [|swi$$tch (expr)|] { default: goo(); } } }"); } [Fact] public void OnSwitch2() { TestSpan( @"class C { void Goo() { [|switch (ex$$pr)|] { default: goo(); } } }"); } [Fact] public void OnSwitch3() { TestSpan( @"class C { void Goo() { [|switch (expr)|] $$ { default: goo(); } } }"); } [Fact] public void OnSwitch4() { TestSpan( @"class C { void Goo() { [|switch (expr)|] { default: goo(); $$ } } }"); } [Fact] public void OnTry1() { TestSpan( @"class C { void Goo() { t$$ry [|{|] } finally { } } }"); } [Fact] public void OnTry2() { TestSpan( @"class C { void Goo() { try $$ [|{|] } finally { } } }"); } [Fact] public void OnGotoStatement1() { TestSpan( @"class C { void Goo() { [|g$$oto goo;|] } }"); } [Fact] public void OnGotoStatement2() { TestSpan( @"class C { void Goo() { [|goto go$$o;|] } }"); } [Fact] public void OnGotoCaseStatement1() { TestSpan( @"class C { void Goo() { switch (expr) { case 1: [|go$$to case 2;|] } } }"); } [Fact] public void OnGotoCaseStatement2() { TestSpan( @"class C { void Goo() { switch (expr) { case 1: [|goto ca$$se 2;|] } } }"); } [Fact] public void OnGotoCaseStatement3() { TestSpan( @"class C { void Goo() { switch (expr) { case 1: [|goto case $$2;|] } } }"); } [Fact] public void OnGotoDefault1() { TestSpan( @"class C { void Goo() { switch (expr) { case 1: [|go$$to default;|] } } }"); } [Fact] public void OnGotoDefault2() { TestSpan( @"class C { void Goo() { switch (expr) { case 1: [|goto defau$$lt;|] } } }"); } [Fact] public void OnBreak1() { TestSpan( @"class C { void Goo() { while (true) { [|bre$$ak;|] } } }"); } [Fact] public void OnContinue1() { TestSpan( @"class C { void Goo() { while (true) { [|cont$$inue;|] } } }"); } [Fact] public void OnReturn1() { TestSpan( @"class C { void Goo() { [|retu$$rn;|] } }"); } [Fact] public void OnReturn2() { TestSpan( @"class C { void Goo() { [|retu$$rn expr();|] } }"); } [Fact] public void OnReturn3() { TestSpan( @"class C { void Goo() { [|return expr$$().bar();|] } }"); } [Fact] public void OnYieldReturn1() { TestSpan( @"class C { void Goo() { [|yi$$eld return goo().bar();|] } }"); } [Fact] public void OnYieldReturn2() { TestSpan( @"class C { void Goo() { [|yield re$$turn goo().bar();|] } }"); } [Fact] public void OnYieldReturn3() { TestSpan( @"class C { void Goo() { [|yield return goo()$$.bar();|] } }"); } [Fact] public void OnYieldBreak1() { TestSpan( @"class C { void Goo() { [|yi$$eld break;|] } }"); } [Fact] public void OnYieldBreak2() { TestSpan( @"class C { void Goo() { [|yield brea$$k;|] } }"); } [Fact] public void OnThrow1() { TestSpan( @"class C { void Goo() { [|th$$row;|] } }"); } [Fact] public void OnThrow2() { TestSpan( @"class C { void Goo() { [|thr$$ow new Goo();|] } }"); } [Fact] public void OnThrow3() { TestSpan( @"class C { void Goo() { [|throw ne$$w Goo();|] } }"); } [Fact] public void OnThrow4() { TestSpan( @"class C { void Goo() { [|throw new Go$$o();|] } }"); } [Fact] public void OnExpressionStatement1() { TestSpan( @"class C { void Goo() { [|goo().$$bar();|] } }"); } [Fact] public void OnEmptyStatement1() { TestSpan( @"class C { void Goo() { [|$$;|] } }"); } [Fact] public void OnEmptyStatement2() { TestSpan( @"class C { void Goo() { while (true) { $$ [|;|] } } }"); } [Fact] public void OnPropertyAccessor1() { TestSpan( @"class C { int Goo { g$$et [|{|] } } }"); } [Fact] public void OnPropertyAccessor2() { TestSpan( @"class C { int Goo { [|g$$et;|] } }"); } [Fact] public void OnPropertyAccessor3() { TestSpan( @"class C { int Goo { get { } s$$et [|{|] } } }"); } [Fact] public void OnPropertyAccessor4() { TestSpan( @"class C { int Goo { [|s$$et;|] } }"); } [Fact] [WorkItem(48504, "https://github.com/dotnet/roslyn/issues/48504")] public void OnPropertyAccessor5() { TestSpan( @"class C { int Goo { [|in$$it;|] } }"); } [Fact] public void OnProperty1() { TestSpan( @"class C { int G$$oo { get [|{|] } set { } } }"); } [Fact] public void OnProperty2() { TestSpan( @"class C { int G$$oo { [|get;|] set {} } }"); } [WorkItem(932711, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/932711")] [Fact] public void OnPropertyWithInitializer() { TestSpan( @"class C { public int Id { get; set; } = [|int.Pa$$rse(""42"")|]; }"); TestSpan( @"class C { public int$$ Id { [|get;|] set; } = int.Parse(""42""); }"); TestSpan( @"class C { public int Id { get; [|set;|] $$} = int.Parse(""42""); }"); TestSpan( @"class C { public int Id { get; [|set;|] }$$ = int.Parse(""42""); }"); TestSpan( @"class C { public int Id { get; set; } =$$ [|int.Parse(""42"")|]; }"); } [Fact] public void OnPropertyExpressionBody1() { TestSpan( @"class C { public int Id => [|12$$3|]; }"); } [Fact] public void OnPropertyExpressionBody2() { TestSpan( @"class C { public int Id $$=> [|123|]; }"); } [Fact] public void OnPropertyExpressionBody3() { TestSpan( @"class C { $$public int Id => [|123|]; }"); } [Fact] public void OnPropertyExpressionBody4() { TestSpan( @"class C { public int Id => [|123|]; $$ }"); } [Fact] public void OnIndexerExpressionBody1() { TestSpan( @"class C { public int this[int a] => [|12$$3|]; }"); } [Fact] public void OnIndexer1() { TestSpan( @"class C { int this[int$$ a] { get [|{|] } set { } } }"); } [Fact] public void OnIndexer2() { TestSpan( @"class C { int this[int$$ a] { [|get;|] set { } } }"); } [Fact] public void OnIndexerExpressionBody2() { TestSpan( @"class C { public int this[int a] $$=> [|123|]; }"); } [Fact] public void OnIndexerExpressionBody3() { TestSpan( @"class C { $$public int this[int a] => [|123|]; }"); } [Fact] public void OnIndexerExpressionBody4() { TestSpan( @"class C { public int this[int a] => [|123|]; $$ }"); } [Fact] public void OnIndexerExpressionBody5() { TestSpan( @"class C { public int this[int $$a] => [|123|]; }"); } [Fact] public void OnMethod1() { TestSpan( @"class C { v$$oid Goo() [|{|] } }"); } [Fact] public void OnMethod2() { TestSpan( @"class C { void G$$oo() [|{|] } }"); } [Fact] public void OnMethod3() { TestSpan( @"class C { void Goo(in$$t i) [|{|] } }"); } [Fact] public void OnMethod4() { TestSpan( @"class C { void Goo(int $$i) [|{|] } }"); } [Fact] public void OnMethod5() { TestSpan( @"class C { void Goo(int i = g$$oo) [|{|] } }"); } [Fact] public void OnMethodWithExpressionBody1() { TestSpan( @"class C { v$$oid Goo() => [|123|]; }"); } [Fact] public void OnMethodWithExpressionBody2() { TestSpan( @"class C { void Goo() =>$$ [|123|]; }"); } [Fact] public void OnMethodWithExpressionBody3() { TestSpan( @"class C { void Goo() => [|123|]; $$ }"); } [Fact] public void OnMethodWithExpressionBody4() { TestSpan( @"class C { void Goo() => [|12$$3|]; }"); } [Fact] public void MissingOnMethod() { TestMissing( @"class C { void Goo($$); }"); } #region Constructors [Fact] public void InstanceConstructor_NoInitializer_BlockBody_All() { VerifyAllSpansInDeclaration<ConstructorDeclarationSyntax>( @"class C { [Attribute1, Attribute2][Attribute3][|$$public C()|] [|{|] [|}|] }"); } [Fact] public void InstanceConstructor_NoInitializer_BlockBody() { // a sequence point for base constructor call TestSpan( @"class C { [|pub$$lic C()|] { } }"); } [Fact] public void InstanceConstructor_NoInitializer_ExpressionBody_All() { VerifyAllSpansInDeclaration<ConstructorDeclarationSyntax>( @"class C { [Attribute1, Attribute2][Attribute3][|$$public C()|] => [|x = 1|]; }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void InstanceConstructor_NoInitializer_ExpressionBody1() { // a sequence point for base constructor call TestSpan( @"class C { [|pub$$lic C()|] => F(); }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void InstanceConstructor_NoInitializer_ExpressionBody2() { // a sequence point for base constructor call TestSpan( @"class C { [|public C()|] $$=> x = 1); }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void InstanceConstructor_NoInitializer_ExpressionBody3() { // a sequence point for base constructor call TestSpan( @"class C { public C() =$$> [|x = 1|]; }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void InstanceConstructor_NoInitializer_ExpressionBody4() { // a sequence point for base constructor call TestSpan( @"class C { public C() => [|$$x = 1|]; }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void InstanceConstructor_NoInitializer_ExpressionBody5() { TestSpan( @"class C { public C() => [|x =$$ 1|]; }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void InstanceConstructor_NoInitializer_ExpressionBody6() { TestSpan( @"class C { public C() => [|x = 1|]$$; }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void InstanceConstructor_NoInitializer_ExpressionBody7() { TestSpan( @"class C { public C() => [|x = 1|];$$ }"); } [Fact] public void InstanceConstructor_NoInitializer_Attributes() { TestSpan( @"class C { [Attribute1,$$ Attribute2] [Attribute3] [|public C()|] { } }"); } [Fact] public void InstanceConstructor_BaseInitializer_BlockBody_All() { VerifyAllSpansInDeclaration<ConstructorDeclarationSyntax>( @"class C { [Attribute1, Attribute2][Attribute3]$$public C() : [|base(42)|] [|{|][|}|] }"); } [Fact] public void InstanceConstructor_BaseInitializer_BlockBody() { // a sequence point for base constructor call TestSpan( @"class C { pub$$lic C() : [|base(42)|] { } }"); } [Fact] public void InstanceConstructor_BaseInitializer_ExpressionBody_All() { VerifyAllSpansInDeclaration<ConstructorDeclarationSyntax>( @"class C { [Attribute1, Attribute2][Attribute3]$$public C() : [|base(42)|] => [|x = 1|]; }"); } [Fact] public void InstanceConstructor_BaseInitializer_ExpressionBody1() { // a sequence point for base constructor call TestSpan( @"class C { pub$$lic C() : [|base(42)|] => F(); }"); } [Fact] public void InstanceConstructor_BaseInitializer_ExpressionBody2() { // a sequence point for base constructor call TestSpan( @"class C { public C() : [|base(42)|] $$=> F(); }"); } [Fact] public void InstanceConstructor_BaseInitializer_ExpressionBody3() { // a sequence point for base constructor call TestSpan( @"class C { public C() : base(42) =$$> [|F()|]; }"); } [Fact] public void InstanceConstructor_BaseInitializer_ExpressionBody4() { // a sequence point for base constructor call TestSpan( @"class C { public C() : base(42) => [|$$F()|]; }"); } [Fact] public void InstanceConstructor_ThisInitializer() { // a sequence point for this constructor call TestSpan( @"class C { pub$$lic C() : [|this(42)|] { } }"); } [Fact] public void StaticConstructor_BlockBody_All() { VerifyAllSpansInDeclaration<ConstructorDeclarationSyntax>( @"class C { [Attribute1, Attribute2][Attribute3]$$static public C() [|{|] [|}|] }"); } [Fact] public void StaticConstructor_BlockBody() { TestSpan( @"class C { $$static C() [|{|] } }"); } [Fact] public void StaticConstructor_ExpressionBody_All() { VerifyAllSpansInDeclaration<ConstructorDeclarationSyntax>( @"class C { [Attribute1, Attribute2][Attribute3]$$static public C() => [|x = 1|]; }"); } [Fact] public void StaticConstructor_ExpressionBody() { TestSpan( @"class C { static C() => [|$$F()|]; }"); } [Fact] public void InstanceConstructorInitializer() { // a sequence point for this constructor call TestSpan( @"class Derived : Base { public Derived() : [|this($$42)|] { } }"); } [WorkItem(543968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543968")] [Fact] public void ConstructorInitializer() { // a sequence point for base constructor call TestSpan( @"class Derived : Base { public Derived() : [|base($$42)|] { } } "); } [Fact] public void OnStaticConstructor() { TestSpan( @"class C { st$$atic C() [|{|] } }"); } #endregion [Fact] public void OnDestructor() { TestSpan( @"class C { ~C$$() [|{|] } }"); } [Fact] public void OnOperator() { TestSpan( @"class C { public static int op$$erator+(C c1, C c2) [|{|] } }"); } [Fact] public void OnOperatorWithExpressionBody1() { TestSpan( @"class C { public static int op$$erator+(C c1, C c2) => [|c1|]; }"); } [Fact] public void OnOperatorWithExpressionBody2() { TestSpan( @"class C { public static int operator+(C c1, C c2) =>$$ [|c1|]; }"); } [Fact] public void OnOperatorWithExpressionBody3() { TestSpan( @"class C { public static int operator+(C c1, C c2) => [|c1|]; $$ }"); } [Fact] public void OnOperatorWithExpressionBody4() { TestSpan( @"class C { public static int operator+(C c1, C c2) => [|c$$1|]; }"); } [Fact] public void OnConversionOperator() { TestSpan( @"class C { public static op$$erator DateTime(C c1) [|{|] } }"); } [Fact] public void OnConversionOperatorWithExpressionBody1() { TestSpan( @"class C { public static op$$erator DateTime(C c1) => [|DataTime.Now|]; }"); } [Fact] public void OnConversionOperatorWithExpressionBody2() { TestSpan( @"class C { public static operator DateTime(C c1) =>$$ [|DataTime.Now|]; }"); } [Fact] public void OnConversionOperatorWithExpressionBody3() { TestSpan( @"class C { public static operator DateTime(C c1) => [|DataTime.Now|];$$ }"); } [Fact] public void OnConversionOperatorWithExpressionBody4() { TestSpan( @"class C { public static operator DateTime(C c1) => [|DataTime$$.Now|]; }"); } [WorkItem(3557, "DevDiv_Projects/Roslyn")] [Fact] public void InFrontOfAttribute() { TestSpan( @"class C { $$ [method: Obsolete] void Goo() [|{|] } }"); } [WorkItem(538058, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538058")] [Fact] public void InInactivePPRegion() { TestLine( @" #if blahblah $$gooby #endif"); } [WorkItem(538777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538777")] [Fact] public void WithIncompleteDeclaration() { TestMissing( @" clas C { void Goo() { $$ int } }"); } [WorkItem(937290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/937290")] [Fact] public void OnGetter() { TestSpan( @"class C { public int $$Id { [|get;|] set; } }"); TestSpan( @"class C { public int Id { [|g$$et;|] set; } }"); TestSpan( @"class C { public int Id { g$$et [|{|] return 42; } set {} } }"); TestSpan( @"class C { public int$$ Id { get [|{|] return 42; } set {} } }"); } [WorkItem(937290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/937290")] [Fact] public void OnSetter() { TestSpan( @"class C { public int Id { get; [|se$$t;|] } }"); TestSpan( @"class C { public int Id { get; [|set;|] $$ } }"); TestSpan( @"class C { public int $$Id { [|set;|] get; } }"); TestSpan( @"class C { public int Id { get { return 42; } s$$et [|{|] } } }"); TestSpan( @"class C { public int Id { get { return 42; } set { [|}|] $$} }"); } [Fact] public void WhenClause_1() { TestSpan( @"class C { string s; bool b; void Goo() { switch (s) { $$ case string s [|when b|]: break; } } }"); } [Fact] public void WhenClause_2() { TestSpan( @"class C { string s; bool b; void Goo() { switch (s) { case string s [|whe$$n b|]: break; } } }"); } [Fact] public void WhenClause_3() { TestSpan( @"class C { string s; bool b; void Goo() { switch (s) { case string s [|when b|]:$$ break; } } }"); } [Fact] public void PatternSwitchCase_1() { TestSpan( @"class C { string s; bool b; void Goo() { switch (s) { $$ case string s: default: [|break;|] } } }"); } [Fact] public void PatternSwitchCase_2() { TestSpan( @"class C { string s; bool b; void Goo() { switch (s) { $$case string s: default: [|break;|] } } }"); } [Fact] public void PatternSwitchCase_3() { TestSpan( @"class C { string s; bool b; void Goo() { switch (s) { case string s:$$ default: [|break;|] } } }"); } [Fact] public void DeconstructionDeclarationStatement_1() { TestSpan( @"class C { void Goo() { $$ [|var (x, y) = (1, 2);|] } }"); } [Fact] public void DeconstructionDeclarationStatement_2() { TestSpan( @"class C { void Goo() { [|var (x, y) = $$(1, 2);|] } }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void OnAccessorExpressionBody1() { TestSpan( @"class C { public int Id { get => [|12$$3|]; } }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void OnAccessorExpressionBody2() { TestSpan( @"class C { public int Id { get $$=> [|123|]; } }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void OnAccessorExpressionBody3() { TestSpan( @"class C { $$public int Id { get => [|123|]; } }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void OnAccessorExpressionBody4() { TestSpan( @"class C { public int Id { get => [|123|]; $$ } }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void OnAccessorExpressionBody5() { TestSpan( @"class C { $$ public event Action Goo { add => [|123|]; remove => 456; } }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void OnAccessorExpressionBody6() { TestSpan( @"class C { public event Action Goo { add => [|123|];$$ remove => 456; } }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void OnAccessorExpressionBody7() { TestSpan( @"class C { public event Action Goo { add => 123; $$remove => [|456|]; } }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void OnAccessorExpressionBody8() { TestSpan( @"class C { public event Action Goo { add => 123; remove => [|456|]; }$$ }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void OnDtorExpressionBody1() { TestSpan( @"class C { $$ public ~C() => [|x = 1|]; }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void OnDtorExpressionBody2() { TestSpan( @"class C { public ~C() => $$[|x = 1|]; }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void OnDtorExpressionBody3() { TestSpan( @"class C { public ~C() => [|x =$$ 1|]; }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void OnDtorExpressionBody4() { TestSpan( @"class C { public ~C() => [|x = 1|]$$; }"); } [Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] public void OnDtorExpressionBody5() { TestSpan( @"class C { public ~C() => [|x = 1|];$$ }"); } [Fact, WorkItem(14437, "https://github.com/dotnet/roslyn/issues/14437")] public void OnLocalFunctionDecl_1() { TestSpan( @"class C { static void M() { $$ int Local(object[] a) [|{|] return a.Length; } } }"); } [Fact, WorkItem(14437, "https://github.com/dotnet/roslyn/issues/14437")] public void OnLocalFunctionDecl_2() { TestSpan( @"class C { static void M() { int Local(object[] a)$$ [|{|] return a.Length; } } }"); } [Fact, WorkItem(14437, "https://github.com/dotnet/roslyn/issues/14437")] public void OnLocalFunctionDecl_3() { TestSpan( @"class C { static void M() { int Local(object[] a) $$ [|{|] return a.Length; } } }"); } [Fact, WorkItem(14437, "https://github.com/dotnet/roslyn/issues/14437")] public void OnLocalFunctionDecl_4() { TestSpan( @"class C { static void M() { $$ int Local(object[] a) => [|a.Length|]; } }"); } [Fact, WorkItem(14437, "https://github.com/dotnet/roslyn/issues/14437")] public void OnLocalFunctionDecl_5() { TestSpan( @"class C { static void M() { int Local(object$$[] a) => [|a.Length|]; } }"); } [Fact, WorkItem(14437, "https://github.com/dotnet/roslyn/issues/14437")] public void OnLocalFunctionDecl_6() { TestSpan( @"class C { static void M() { int Local(object[] a) => [|a.Length|];$$ } }"); } [Fact, WorkItem(98990, "https://developercommunity.visualstudio.com/content/problem/98990/cant-set-breakpoint.html")] public void IncompleteExpressionStatement() { TestSpan( @"class C { void Goo() { [|$$aaa|] } }"); } #region Top Level Statements [Fact] public void TopLevelStatements() { VerifyAllSpansInDeclaration<CompilationUnitSyntax>(@" $$[|int d = 5;|] [|int a = 1|], [|b = 2|], [|c = 3|]; for ([|int i = 0|], [|j = 1|], [|k = 2|]; [|i < 10|]; [|i++|], [|j++|], [|k--|]) [|while (b > 0)|] [|{|] [|if (c < b)|] try [|{|] [|System.Console.WriteLine(a);|] [|}|] [|catch (Exception e)|] [|{|] [|System.Console.WriteLine(e);|] [|}|] finally [|{|] [|}|] else [|if (b < 10)|] [|System.Console.WriteLine(b);|] else [|System.Console.WriteLine(c);|] [|}|] "); } #endregion } }
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/TrueKeywordRecommender.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.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class TrueKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public TrueKeywordRecommender() : base(SyntaxKind.TrueKeyword, isValidInPreprocessorContext: true) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsAnyExpressionContext || context.IsPreProcessorExpressionContext || context.IsStatementContext || context.IsGlobalStatementContext || context.TargetToken.IsUnaryOperatorContext(); } } }
// Licensed to the .NET Foundation under one or more 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.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class TrueKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public TrueKeywordRecommender() : base(SyntaxKind.TrueKeyword, isValidInPreprocessorContext: true) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsAnyExpressionContext || context.IsPreProcessorExpressionContext || context.IsStatementContext || context.IsGlobalStatementContext || context.TargetToken.IsUnaryOperatorContext(); } } }
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/Compilers/CSharp/Portable/Declarations/RootSingleNamespaceDeclaration.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; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class RootSingleNamespaceDeclaration : SingleNamespaceDeclaration { private readonly ImmutableArray<ReferenceDirective> _referenceDirectives; private readonly bool _hasAssemblyAttributes; private readonly bool _hasGlobalUsings; private readonly bool _hasUsings; private readonly bool _hasExternAliases; public RootSingleNamespaceDeclaration( bool hasGlobalUsings, bool hasUsings, bool hasExternAliases, SyntaxReference treeNode, ImmutableArray<SingleNamespaceOrTypeDeclaration> children, ImmutableArray<ReferenceDirective> referenceDirectives, bool hasAssemblyAttributes, ImmutableArray<Diagnostic> diagnostics) : base(string.Empty, treeNode, nameLocation: new SourceLocation(treeNode), children: children, diagnostics: diagnostics) { Debug.Assert(!referenceDirectives.IsDefault); _referenceDirectives = referenceDirectives; _hasAssemblyAttributes = hasAssemblyAttributes; _hasGlobalUsings = hasGlobalUsings; _hasUsings = hasUsings; _hasExternAliases = hasExternAliases; } public ImmutableArray<ReferenceDirective> ReferenceDirectives { get { return _referenceDirectives; } } public bool HasAssemblyAttributes { get { return _hasAssemblyAttributes; } } public override bool HasGlobalUsings { get { return _hasGlobalUsings; } } public override bool HasUsings { get { return _hasUsings; } } public override bool HasExternAliases { get { return _hasExternAliases; } } } }
// Licensed to the .NET Foundation under one or more 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; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class RootSingleNamespaceDeclaration : SingleNamespaceDeclaration { private readonly ImmutableArray<ReferenceDirective> _referenceDirectives; private readonly bool _hasAssemblyAttributes; private readonly bool _hasGlobalUsings; private readonly bool _hasUsings; private readonly bool _hasExternAliases; public RootSingleNamespaceDeclaration( bool hasGlobalUsings, bool hasUsings, bool hasExternAliases, SyntaxReference treeNode, ImmutableArray<SingleNamespaceOrTypeDeclaration> children, ImmutableArray<ReferenceDirective> referenceDirectives, bool hasAssemblyAttributes, ImmutableArray<Diagnostic> diagnostics) : base(string.Empty, treeNode, nameLocation: new SourceLocation(treeNode), children: children, diagnostics: diagnostics) { Debug.Assert(!referenceDirectives.IsDefault); _referenceDirectives = referenceDirectives; _hasAssemblyAttributes = hasAssemblyAttributes; _hasGlobalUsings = hasGlobalUsings; _hasUsings = hasUsings; _hasExternAliases = hasExternAliases; } public ImmutableArray<ReferenceDirective> ReferenceDirectives { get { return _referenceDirectives; } } public bool HasAssemblyAttributes { get { return _hasAssemblyAttributes; } } public override bool HasGlobalUsings { get { return _hasGlobalUsings; } } public override bool HasUsings { get { return _hasUsings; } } public override bool HasExternAliases { get { return _hasExternAliases; } } } }
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/Compilers/Test/Core/Traits/Traits.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.Test.Utilities { public static class Traits { public const string Editor = nameof(Editor); public static class Editors { public const string KeyProcessors = nameof(KeyProcessors); public const string KeyProcessorProviders = nameof(KeyProcessorProviders); public const string Preview = nameof(Preview); public const string LanguageServerProtocol = nameof(LanguageServerProtocol); } public const string Feature = nameof(Feature); public static class Features { public const string AddAwait = "Refactoring.AddAwait"; public const string AddMissingImports = "Refactoring.AddMissingImports"; public const string AddMissingReference = nameof(AddMissingReference); public const string AddMissingTokens = nameof(AddMissingTokens); public const string Adornments = nameof(Adornments); public const string AsyncLazy = nameof(AsyncLazy); public const string AutomaticCompletion = nameof(AutomaticCompletion); public const string AutomaticEndConstructCorrection = nameof(AutomaticEndConstructCorrection); public const string BlockCommentEditing = nameof(BlockCommentEditing); public const string BraceHighlighting = nameof(BraceHighlighting); public const string BraceMatching = nameof(BraceMatching); public const string Build = nameof(Build); public const string CallHierarchy = nameof(CallHierarchy); public const string CaseCorrection = nameof(CaseCorrection); public const string ChangeSignature = nameof(ChangeSignature); public const string ClassView = nameof(ClassView); public const string Classification = nameof(Classification); public const string CodeActionsAddAccessibilityModifiers = "CodeActions.AddAccessibilityModifiers"; public const string CodeActionsAddAnonymousTypeMemberName = "CodeActions.AddAnonymousTypeMemberName"; public const string CodeActionsAddAwait = "CodeActions.AddAwait"; public const string CodeActionsAddBraces = "CodeActions.AddBraces"; public const string CodeActionsAddConstructorParametersFromMembers = "CodeActions.AddConstructorParametersFromMembers"; public const string CodeActionsAddDebuggerDisplay = "CodeActions.AddDebuggerDisplay"; public const string CodeActionsAddDocCommentNodes = "CodeActions.AddDocCommentParamNodes"; public const string CodeActionsAddExplicitCast = "CodeActions.AddExplicitCast"; public const string CodeActionsAddFileBanner = "CodeActions.AddFileBanner"; public const string CodeActionsAddImport = "CodeActions.AddImport"; public const string CodeActionsAddMissingReference = "CodeActions.AddMissingReference"; public const string CodeActionsAddNew = "CodeActions.AddNew"; public const string CodeActionsRemoveNewModifier = "CodeActions.RemoveNewModifier"; public const string CodeActionsAddObsoleteAttribute = "CodeActions.AddObsoleteAttribute"; public const string CodeActionsAddOverload = "CodeActions.AddOverloads"; public const string CodeActionsAddParameter = "CodeActions.AddParameter"; public const string CodeActionsAddParenthesesAroundConditionalExpressionInInterpolatedString = "CodeActions.AddParenthesesAroundConditionalExpressionInInterpolatedString"; public const string CodeActionsAddRequiredParentheses = "CodeActions.AddRequiredParentheses"; public const string CodeActionsAddShadows = "CodeActions.AddShadows"; public const string CodeActionsMakeMemberStatic = "CodeActions.MakeMemberStatic"; public const string CodeActionsAliasAmbiguousType = "CodeActions.AliasAmbiguousType"; public const string CodeActionsAssignOutParameters = "CodeActions.AssignOutParameters"; public const string CodeActionsChangeToAsync = "CodeActions.ChangeToAsync"; public const string CodeActionsChangeToIEnumerable = "CodeActions.ChangeToIEnumerable"; public const string CodeActionsChangeToYield = "CodeActions.ChangeToYield"; public const string CodeActionsConfiguration = "CodeActions.Configuration"; public const string CodeActionsConvertAnonymousTypeToClass = "CodeActions.ConvertAnonymousTypeToClass"; public const string CodeActionsConvertAnonymousTypeToTuple = "CodeActions.ConvertAnonymousTypeToTuple"; public const string CodeActionsConvertBetweenRegularAndVerbatimString = "CodeActions.ConvertBetweenRegularAndVerbatimString"; public const string CodeActionsConvertForEachToFor = "CodeActions.ConvertForEachToFor"; public const string CodeActionsConvertForEachToQuery = "CodeActions.ConvertForEachToQuery"; public const string CodeActionsConvertForToForEach = "CodeActions.ConvertForToForEach"; public const string CodeActionsConvertIfToSwitch = "CodeActions.ConvertIfToSwitch"; public const string CodeActionsConvertLocalFunctionToMethod = "CodeActions.ConvertLocalFunctionToMethod"; public const string CodeActionsConvertNumericLiteral = "CodeActions.ConvertNumericLiteral"; public const string CodeActionsConvertQueryToForEach = "CodeActions.ConvertQueryToForEach"; public const string CodeActionsConvertSwitchStatementToExpression = "CodeActions.ConvertSwitchStatementToExpression"; public const string CodeActionsConvertToInterpolatedString = "CodeActions.ConvertToInterpolatedString"; public const string CodeActionsConvertToIterator = "CodeActions.ConvertToIterator"; public const string CodeActionsConvertTupleToStruct = "CodeActions.ConvertTupleToStruct"; public const string CodeActionsCorrectExitContinue = "CodeActions.CorrectExitContinue"; public const string CodeActionsCorrectFunctionReturnType = "CodeActions.CorrectFunctionReturnType"; public const string CodeActionsCorrectNextControlVariable = "CodeActions.CorrectNextControlVariable"; public const string CodeActionsDeclareAsNullable = "CodeActions.DeclareAsNullable"; public const string CodeActionsExtractInterface = "CodeActions.ExtractInterface"; public const string CodeActionsExtractLocalFunction = "CodeActions.ExtractLocalFunction"; public const string CodeActionsExtractMethod = "CodeActions.ExtractMethod"; public const string CodeActionsFixAllOccurrences = "CodeActions.FixAllOccurrences"; public const string CodeActionsFixReturnType = "CodeActions.FixReturnType"; public const string CodeActionsFullyQualify = "CodeActions.FullyQualify"; public const string CodeActionsGenerateComparisonOperators = "CodeActions.GenerateComparisonOperators"; public const string CodeActionsGenerateConstructor = "CodeActions.GenerateConstructor"; public const string CodeActionsGenerateConstructorFromMembers = "CodeActions.GenerateConstructorFromMembers"; public const string CodeActionsGenerateDefaultConstructors = "CodeActions.GenerateDefaultConstructors"; public const string CodeActionsGenerateEndConstruct = "CodeActions.GenerateEndConstruct"; public const string CodeActionsGenerateEnumMember = "CodeActions.GenerateEnumMember"; public const string CodeActionsGenerateEqualsAndGetHashCode = "CodeActions.GenerateEqualsAndGetHashCodeFromMembers"; public const string CodeActionsGenerateEvent = "CodeActions.GenerateEvent"; public const string CodeActionsGenerateLocal = "CodeActions.GenerateLocal"; public const string CodeActionsGenerateMethod = "CodeActions.GenerateMethod"; public const string CodeActionsGenerateOverrides = "CodeActions.GenerateOverrides"; public const string CodeActionsGenerateType = "CodeActions.GenerateType"; public const string CodeActionsGenerateVariable = "CodeActions.GenerateVariable"; public const string CodeActionsImplementAbstractClass = "CodeActions.ImplementAbstractClass"; public const string CodeActionsImplementInterface = "CodeActions.ImplementInterface"; public const string CodeActionsInitializeParameter = "CodeActions.InitializeParameter"; public const string CodeActionsInlineMethod = "CodeActions.InlineMethod"; public const string CodeActionsInlineDeclaration = "CodeActions.InlineDeclaration"; public const string CodeActionsInlineTemporary = "CodeActions.InlineTemporary"; public const string CodeActionsInlineTypeCheck = "CodeActions.InlineTypeCheck"; public const string CodeActionsInsertBraces = "CodeActions.InsertBraces"; public const string CodeActionsInsertMissingTokens = "CodeActions.InsertMissingTokens"; public const string CodeActionsIntroduceLocalForExpression = "CodeActions.IntroduceLocalForExpression"; public const string CodeActionsIntroduceParameter = "CodeActions.IntroduceParameter"; public const string CodeActionsIntroduceUsingStatement = "CodeActions.IntroduceUsingStatement"; public const string CodeActionsIntroduceVariable = "CodeActions.IntroduceVariable"; public const string CodeActionsInvertConditional = "CodeActions.InvertConditional"; public const string CodeActionsInvertIf = "CodeActions.InvertIf"; public const string CodeActionsInvertLogical = "CodeActions.InvertLogical"; public const string CodeActionsInvokeDelegateWithConditionalAccess = "CodeActions.InvokeDelegateWithConditionalAccess"; public const string CodeActionsLambdaSimplifier = "CodeActions.LambdaSimplifier"; public const string CodeActionsMakeFieldReadonly = "CodeActions.MakeFieldReadonly"; public const string CodeActionsMakeLocalFunctionStatic = "CodeActions.MakeLocalFunctionStatic"; public const string CodeActionsMakeMethodAsynchronous = "CodeActions.MakeMethodAsynchronous"; public const string CodeActionsMakeMethodSynchronous = "CodeActions.MakeMethodSynchronous"; public const string CodeActionsMakeRefStruct = "CodeActions.MakeRefStruct"; public const string CodeActionsMakeStatementAsynchronous = "CodeActions.MakeStatementAsynchronous"; public const string CodeActionsMakeStructFieldsWritable = "CodeActions.MakeStructFieldsWritable"; public const string CodeActionsMakeTypeAbstract = "CodeActions.MakeTypeAbstract"; public const string CodeActionsMergeConsecutiveIfStatements = "CodeActions.MergeConsecutiveIfStatements"; public const string CodeActionsMergeNestedIfStatements = "CodeActions.MergeNestedIfStatements"; public const string CodeActionsMoveDeclarationNearReference = "CodeActions.MoveDeclarationNearReference"; public const string CodeActionsMoveToNamespace = nameof(CodeActionsMoveToNamespace); public const string CodeActionsMoveToTopOfFile = "CodeActions.MoveToTopOfFile"; public const string CodeActionsMoveType = "CodeActions.MoveType"; public const string CodeActionsNameTupleElement = "CodeActions.NameTupleElement"; public const string CodeActionsOrderModifiers = "CodeActions.OrderModifiers"; public const string CodeActionsPopulateSwitch = "CodeActions.PopulateSwitch"; public const string CodeActionsPullMemberUp = "CodeActions.PullMemberUp"; public const string CodeActionsQualifyMemberAccess = "CodeActions.QualifyMemberAccess"; public const string CodeActionsRemoveAsyncModifier = "CodeActions.RemoveAsyncModifier"; public const string CodeActionsRemoveByVal = "CodeActions.RemoveByVal"; public const string CodeActionsRemoveDocCommentNode = "CodeActions.RemoveDocCommentNode"; public const string CodeActionsRemoveInKeyword = "CodeActions.RemoveInKeyword"; public const string CodeActionsRemoveUnnecessarySuppressions = "CodeActions.RemoveUnnecessarySuppressions"; public const string CodeActionsRemoveUnnecessaryCast = "CodeActions.RemoveUnnecessaryCast"; public const string CodeActionsRemoveUnnecessaryDiscardDesignation = "CodeActions.RemoveUnnecessaryDiscardDesignation"; public const string CodeActionsRemoveUnnecessaryImports = "CodeActions.RemoveUnnecessaryImports"; public const string CodeActionsRemoveUnnecessaryParentheses = "CodeActions.RemoveUnnecessaryParentheses"; public const string CodeActionsRemoveUnreachableCode = "CodeActions.RemoveUnreachableCode"; public const string CodeActionsRemoveUnusedLocalFunction = "CodeActions.RemoveUnusedLocalFunction"; public const string CodeActionsRemoveUnusedMembers = "CodeActions.RemoveUnusedMembers"; public const string CodeActionsRemoveUnusedParameters = "CodeActions.RemoveUnusedParameters"; public const string CodeActionsRemoveUnusedValues = "CodeActions.RemoveUnusedValues"; public const string CodeActionsRemoveUnusedVariable = "CodeActions.RemoveUnusedVariable"; public const string CodeActionsReplaceDefaultLiteral = "CodeActions.ReplaceDefaultLiteral"; public const string CodeActionsReplaceDocCommentTextWithTag = "CodeActions.ReplaceDocCommentTextWithTag"; public const string CodeActionsReplaceMethodWithProperty = "CodeActions.ReplaceMethodWithProperty"; public const string CodeActionsReplacePropertyWithMethods = "CodeActions.ReplacePropertyWithMethods"; public const string CodeActionsResolveConflictMarker = "CodeActions.ResolveConflictMarker"; public const string CodeActionsReverseForStatement = "CodeActions.ReverseForStatement"; public const string CodeActionsSimplifyConditional = "CodeActions.SimplifyConditional"; public const string CodeActionsSimplifyInterpolation = "CodeActions.SimplifyInterpolation"; public const string CodeActionsSimplifyLinqExpression = "CodeActions.SimplifyLinqExpression"; public const string CodeActionsSimplifyThisOrMe = "CodeActions.SimplifyThisOrMe"; public const string CodeActionsSimplifyTypeNames = "CodeActions.SimplifyTypeNames"; public const string CodeActionsSpellcheck = "CodeActions.Spellcheck"; public const string CodeActionsSplitIntoConsecutiveIfStatements = "CodeActions.SplitIntoConsecutiveIfStatements"; public const string CodeActionsSplitIntoNestedIfStatements = "CodeActions.SplitIntoNestedIfStatements"; public const string CodeActionsSuppression = "CodeActions.Suppression"; public const string CodeActionsSyncNamespace = "CodeActions.SyncNamespace"; public const string CodeActionsUnsealClass = "CodeActions.UnsealClass"; public const string CodeActionsUpdateLegacySuppressions = "CodeActions.UpdateLegacySuppressions"; public const string CodeActionsUpdateProjectToAllowUnsafe = "CodeActions.UpdateProjectToAllowUnsafe"; public const string CodeActionsUpgradeProject = "CodeActions.UpgradeProject"; public const string CodeActionsUseAutoProperty = "CodeActions.UseAutoProperty"; public const string CodeActionsUseCoalesceExpression = "CodeActions.UseCoalesceExpression"; public const string CodeActionsUseCollectionInitializer = "CodeActions.UseCollectionInitializer"; public const string CodeActionsUseCompoundAssignment = "CodeActions.UseCompoundAssignment"; public const string CodeActionsUseConditionalExpression = "CodeActions.UseConditionalExpression"; public const string CodeActionsUseDeconstruction = "CodeActions.UseDeconstruction"; public const string CodeActionsUseDefaultLiteral = "CodeActions.UseDefaultLiteral"; public const string CodeActionsUseExplicitTupleName = "CodeActions.UseExplicitTupleName"; public const string CodeActionsUseExplicitType = "CodeActions.UseExplicitType"; public const string CodeActionsUseExplicitTypeForConst = "CodeActions.UseExplicitTypeForConst"; public const string CodeActionsUseExpressionBody = "CodeActions.UseExpressionBody"; public const string CodeActionsUseFrameworkType = "CodeActions.UseFrameworkType"; public const string CodeActionsUseImplicitObjectCreation = "CodeActions.UseImplicitObjectCreation"; public const string CodeActionsUseImplicitType = "CodeActions.UseImplicitType"; public const string CodeActionsUseIndexOperator = "CodeActions.UseIndexOperator"; public const string CodeActionsUseInferredMemberName = "CodeActions.UseInferredMemberName"; public const string CodeActionsUseInterpolatedVerbatimString = "CodeActions.UseInterpolatedVerbatimString"; public const string CodeActionsUseIsNotExpression = "CodeActions.UseIsNotExpression"; public const string CodeActionsUseIsNullCheck = "CodeActions.UseIsNullCheck"; public const string CodeActionsUseLocalFunction = "CodeActions.UseLocalFunction"; public const string CodeActionsUseNamedArguments = "CodeActions.UseNamedArguments"; public const string CodeActionsUseNotPattern = "CodeActions.UseNotPattern"; public const string CodeActionsUsePatternCombinators = "CodeActions.UsePatternCombinators"; public const string CodeActionsUseRecursivePatterns = "CodeActions.UseRecursivePatterns"; public const string CodeActionsUseNullPropagation = "CodeActions.UseNullPropagation"; public const string CodeActionsUseObjectInitializer = "CodeActions.UseObjectInitializer"; public const string CodeActionsUseRangeOperator = "CodeActions.UseRangeOperator"; public const string CodeActionsUseSimpleUsingStatement = "CodeActions.UseSimpleUsingStatement"; public const string CodeActionsUseSystemHashCode = "CodeActions.UseSystemHashCode"; public const string CodeActionsUseThrowExpression = "CodeActions.UseThrowExpression"; public const string CodeActionsWrapping = "CodeActions.Wrapping"; public const string CodeCleanup = nameof(CodeCleanup); public const string CodeGeneration = nameof(CodeGeneration); public const string CodeGenerationSortDeclarations = "CodeGeneration.SortDeclarations"; public const string CodeLens = nameof(CodeLens); public const string CodeModel = nameof(CodeModel); public const string CodeModelEvents = "CodeModel.Events"; public const string CodeModelMethodXml = "CodeModel.MethodXml"; public const string CommentSelection = nameof(CommentSelection); public const string CompleteStatement = nameof(CompleteStatement); public const string Completion = nameof(Completion); public const string ConvertAutoPropertyToFullProperty = nameof(ConvertAutoPropertyToFullProperty); public const string ConvertCast = nameof(ConvertCast); public const string ConvertTypeOfToNameOf = nameof(ConvertTypeOfToNameOf); public const string DebuggingBreakpoints = "Debugging.Breakpoints"; public const string DebuggingDataTips = "Debugging.DataTips"; public const string DebuggingEditAndContinue = "Debugging.EditAndContinue"; public const string DebuggingIntelliSense = "Debugging.IntelliSense"; public const string DebuggingLocationName = "Debugging.LocationName"; public const string DebuggingNameResolver = "Debugging.NameResolver"; public const string DebuggingProximityExpressions = "Debugging.ProximityExpressions"; public const string DecompiledSource = nameof(DecompiledSource); public const string Diagnostics = nameof(Diagnostics); public const string DisposeAnalysis = nameof(DisposeAnalysis); public const string DocCommentFormatting = nameof(DocCommentFormatting); public const string DocumentationComments = nameof(DocumentationComments); public const string EditorConfig = nameof(EditorConfig); public const string EditorConfigUI = nameof(EditorConfigUI); public const string EncapsulateField = nameof(EncapsulateField); public const string EndConstructGeneration = nameof(EndConstructGeneration); public const string ErrorList = nameof(ErrorList); public const string ErrorSquiggles = nameof(ErrorSquiggles); public const string EventHookup = nameof(EventHookup); public const string Expansion = nameof(Expansion); public const string ExtractInterface = "Refactoring.ExtractInterface"; public const string ExtractMethod = "Refactoring.ExtractMethod"; public const string F1Help = nameof(F1Help); public const string FindReferences = nameof(FindReferences); public const string FixIncorrectTokens = nameof(FixIncorrectTokens); public const string FixInterpolatedVerbatimString = nameof(FixInterpolatedVerbatimString); public const string Formatting = nameof(Formatting); public const string GoToAdjacentMember = nameof(GoToAdjacentMember); public const string GoToBase = nameof(GoToBase); public const string GoToDefinition = nameof(GoToDefinition); public const string GoToImplementation = nameof(GoToImplementation); public const string InheritanceMargin = nameof(InheritanceMargin); public const string InlineHints = nameof(InlineHints); public const string Interactive = nameof(Interactive); public const string InteractiveHost = nameof(InteractiveHost); public const string KeywordHighlighting = nameof(KeywordHighlighting); public const string KeywordRecommending = nameof(KeywordRecommending); public const string LineCommit = nameof(LineCommit); public const string LineSeparators = nameof(LineSeparators); public const string LinkedFileDiffMerging = nameof(LinkedFileDiffMerging); public const string MSBuildWorkspace = nameof(MSBuildWorkspace); public const string MetadataAsSource = nameof(MetadataAsSource); public const string MoveToNamespace = nameof(MoveToNamespace); public const string NamingStyle = nameof(NamingStyle); public const string NavigableSymbols = nameof(NavigableSymbols); public const string NavigateTo = nameof(NavigateTo); public const string NavigationBar = nameof(NavigationBar); public const string NetCore = nameof(NetCore); public const string NormalizeModifiersOrOperators = nameof(NormalizeModifiersOrOperators); public const string ObjectBrowser = nameof(ObjectBrowser); public const string Options = nameof(Options); public const string Organizing = nameof(Organizing); public const string Outlining = nameof(Outlining); public const string Packaging = nameof(Packaging); public const string PasteTracking = nameof(PasteTracking); public const string Peek = nameof(Peek); public const string Progression = nameof(Progression); public const string ProjectSystemShims = nameof(ProjectSystemShims); public const string SarifErrorLogging = nameof(SarifErrorLogging); public const string QuickInfo = nameof(QuickInfo); public const string RQName = nameof(RQName); public const string ReduceTokens = nameof(ReduceTokens); public const string ReferenceHighlighting = nameof(ReferenceHighlighting); public const string RemoteHost = nameof(RemoteHost); public const string RemoveUnnecessaryLineContinuation = nameof(RemoveUnnecessaryLineContinuation); public const string Rename = nameof(Rename); public const string RenameTracking = nameof(RenameTracking); public const string SignatureHelp = nameof(SignatureHelp); public const string Simplification = nameof(Simplification); public const string SmartIndent = nameof(SmartIndent); public const string SmartTokenFormatting = nameof(SmartTokenFormatting); public const string Snippets = nameof(Snippets); public const string SourceGenerators = nameof(SourceGenerators); public const string SplitComment = nameof(SplitComment); public const string SplitStringLiteral = nameof(SplitStringLiteral); public const string SuggestionTags = nameof(SuggestionTags); public const string SyncNamespaces = nameof(SyncNamespaces); public const string TargetTypedCompletion = nameof(TargetTypedCompletion); public const string TextStructureNavigator = nameof(TextStructureNavigator); public const string TodoComments = nameof(TodoComments); public const string ToggleBlockComment = nameof(ToggleBlockComment); public const string ToggleLineComment = nameof(ToggleLineComment); public const string TypeInferenceService = nameof(TypeInferenceService); public const string UnusedReferences = nameof(UnusedReferences); public const string ValidateFormatString = nameof(ValidateFormatString); public const string ValidateRegexString = nameof(ValidateRegexString); public const string Venus = nameof(Venus); public const string VsLanguageBlock = nameof(VsLanguageBlock); public const string VsNavInfo = nameof(VsNavInfo); public const string VsSearch = nameof(VsSearch); public const string WinForms = nameof(WinForms); public const string Workspace = nameof(Workspace); public const string XmlTagCompletion = nameof(XmlTagCompletion); } public const string Environment = nameof(Environment); public static class Environments { public const string VSProductInstall = nameof(VSProductInstall); } } }
// Licensed to the .NET Foundation under one or more 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.Test.Utilities { public static class Traits { public const string Editor = nameof(Editor); public static class Editors { public const string KeyProcessors = nameof(KeyProcessors); public const string KeyProcessorProviders = nameof(KeyProcessorProviders); public const string Preview = nameof(Preview); public const string LanguageServerProtocol = nameof(LanguageServerProtocol); } public const string Feature = nameof(Feature); public static class Features { public const string AddAwait = "Refactoring.AddAwait"; public const string AddMissingImports = "Refactoring.AddMissingImports"; public const string AddMissingReference = nameof(AddMissingReference); public const string AddMissingTokens = nameof(AddMissingTokens); public const string Adornments = nameof(Adornments); public const string AsyncLazy = nameof(AsyncLazy); public const string AutomaticCompletion = nameof(AutomaticCompletion); public const string AutomaticEndConstructCorrection = nameof(AutomaticEndConstructCorrection); public const string BlockCommentEditing = nameof(BlockCommentEditing); public const string BraceHighlighting = nameof(BraceHighlighting); public const string BraceMatching = nameof(BraceMatching); public const string Build = nameof(Build); public const string CallHierarchy = nameof(CallHierarchy); public const string CaseCorrection = nameof(CaseCorrection); public const string ChangeSignature = nameof(ChangeSignature); public const string ClassView = nameof(ClassView); public const string Classification = nameof(Classification); public const string CodeActionsAddAccessibilityModifiers = "CodeActions.AddAccessibilityModifiers"; public const string CodeActionsAddAnonymousTypeMemberName = "CodeActions.AddAnonymousTypeMemberName"; public const string CodeActionsAddAwait = "CodeActions.AddAwait"; public const string CodeActionsAddBraces = "CodeActions.AddBraces"; public const string CodeActionsAddConstructorParametersFromMembers = "CodeActions.AddConstructorParametersFromMembers"; public const string CodeActionsAddDebuggerDisplay = "CodeActions.AddDebuggerDisplay"; public const string CodeActionsAddDocCommentNodes = "CodeActions.AddDocCommentParamNodes"; public const string CodeActionsAddExplicitCast = "CodeActions.AddExplicitCast"; public const string CodeActionsAddFileBanner = "CodeActions.AddFileBanner"; public const string CodeActionsAddImport = "CodeActions.AddImport"; public const string CodeActionsAddMissingReference = "CodeActions.AddMissingReference"; public const string CodeActionsAddNew = "CodeActions.AddNew"; public const string CodeActionsRemoveNewModifier = "CodeActions.RemoveNewModifier"; public const string CodeActionsAddObsoleteAttribute = "CodeActions.AddObsoleteAttribute"; public const string CodeActionsAddOverload = "CodeActions.AddOverloads"; public const string CodeActionsAddParameter = "CodeActions.AddParameter"; public const string CodeActionsAddParenthesesAroundConditionalExpressionInInterpolatedString = "CodeActions.AddParenthesesAroundConditionalExpressionInInterpolatedString"; public const string CodeActionsAddRequiredParentheses = "CodeActions.AddRequiredParentheses"; public const string CodeActionsAddShadows = "CodeActions.AddShadows"; public const string CodeActionsMakeMemberStatic = "CodeActions.MakeMemberStatic"; public const string CodeActionsAliasAmbiguousType = "CodeActions.AliasAmbiguousType"; public const string CodeActionsAssignOutParameters = "CodeActions.AssignOutParameters"; public const string CodeActionsChangeToAsync = "CodeActions.ChangeToAsync"; public const string CodeActionsChangeToIEnumerable = "CodeActions.ChangeToIEnumerable"; public const string CodeActionsChangeToYield = "CodeActions.ChangeToYield"; public const string CodeActionsConfiguration = "CodeActions.Configuration"; public const string CodeActionsConvertAnonymousTypeToClass = "CodeActions.ConvertAnonymousTypeToClass"; public const string CodeActionsConvertAnonymousTypeToTuple = "CodeActions.ConvertAnonymousTypeToTuple"; public const string CodeActionsConvertBetweenRegularAndVerbatimString = "CodeActions.ConvertBetweenRegularAndVerbatimString"; public const string CodeActionsConvertForEachToFor = "CodeActions.ConvertForEachToFor"; public const string CodeActionsConvertForEachToQuery = "CodeActions.ConvertForEachToQuery"; public const string CodeActionsConvertForToForEach = "CodeActions.ConvertForToForEach"; public const string CodeActionsConvertIfToSwitch = "CodeActions.ConvertIfToSwitch"; public const string CodeActionsConvertLocalFunctionToMethod = "CodeActions.ConvertLocalFunctionToMethod"; public const string CodeActionsConvertNumericLiteral = "CodeActions.ConvertNumericLiteral"; public const string CodeActionsConvertQueryToForEach = "CodeActions.ConvertQueryToForEach"; public const string CodeActionsConvertSwitchStatementToExpression = "CodeActions.ConvertSwitchStatementToExpression"; public const string CodeActionsConvertToInterpolatedString = "CodeActions.ConvertToInterpolatedString"; public const string CodeActionsConvertToIterator = "CodeActions.ConvertToIterator"; public const string CodeActionsConvertTupleToStruct = "CodeActions.ConvertTupleToStruct"; public const string CodeActionsCorrectExitContinue = "CodeActions.CorrectExitContinue"; public const string CodeActionsCorrectFunctionReturnType = "CodeActions.CorrectFunctionReturnType"; public const string CodeActionsCorrectNextControlVariable = "CodeActions.CorrectNextControlVariable"; public const string CodeActionsDeclareAsNullable = "CodeActions.DeclareAsNullable"; public const string CodeActionsExtractInterface = "CodeActions.ExtractInterface"; public const string CodeActionsExtractLocalFunction = "CodeActions.ExtractLocalFunction"; public const string CodeActionsExtractMethod = "CodeActions.ExtractMethod"; public const string CodeActionsFixAllOccurrences = "CodeActions.FixAllOccurrences"; public const string CodeActionsFixReturnType = "CodeActions.FixReturnType"; public const string CodeActionsFullyQualify = "CodeActions.FullyQualify"; public const string CodeActionsGenerateComparisonOperators = "CodeActions.GenerateComparisonOperators"; public const string CodeActionsGenerateConstructor = "CodeActions.GenerateConstructor"; public const string CodeActionsGenerateConstructorFromMembers = "CodeActions.GenerateConstructorFromMembers"; public const string CodeActionsGenerateDefaultConstructors = "CodeActions.GenerateDefaultConstructors"; public const string CodeActionsGenerateEndConstruct = "CodeActions.GenerateEndConstruct"; public const string CodeActionsGenerateEnumMember = "CodeActions.GenerateEnumMember"; public const string CodeActionsGenerateEqualsAndGetHashCode = "CodeActions.GenerateEqualsAndGetHashCodeFromMembers"; public const string CodeActionsGenerateEvent = "CodeActions.GenerateEvent"; public const string CodeActionsGenerateLocal = "CodeActions.GenerateLocal"; public const string CodeActionsGenerateMethod = "CodeActions.GenerateMethod"; public const string CodeActionsGenerateOverrides = "CodeActions.GenerateOverrides"; public const string CodeActionsGenerateType = "CodeActions.GenerateType"; public const string CodeActionsGenerateVariable = "CodeActions.GenerateVariable"; public const string CodeActionsImplementAbstractClass = "CodeActions.ImplementAbstractClass"; public const string CodeActionsImplementInterface = "CodeActions.ImplementInterface"; public const string CodeActionsInitializeParameter = "CodeActions.InitializeParameter"; public const string CodeActionsInlineMethod = "CodeActions.InlineMethod"; public const string CodeActionsInlineDeclaration = "CodeActions.InlineDeclaration"; public const string CodeActionsInlineTemporary = "CodeActions.InlineTemporary"; public const string CodeActionsInlineTypeCheck = "CodeActions.InlineTypeCheck"; public const string CodeActionsInsertBraces = "CodeActions.InsertBraces"; public const string CodeActionsInsertMissingTokens = "CodeActions.InsertMissingTokens"; public const string CodeActionsIntroduceLocalForExpression = "CodeActions.IntroduceLocalForExpression"; public const string CodeActionsIntroduceParameter = "CodeActions.IntroduceParameter"; public const string CodeActionsIntroduceUsingStatement = "CodeActions.IntroduceUsingStatement"; public const string CodeActionsIntroduceVariable = "CodeActions.IntroduceVariable"; public const string CodeActionsInvertConditional = "CodeActions.InvertConditional"; public const string CodeActionsInvertIf = "CodeActions.InvertIf"; public const string CodeActionsInvertLogical = "CodeActions.InvertLogical"; public const string CodeActionsInvokeDelegateWithConditionalAccess = "CodeActions.InvokeDelegateWithConditionalAccess"; public const string CodeActionsLambdaSimplifier = "CodeActions.LambdaSimplifier"; public const string CodeActionsMakeFieldReadonly = "CodeActions.MakeFieldReadonly"; public const string CodeActionsMakeLocalFunctionStatic = "CodeActions.MakeLocalFunctionStatic"; public const string CodeActionsMakeMethodAsynchronous = "CodeActions.MakeMethodAsynchronous"; public const string CodeActionsMakeMethodSynchronous = "CodeActions.MakeMethodSynchronous"; public const string CodeActionsMakeRefStruct = "CodeActions.MakeRefStruct"; public const string CodeActionsMakeStatementAsynchronous = "CodeActions.MakeStatementAsynchronous"; public const string CodeActionsMakeStructFieldsWritable = "CodeActions.MakeStructFieldsWritable"; public const string CodeActionsMakeTypeAbstract = "CodeActions.MakeTypeAbstract"; public const string CodeActionsMergeConsecutiveIfStatements = "CodeActions.MergeConsecutiveIfStatements"; public const string CodeActionsMergeNestedIfStatements = "CodeActions.MergeNestedIfStatements"; public const string CodeActionsMoveDeclarationNearReference = "CodeActions.MoveDeclarationNearReference"; public const string CodeActionsMoveToNamespace = nameof(CodeActionsMoveToNamespace); public const string CodeActionsMoveToTopOfFile = "CodeActions.MoveToTopOfFile"; public const string CodeActionsMoveType = "CodeActions.MoveType"; public const string CodeActionsNameTupleElement = "CodeActions.NameTupleElement"; public const string CodeActionsOrderModifiers = "CodeActions.OrderModifiers"; public const string CodeActionsPopulateSwitch = "CodeActions.PopulateSwitch"; public const string CodeActionsPullMemberUp = "CodeActions.PullMemberUp"; public const string CodeActionsQualifyMemberAccess = "CodeActions.QualifyMemberAccess"; public const string CodeActionsRemoveAsyncModifier = "CodeActions.RemoveAsyncModifier"; public const string CodeActionsRemoveByVal = "CodeActions.RemoveByVal"; public const string CodeActionsRemoveDocCommentNode = "CodeActions.RemoveDocCommentNode"; public const string CodeActionsRemoveInKeyword = "CodeActions.RemoveInKeyword"; public const string CodeActionsRemoveUnnecessarySuppressions = "CodeActions.RemoveUnnecessarySuppressions"; public const string CodeActionsRemoveUnnecessaryCast = "CodeActions.RemoveUnnecessaryCast"; public const string CodeActionsRemoveUnnecessaryDiscardDesignation = "CodeActions.RemoveUnnecessaryDiscardDesignation"; public const string CodeActionsRemoveUnnecessaryImports = "CodeActions.RemoveUnnecessaryImports"; public const string CodeActionsRemoveUnnecessaryParentheses = "CodeActions.RemoveUnnecessaryParentheses"; public const string CodeActionsRemoveUnreachableCode = "CodeActions.RemoveUnreachableCode"; public const string CodeActionsRemoveUnusedLocalFunction = "CodeActions.RemoveUnusedLocalFunction"; public const string CodeActionsRemoveUnusedMembers = "CodeActions.RemoveUnusedMembers"; public const string CodeActionsRemoveUnusedParameters = "CodeActions.RemoveUnusedParameters"; public const string CodeActionsRemoveUnusedValues = "CodeActions.RemoveUnusedValues"; public const string CodeActionsRemoveUnusedVariable = "CodeActions.RemoveUnusedVariable"; public const string CodeActionsReplaceDefaultLiteral = "CodeActions.ReplaceDefaultLiteral"; public const string CodeActionsReplaceDocCommentTextWithTag = "CodeActions.ReplaceDocCommentTextWithTag"; public const string CodeActionsReplaceMethodWithProperty = "CodeActions.ReplaceMethodWithProperty"; public const string CodeActionsReplacePropertyWithMethods = "CodeActions.ReplacePropertyWithMethods"; public const string CodeActionsResolveConflictMarker = "CodeActions.ResolveConflictMarker"; public const string CodeActionsReverseForStatement = "CodeActions.ReverseForStatement"; public const string CodeActionsSimplifyConditional = "CodeActions.SimplifyConditional"; public const string CodeActionsSimplifyInterpolation = "CodeActions.SimplifyInterpolation"; public const string CodeActionsSimplifyLinqExpression = "CodeActions.SimplifyLinqExpression"; public const string CodeActionsSimplifyThisOrMe = "CodeActions.SimplifyThisOrMe"; public const string CodeActionsSimplifyTypeNames = "CodeActions.SimplifyTypeNames"; public const string CodeActionsSpellcheck = "CodeActions.Spellcheck"; public const string CodeActionsSplitIntoConsecutiveIfStatements = "CodeActions.SplitIntoConsecutiveIfStatements"; public const string CodeActionsSplitIntoNestedIfStatements = "CodeActions.SplitIntoNestedIfStatements"; public const string CodeActionsSuppression = "CodeActions.Suppression"; public const string CodeActionsSyncNamespace = "CodeActions.SyncNamespace"; public const string CodeActionsUnsealClass = "CodeActions.UnsealClass"; public const string CodeActionsUpdateLegacySuppressions = "CodeActions.UpdateLegacySuppressions"; public const string CodeActionsUpdateProjectToAllowUnsafe = "CodeActions.UpdateProjectToAllowUnsafe"; public const string CodeActionsUpgradeProject = "CodeActions.UpgradeProject"; public const string CodeActionsUseAutoProperty = "CodeActions.UseAutoProperty"; public const string CodeActionsUseCoalesceExpression = "CodeActions.UseCoalesceExpression"; public const string CodeActionsUseCollectionInitializer = "CodeActions.UseCollectionInitializer"; public const string CodeActionsUseCompoundAssignment = "CodeActions.UseCompoundAssignment"; public const string CodeActionsUseConditionalExpression = "CodeActions.UseConditionalExpression"; public const string CodeActionsUseDeconstruction = "CodeActions.UseDeconstruction"; public const string CodeActionsUseDefaultLiteral = "CodeActions.UseDefaultLiteral"; public const string CodeActionsUseExplicitTupleName = "CodeActions.UseExplicitTupleName"; public const string CodeActionsUseExplicitType = "CodeActions.UseExplicitType"; public const string CodeActionsUseExplicitTypeForConst = "CodeActions.UseExplicitTypeForConst"; public const string CodeActionsUseExpressionBody = "CodeActions.UseExpressionBody"; public const string CodeActionsUseFrameworkType = "CodeActions.UseFrameworkType"; public const string CodeActionsUseImplicitObjectCreation = "CodeActions.UseImplicitObjectCreation"; public const string CodeActionsUseImplicitType = "CodeActions.UseImplicitType"; public const string CodeActionsUseIndexOperator = "CodeActions.UseIndexOperator"; public const string CodeActionsUseInferredMemberName = "CodeActions.UseInferredMemberName"; public const string CodeActionsUseInterpolatedVerbatimString = "CodeActions.UseInterpolatedVerbatimString"; public const string CodeActionsUseIsNotExpression = "CodeActions.UseIsNotExpression"; public const string CodeActionsUseIsNullCheck = "CodeActions.UseIsNullCheck"; public const string CodeActionsUseLocalFunction = "CodeActions.UseLocalFunction"; public const string CodeActionsUseNamedArguments = "CodeActions.UseNamedArguments"; public const string CodeActionsUseNotPattern = "CodeActions.UseNotPattern"; public const string CodeActionsUsePatternCombinators = "CodeActions.UsePatternCombinators"; public const string CodeActionsUseRecursivePatterns = "CodeActions.UseRecursivePatterns"; public const string CodeActionsUseNullPropagation = "CodeActions.UseNullPropagation"; public const string CodeActionsUseObjectInitializer = "CodeActions.UseObjectInitializer"; public const string CodeActionsUseRangeOperator = "CodeActions.UseRangeOperator"; public const string CodeActionsUseSimpleUsingStatement = "CodeActions.UseSimpleUsingStatement"; public const string CodeActionsUseSystemHashCode = "CodeActions.UseSystemHashCode"; public const string CodeActionsUseThrowExpression = "CodeActions.UseThrowExpression"; public const string CodeActionsWrapping = "CodeActions.Wrapping"; public const string CodeCleanup = nameof(CodeCleanup); public const string CodeGeneration = nameof(CodeGeneration); public const string CodeGenerationSortDeclarations = "CodeGeneration.SortDeclarations"; public const string CodeLens = nameof(CodeLens); public const string CodeModel = nameof(CodeModel); public const string CodeModelEvents = "CodeModel.Events"; public const string CodeModelMethodXml = "CodeModel.MethodXml"; public const string CommentSelection = nameof(CommentSelection); public const string CompleteStatement = nameof(CompleteStatement); public const string Completion = nameof(Completion); public const string ConvertAutoPropertyToFullProperty = nameof(ConvertAutoPropertyToFullProperty); public const string ConvertCast = nameof(ConvertCast); public const string ConvertTypeOfToNameOf = nameof(ConvertTypeOfToNameOf); public const string DebuggingBreakpoints = "Debugging.Breakpoints"; public const string DebuggingDataTips = "Debugging.DataTips"; public const string DebuggingEditAndContinue = "Debugging.EditAndContinue"; public const string DebuggingIntelliSense = "Debugging.IntelliSense"; public const string DebuggingLocationName = "Debugging.LocationName"; public const string DebuggingNameResolver = "Debugging.NameResolver"; public const string DebuggingProximityExpressions = "Debugging.ProximityExpressions"; public const string DecompiledSource = nameof(DecompiledSource); public const string Diagnostics = nameof(Diagnostics); public const string DisposeAnalysis = nameof(DisposeAnalysis); public const string DocCommentFormatting = nameof(DocCommentFormatting); public const string DocumentationComments = nameof(DocumentationComments); public const string EditorConfig = nameof(EditorConfig); public const string EditorConfigUI = nameof(EditorConfigUI); public const string EncapsulateField = nameof(EncapsulateField); public const string EndConstructGeneration = nameof(EndConstructGeneration); public const string ErrorList = nameof(ErrorList); public const string ErrorSquiggles = nameof(ErrorSquiggles); public const string EventHookup = nameof(EventHookup); public const string Expansion = nameof(Expansion); public const string ExtractInterface = "Refactoring.ExtractInterface"; public const string ExtractMethod = "Refactoring.ExtractMethod"; public const string F1Help = nameof(F1Help); public const string FindReferences = nameof(FindReferences); public const string FixIncorrectTokens = nameof(FixIncorrectTokens); public const string FixInterpolatedVerbatimString = nameof(FixInterpolatedVerbatimString); public const string Formatting = nameof(Formatting); public const string GoToAdjacentMember = nameof(GoToAdjacentMember); public const string GoToBase = nameof(GoToBase); public const string GoToDefinition = nameof(GoToDefinition); public const string GoToImplementation = nameof(GoToImplementation); public const string InheritanceMargin = nameof(InheritanceMargin); public const string InlineHints = nameof(InlineHints); public const string Interactive = nameof(Interactive); public const string InteractiveHost = nameof(InteractiveHost); public const string KeywordHighlighting = nameof(KeywordHighlighting); public const string KeywordRecommending = nameof(KeywordRecommending); public const string LineCommit = nameof(LineCommit); public const string LineSeparators = nameof(LineSeparators); public const string LinkedFileDiffMerging = nameof(LinkedFileDiffMerging); public const string MSBuildWorkspace = nameof(MSBuildWorkspace); public const string MetadataAsSource = nameof(MetadataAsSource); public const string MoveToNamespace = nameof(MoveToNamespace); public const string NamingStyle = nameof(NamingStyle); public const string NavigableSymbols = nameof(NavigableSymbols); public const string NavigateTo = nameof(NavigateTo); public const string NavigationBar = nameof(NavigationBar); public const string NetCore = nameof(NetCore); public const string NormalizeModifiersOrOperators = nameof(NormalizeModifiersOrOperators); public const string ObjectBrowser = nameof(ObjectBrowser); public const string Options = nameof(Options); public const string Organizing = nameof(Organizing); public const string Outlining = nameof(Outlining); public const string Packaging = nameof(Packaging); public const string PasteTracking = nameof(PasteTracking); public const string Peek = nameof(Peek); public const string Progression = nameof(Progression); public const string ProjectSystemShims = nameof(ProjectSystemShims); public const string SarifErrorLogging = nameof(SarifErrorLogging); public const string QuickInfo = nameof(QuickInfo); public const string RQName = nameof(RQName); public const string ReduceTokens = nameof(ReduceTokens); public const string ReferenceHighlighting = nameof(ReferenceHighlighting); public const string RemoteHost = nameof(RemoteHost); public const string RemoveUnnecessaryLineContinuation = nameof(RemoveUnnecessaryLineContinuation); public const string Rename = nameof(Rename); public const string RenameTracking = nameof(RenameTracking); public const string SignatureHelp = nameof(SignatureHelp); public const string Simplification = nameof(Simplification); public const string SmartIndent = nameof(SmartIndent); public const string SmartTokenFormatting = nameof(SmartTokenFormatting); public const string Snippets = nameof(Snippets); public const string SourceGenerators = nameof(SourceGenerators); public const string SplitComment = nameof(SplitComment); public const string SplitStringLiteral = nameof(SplitStringLiteral); public const string SuggestionTags = nameof(SuggestionTags); public const string SyncNamespaces = nameof(SyncNamespaces); public const string TargetTypedCompletion = nameof(TargetTypedCompletion); public const string TextStructureNavigator = nameof(TextStructureNavigator); public const string TodoComments = nameof(TodoComments); public const string ToggleBlockComment = nameof(ToggleBlockComment); public const string ToggleLineComment = nameof(ToggleLineComment); public const string TypeInferenceService = nameof(TypeInferenceService); public const string UnusedReferences = nameof(UnusedReferences); public const string ValidateFormatString = nameof(ValidateFormatString); public const string ValidateRegexString = nameof(ValidateRegexString); public const string Venus = nameof(Venus); public const string VsLanguageBlock = nameof(VsLanguageBlock); public const string VsNavInfo = nameof(VsNavInfo); public const string VsSearch = nameof(VsSearch); public const string WinForms = nameof(WinForms); public const string Workspace = nameof(Workspace); public const string XmlTagCompletion = nameof(XmlTagCompletion); } public const string Environment = nameof(Environment); public static class Environments { public const string VSProductInstall = nameof(VSProductInstall); } } }
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/Workspaces/CoreTest/WorkspaceServiceTests/OptionServiceTests.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.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor.Implementation.TodoComments; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.WorkspaceServices { [UseExportProvider] public class OptionServiceTests { [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void OptionWithNullOrWhitespace() { using var workspace = new AdhocWorkspace(); var optionService = TestOptionService.GetService(workspace); var optionSet = optionService.GetOptions(); Assert.Throws<System.ArgumentException>(delegate { var option = new Option<bool>("Test Feature", "", false); }); Assert.Throws<System.ArgumentException>(delegate { var option2 = new Option<bool>("Test Feature", null!, false); }); Assert.Throws<System.ArgumentNullException>(delegate { var option3 = new Option<bool>(" ", "Test Name", false); }); Assert.Throws<System.ArgumentNullException>(delegate { var option4 = new Option<bool>(null!, "Test Name", false); }); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void OptionPerLanguageOption() { using var workspace = new AdhocWorkspace(); var optionService = TestOptionService.GetService(workspace); var optionSet = optionService.GetOptions(); Assert.Throws<System.ArgumentException>(delegate { var option = new PerLanguageOption<bool>("Test Feature", "", false); }); Assert.Throws<System.ArgumentException>(delegate { var option2 = new PerLanguageOption<bool>("Test Feature", null!, false); }); Assert.Throws<System.ArgumentNullException>(delegate { var option3 = new PerLanguageOption<bool>(" ", "Test Name", false); }); Assert.Throws<System.ArgumentNullException>(delegate { var option4 = new PerLanguageOption<bool>(null!, "Test Name", false); }); var optionvalid = new PerLanguageOption<bool>("Test Feature", "Test Name", false); Assert.False(optionSet.GetOption(optionvalid, "CS")); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void GettingOptionReturnsOption() { using var workspace = new AdhocWorkspace(); var optionService = TestOptionService.GetService(workspace); var optionSet = optionService.GetOptions(); var option = new Option<bool>("Test Feature", "Test Name", false); Assert.False(optionSet.GetOption(option)); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void GlobalOptions() { using var workspace = new AdhocWorkspace(); var optionService = TestOptionService.GetGlobalOptionService(workspace.Services); var option1 = new Option<int>("Feature1", "Name1", defaultValue: 1); var option2 = new Option<int>("Feature2", "Name2", defaultValue: 2); var option3 = new Option<int>("Feature3", "Name3", defaultValue: 3); var changedOptions = new List<OptionChangedEventArgs>(); var handler = new EventHandler<OptionChangedEventArgs>((_, e) => changedOptions.Add(e)); optionService.OptionChanged += handler; var values = optionService.GetOptions(ImmutableArray.Create<OptionKey>(option1, option2)); Assert.Equal(1, values[0]); Assert.Equal(2, values[1]); optionService.SetGlobalOptions( ImmutableArray.Create<OptionKey>(option1, option2, option3), ImmutableArray.Create<object?>(5, 6, 3)); AssertEx.Equal(new[] { "Name1=5", "Name2=6", }, changedOptions.Select(e => $"{e.OptionKey.Option.Name}={e.Value}")); values = optionService.GetOptions(ImmutableArray.Create<OptionKey>(option1, option2, option3)); Assert.Equal(5, values[0]); Assert.Equal(6, values[1]); Assert.Equal(3, values[2]); Assert.Equal(5, optionService.GetOption(option1)); Assert.Equal(6, optionService.GetOption(option2)); Assert.Equal(3, optionService.GetOption(option3)); optionService.OptionChanged -= handler; } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void GettingOptionWithChangedOption() { using var workspace = new AdhocWorkspace(); var optionService = TestOptionService.GetService(workspace); OptionSet optionSet = optionService.GetOptions(); var option = new Option<bool>("Test Feature", "Test Name", false); var key = new OptionKey(option); Assert.False(optionSet.GetOption(option)); optionSet = optionSet.WithChangedOption(key, true); Assert.True((bool?)optionSet.GetOption(key)); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void GettingOptionWithoutChangedOption() { using var workspace = new AdhocWorkspace(); var optionService = TestOptionService.GetService(workspace); var optionSet = optionService.GetOptions(); var optionFalse = new Option<bool>("Test Feature", "Test Name", false); Assert.False(optionSet.GetOption(optionFalse)); var optionTrue = new Option<bool>("Test Feature", "Test Name", true); Assert.True(optionSet.GetOption(optionTrue)); var falseKey = new OptionKey(optionFalse); Assert.False((bool?)optionSet.GetOption(falseKey)); var trueKey = new OptionKey(optionTrue); Assert.True((bool?)optionSet.GetOption(trueKey)); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void GetKnownOptions() { using var workspace = new AdhocWorkspace(); var optionService = TestOptionService.GetService(workspace); var option = new Option<bool>("Test Feature", "Test Name", defaultValue: true); optionService.GetOption(option); var optionSet = optionService.GetOptions(); var value = optionSet.GetOption(option); Assert.True(value); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void GetKnownOptionsKey() { using var workspace = new AdhocWorkspace(); var optionService = TestOptionService.GetService(workspace); var option = new Option<bool>("Test Feature", "Test Name", defaultValue: true); optionService.GetOption(option); var optionSet = optionService.GetOptions(); var optionKey = new OptionKey(option); var value = (bool?)optionSet.GetOption(optionKey); Assert.True(value); } [Fact] public void SetKnownOptions() { using var workspace = new AdhocWorkspace(); var optionService = TestOptionService.GetService(workspace); var optionSet = optionService.GetOptions(); var option = new Option<bool>("Test Feature", "Test Name", defaultValue: true); var optionKey = new OptionKey(option); var newOptionSet = optionSet.WithChangedOption(optionKey, false); optionService.SetOptions(newOptionSet); var isOptionSet = (bool?)optionService.GetOptions().GetOption(optionKey); Assert.False(isOptionSet); } [Fact] public void OptionSetIsImmutable() { using var workspace = new AdhocWorkspace(); var optionService = TestOptionService.GetService(workspace); var optionSet = optionService.GetOptions(); var option = new Option<bool>("Test Feature", "Test Name", defaultValue: true); var optionKey = new OptionKey(option); var newOptionSet = optionSet.WithChangedOption(optionKey, false); Assert.NotSame(optionSet, newOptionSet); Assert.NotEqual(optionSet, newOptionSet); } [Fact] public void TestChangedOptions() { using var workspace = new AdhocWorkspace(); // Apply a serializable changed option to the option service // and verify that serializable options snapshot contains this changed option. TestChangedOptionsCore( workspace, GenerationOptions.PlaceSystemNamespaceFirst, optionProvider: ((IMefHostExportProvider)workspace.Services.HostServices).GetExportedValues<IOptionProvider>().OfType<GenerationOptionsProvider>().Single(), isSerializable: true); // Apply a non-serializable changed option to the option service // and verify that serializable options snapshot does not contain this changed option TestChangedOptionsCore( workspace, new PerLanguageOption2<bool>("Test Feature", "Test Name", defaultValue: true), optionProvider: new TestOptionService.TestOptionsProvider(), isSerializable: false); return; static void TestChangedOptionsCore(Workspace workspace, PerLanguageOption2<bool> option, IOptionProvider optionProvider, bool isSerializable) { var optionService = TestOptionService.GetService(workspace, optionProvider); var optionSet = optionService.GetOptions(); var optionKey = new OptionKey(option, LanguageNames.CSharp); var currentOptionValue = optionSet.GetOption(option, LanguageNames.CSharp); var newOptionValue = !currentOptionValue; var newOptionSet = (SerializableOptionSet)optionSet.WithChangedOption(optionKey, newOptionValue); optionService.SetOptions(newOptionSet); var isOptionSet = (bool?)optionService.GetOptions().GetOption(optionKey); Assert.Equal(newOptionValue, isOptionSet); // Verify the serializable option snapshot obtained option service has the changed option only if the option key is serializable. var languages = ImmutableHashSet.Create(LanguageNames.CSharp); var serializableOptionSet = optionService.GetSerializableOptionsSnapshot(languages); VerifyChangedOptionsCore(serializableOptionSet, optionKey, expectedChangedOption: isSerializable); // Serialize/deserialize the option set to test round tripping. serializableOptionSet = (SerializableOptionSet)serializableOptionSet.WithChangedOption(optionKey, newOptionValue); using var memoryStream = new MemoryStream(); using var writer = new ObjectWriter(memoryStream, leaveOpen: true); serializableOptionSet.Serialize(writer, CancellationToken.None); memoryStream.Position = 0; var originalChecksum = Checksum.Create(memoryStream); memoryStream.Position = 0; using var reader = ObjectReader.TryGetReader(memoryStream); serializableOptionSet = SerializableOptionSet.Deserialize(reader, optionService, CancellationToken.None); // Verify the option set obtained from round trip has the changed option only if the option key is serializable. VerifyChangedOptionsCore(serializableOptionSet, optionKey, expectedChangedOption: isSerializable); using var newMemoryStream = new MemoryStream(); using var newWriter = new ObjectWriter(newMemoryStream, leaveOpen: true); serializableOptionSet.Serialize(newWriter, CancellationToken.None); newMemoryStream.Position = 0; var newChecksum = Checksum.Create(newMemoryStream); Assert.Equal(originalChecksum, newChecksum); return; static void VerifyChangedOptionsCore(SerializableOptionSet serializableOptionSet, OptionKey optionKey, bool expectedChangedOption) { var changedOptions = serializableOptionSet.GetChangedOptions(); if (expectedChangedOption) { var changedOptionKey = Assert.Single(changedOptions); Assert.Equal(optionKey, changedOptionKey); } else { Assert.Empty(changedOptions); } } } } [Fact, WorkItem(43788, "https://github.com/dotnet/roslyn/issues/43788")] public void TestChangedTodoCommentOptions() { var hostServices = FeaturesTestCompositions.Features.AddParts(typeof(TestOptionsServiceFactory)).GetHostServices(); using var workspace = new AdhocWorkspace(hostServices); var option = TodoCommentOptions.TokenList; var provider = ((IMefHostExportProvider)hostServices).GetExportedValues<IOptionProvider>().OfType<TodoCommentOptionsProvider>().FirstOrDefault(); var optionService = TestOptionService.GetService(workspace, provider); var optionSet = optionService.GetOptions(); var optionKey = new OptionKey(option); var currentOptionValue = optionSet.GetOption(option); var newOptionValue = currentOptionValue + "newValue"; var newOptionSet = optionSet.WithChangedOption(optionKey, newOptionValue); optionService.SetOptions(newOptionSet); Assert.Equal(newOptionValue, (string?)optionService.GetOptions().GetOption(optionKey)); var languages = ImmutableHashSet.Create(LanguageNames.CSharp); var serializableOptionSet = optionService.GetSerializableOptionsSnapshot(languages); var changedOptions = serializableOptionSet.GetChangedOptions(); var changedOptionKey = Assert.Single(changedOptions); Assert.Equal(optionKey, changedOptionKey); Assert.Equal(newOptionValue, serializableOptionSet.GetOption(changedOptionKey)); } [Fact, WorkItem(1128126, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1128126")] public void TestPersistedTodoCommentOptions() { var hostServices = FeaturesTestCompositions.Features.AddParts(typeof(TestOptionsServiceFactory)).GetHostServices(); using var workspace = new AdhocWorkspace(hostServices); var option = TodoCommentOptions.TokenList; var newOptionValue = option.DefaultValue + "|name:value"; var persister = new TestOptionService.TestOptionsPersister(); var persisted = persister.TryPersist(option, newOptionValue); Assert.True(persisted); Assert.True(persister.TryFetch(option, out var persistedValue)); Assert.Equal(newOptionValue, persistedValue); var provider = ((IMefHostExportProvider)hostServices).GetExportedValues<IOptionProvider>().OfType<TodoCommentOptionsProvider>().FirstOrDefault(); var persisterProvider = new TestOptionService.TestOptionsPersisterProvider(persister); var optionService = TestOptionService.GetService(workspace, provider, persisterProvider); var optionSet = optionService.GetOptions(); var optionKey = new OptionKey(option); Assert.Equal(newOptionValue, (string?)optionSet.GetOption(optionKey)); var languages = ImmutableHashSet.Create(LanguageNames.CSharp); var serializableOptionSet = optionService.GetSerializableOptionsSnapshot(languages); var changedOptions = serializableOptionSet.GetChangedOptions(); var changedOptionKey = Assert.Single(changedOptions); Assert.Equal(optionKey, changedOptionKey); Assert.Equal(newOptionValue, serializableOptionSet.GetOption(changedOptionKey)); } [Fact] public void TestPerLanguageCodeStyleOptions() { using var workspace = new AdhocWorkspace(); var perLanguageOption2 = new PerLanguageOption2<CodeStyleOption2<bool>>("test", "test", new CodeStyleOption2<bool>(false, NotificationOption2.Warning)); var perLanguageOption = perLanguageOption2.ToPublicOption(); var newValueCodeStyleOption2 = new CodeStyleOption2<bool>(!perLanguageOption2.DefaultValue.Value, perLanguageOption2.DefaultValue.Notification); var newValueCodeStyleOption = (CodeStyleOption<bool>)newValueCodeStyleOption2!; // Test "OptionKey" based overloads for get/set options on OptionSet and OptionService using different public and internal type combinations. // 1. { PerLanguageOption, CodeStyleOption } TestCodeStyleOptionsCommon(workspace, perLanguageOption, LanguageNames.CSharp, newValueCodeStyleOption); // 2. { PerLanguageOption2, CodeStyleOption } TestCodeStyleOptionsCommon(workspace, perLanguageOption2, LanguageNames.CSharp, newValueCodeStyleOption); // 3. { PerLanguageOption, CodeStyleOption2 } TestCodeStyleOptionsCommon(workspace, perLanguageOption, LanguageNames.CSharp, newValueCodeStyleOption2); // 4. { PerLanguageOption2, CodeStyleOption2 } TestCodeStyleOptionsCommon(workspace, perLanguageOption2, LanguageNames.CSharp, newValueCodeStyleOption2); var optionService = TestOptionService.GetService(workspace); var originalOptionSet = optionService.GetOptions(); // Test "PerLanguageOption" and "PerLanguageOption2" overloads for OptionSet and OptionService. // 1. Verify default value. Assert.Equal(perLanguageOption.DefaultValue, originalOptionSet.GetOption(perLanguageOption, LanguageNames.CSharp)); Assert.Equal(perLanguageOption2.DefaultValue, originalOptionSet.GetOption(perLanguageOption2, LanguageNames.CSharp)); // 2. OptionSet validations. var newOptionSet = originalOptionSet.WithChangedOption(perLanguageOption, LanguageNames.CSharp, newValueCodeStyleOption); Assert.Equal(newValueCodeStyleOption, newOptionSet.GetOption(perLanguageOption, LanguageNames.CSharp)); Assert.Equal(newValueCodeStyleOption2, newOptionSet.GetOption(perLanguageOption2, LanguageNames.CSharp)); newOptionSet = originalOptionSet.WithChangedOption(perLanguageOption2, LanguageNames.CSharp, newValueCodeStyleOption2); Assert.Equal(newValueCodeStyleOption, newOptionSet.GetOption(perLanguageOption, LanguageNames.CSharp)); Assert.Equal(newValueCodeStyleOption2, newOptionSet.GetOption(perLanguageOption2, LanguageNames.CSharp)); // 3. IOptionService validation optionService.SetOptions(newOptionSet); Assert.Equal(newValueCodeStyleOption, optionService.GetOption(perLanguageOption, LanguageNames.CSharp)); Assert.Equal(newValueCodeStyleOption2, optionService.GetOption(perLanguageOption2, LanguageNames.CSharp)); } [Fact] public void TestLanguageSpecificCodeStyleOptions() { using var workspace = new AdhocWorkspace(); var option2 = new Option2<CodeStyleOption2<bool>>("test", "test", new CodeStyleOption2<bool>(false, NotificationOption2.Warning)); var option = option2.ToPublicOption(); var newValueCodeStyleOption2 = new CodeStyleOption2<bool>(!option2.DefaultValue.Value, option2.DefaultValue.Notification); var newValueCodeStyleOption = (CodeStyleOption<bool>)newValueCodeStyleOption2!; // Test "OptionKey" based overloads for get/set options on OptionSet and OptionService using different public and internal type combinations. // 1. { Option, CodeStyleOption } TestCodeStyleOptionsCommon(workspace, option, language: null, newValueCodeStyleOption); // 2. { Option2, CodeStyleOption } TestCodeStyleOptionsCommon(workspace, option2, language: null, newValueCodeStyleOption); // 3. { Option, CodeStyleOption2 } TestCodeStyleOptionsCommon(workspace, option, language: null, newValueCodeStyleOption2); // 4. { Option2, CodeStyleOption2 } TestCodeStyleOptionsCommon(workspace, option2, language: null, newValueCodeStyleOption2); var optionService = TestOptionService.GetService(workspace); var originalOptionSet = optionService.GetOptions(); // Test "Option" and "Option2" overloads for OptionSet and OptionService. // 1. Verify default value. Assert.Equal(option.DefaultValue, originalOptionSet.GetOption(option)); Assert.Equal(option2.DefaultValue, originalOptionSet.GetOption(option2)); // 2. OptionSet validations. var newOptionSet = originalOptionSet.WithChangedOption(option, newValueCodeStyleOption); Assert.Equal(newValueCodeStyleOption, newOptionSet.GetOption(option)); Assert.Equal(newValueCodeStyleOption2, newOptionSet.GetOption(option2)); newOptionSet = originalOptionSet.WithChangedOption(option2, newValueCodeStyleOption2); Assert.Equal(newValueCodeStyleOption, newOptionSet.GetOption(option)); Assert.Equal(newValueCodeStyleOption2, newOptionSet.GetOption(option2)); // 3. IOptionService validation optionService.SetOptions(newOptionSet); Assert.Equal(newValueCodeStyleOption, optionService.GetOption(option)); Assert.Equal(newValueCodeStyleOption2, optionService.GetOption(option2)); } private static void TestCodeStyleOptionsCommon<TCodeStyleOption>(Workspace workspace, IOption2 option, string? language, TCodeStyleOption newValue) where TCodeStyleOption : ICodeStyleOption { var optionService = TestOptionService.GetService(workspace); var originalOptionSet = optionService.GetOptions(); // Test matrix using different OptionKey and OptionKey2 get/set operations. var optionKey = new OptionKey(option, language); var optionKey2 = new OptionKey2(option, language); // Value return from "object GetOption(OptionKey)" should always be public CodeStyleOption type. var newPublicValue = newValue.AsPublicCodeStyleOption(); // 1. WithChangedOption(OptionKey), GetOption(OptionKey)/GetOption<T>(OptionKey) var newOptionSet = originalOptionSet.WithChangedOption(optionKey, newValue); Assert.Equal(newPublicValue, newOptionSet.GetOption(optionKey)); // Value returned from public API should always be castable to public CodeStyleOption type. Assert.NotNull((CodeStyleOption<bool>)newOptionSet.GetOption(optionKey)!); // Verify "T GetOption<T>(OptionKey)" works for both cases of T being a public and internal code style option type. Assert.Equal(newPublicValue, newOptionSet.GetOption<CodeStyleOption<bool>>(optionKey)); Assert.Equal(newValue, newOptionSet.GetOption<TCodeStyleOption>(optionKey)); // 2. WithChangedOption(OptionKey), GetOption(OptionKey2)/GetOption<T>(OptionKey2) newOptionSet = originalOptionSet.WithChangedOption(optionKey, newValue); Assert.Equal(newPublicValue, newOptionSet.GetOption(optionKey2)); // Verify "T GetOption<T>(OptionKey2)" works for both cases of T being a public and internal code style option type. Assert.Equal(newPublicValue, newOptionSet.GetOption<CodeStyleOption<bool>>(optionKey2)); Assert.Equal(newValue, newOptionSet.GetOption<TCodeStyleOption>(optionKey2)); // 3. WithChangedOption(OptionKey2), GetOption(OptionKey)/GetOption<T>(OptionKey) newOptionSet = originalOptionSet.WithChangedOption(optionKey2, newValue); Assert.Equal(newPublicValue, newOptionSet.GetOption(optionKey)); // Value returned from public API should always be castable to public CodeStyleOption type. Assert.NotNull((CodeStyleOption<bool>)newOptionSet.GetOption(optionKey)!); // Verify "T GetOption<T>(OptionKey)" works for both cases of T being a public and internal code style option type. Assert.Equal(newPublicValue, newOptionSet.GetOption<CodeStyleOption<bool>>(optionKey)); Assert.Equal(newValue, newOptionSet.GetOption<TCodeStyleOption>(optionKey)); // 4. WithChangedOption(OptionKey2), GetOption(OptionKey2)/GetOption<T>(OptionKey2) newOptionSet = originalOptionSet.WithChangedOption(optionKey2, newValue); Assert.Equal(newPublicValue, newOptionSet.GetOption(optionKey2)); // Verify "T GetOption<T>(OptionKey2)" works for both cases of T being a public and internal code style option type. Assert.Equal(newPublicValue, newOptionSet.GetOption<CodeStyleOption<bool>>(optionKey2)); Assert.Equal(newValue, newOptionSet.GetOption<TCodeStyleOption>(optionKey2)); // 5. IOptionService.GetOption(OptionKey) optionService.SetOptions(newOptionSet); Assert.Equal(newPublicValue, optionService.GetOption(optionKey)); } } }
// Licensed to the .NET Foundation under one or more 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.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor.Implementation.TodoComments; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.WorkspaceServices { [UseExportProvider] public class OptionServiceTests { [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void OptionWithNullOrWhitespace() { using var workspace = new AdhocWorkspace(); var optionService = TestOptionService.GetService(workspace); var optionSet = optionService.GetOptions(); Assert.Throws<System.ArgumentException>(delegate { var option = new Option<bool>("Test Feature", "", false); }); Assert.Throws<System.ArgumentException>(delegate { var option2 = new Option<bool>("Test Feature", null!, false); }); Assert.Throws<System.ArgumentNullException>(delegate { var option3 = new Option<bool>(" ", "Test Name", false); }); Assert.Throws<System.ArgumentNullException>(delegate { var option4 = new Option<bool>(null!, "Test Name", false); }); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void OptionPerLanguageOption() { using var workspace = new AdhocWorkspace(); var optionService = TestOptionService.GetService(workspace); var optionSet = optionService.GetOptions(); Assert.Throws<System.ArgumentException>(delegate { var option = new PerLanguageOption<bool>("Test Feature", "", false); }); Assert.Throws<System.ArgumentException>(delegate { var option2 = new PerLanguageOption<bool>("Test Feature", null!, false); }); Assert.Throws<System.ArgumentNullException>(delegate { var option3 = new PerLanguageOption<bool>(" ", "Test Name", false); }); Assert.Throws<System.ArgumentNullException>(delegate { var option4 = new PerLanguageOption<bool>(null!, "Test Name", false); }); var optionvalid = new PerLanguageOption<bool>("Test Feature", "Test Name", false); Assert.False(optionSet.GetOption(optionvalid, "CS")); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void GettingOptionReturnsOption() { using var workspace = new AdhocWorkspace(); var optionService = TestOptionService.GetService(workspace); var optionSet = optionService.GetOptions(); var option = new Option<bool>("Test Feature", "Test Name", false); Assert.False(optionSet.GetOption(option)); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void GlobalOptions() { using var workspace = new AdhocWorkspace(); var optionService = TestOptionService.GetGlobalOptionService(workspace.Services); var option1 = new Option<int>("Feature1", "Name1", defaultValue: 1); var option2 = new Option<int>("Feature2", "Name2", defaultValue: 2); var option3 = new Option<int>("Feature3", "Name3", defaultValue: 3); var changedOptions = new List<OptionChangedEventArgs>(); var handler = new EventHandler<OptionChangedEventArgs>((_, e) => changedOptions.Add(e)); optionService.OptionChanged += handler; var values = optionService.GetOptions(ImmutableArray.Create<OptionKey>(option1, option2)); Assert.Equal(1, values[0]); Assert.Equal(2, values[1]); optionService.SetGlobalOptions( ImmutableArray.Create<OptionKey>(option1, option2, option3), ImmutableArray.Create<object?>(5, 6, 3)); AssertEx.Equal(new[] { "Name1=5", "Name2=6", }, changedOptions.Select(e => $"{e.OptionKey.Option.Name}={e.Value}")); values = optionService.GetOptions(ImmutableArray.Create<OptionKey>(option1, option2, option3)); Assert.Equal(5, values[0]); Assert.Equal(6, values[1]); Assert.Equal(3, values[2]); Assert.Equal(5, optionService.GetOption(option1)); Assert.Equal(6, optionService.GetOption(option2)); Assert.Equal(3, optionService.GetOption(option3)); optionService.OptionChanged -= handler; } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void GettingOptionWithChangedOption() { using var workspace = new AdhocWorkspace(); var optionService = TestOptionService.GetService(workspace); OptionSet optionSet = optionService.GetOptions(); var option = new Option<bool>("Test Feature", "Test Name", false); var key = new OptionKey(option); Assert.False(optionSet.GetOption(option)); optionSet = optionSet.WithChangedOption(key, true); Assert.True((bool?)optionSet.GetOption(key)); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void GettingOptionWithoutChangedOption() { using var workspace = new AdhocWorkspace(); var optionService = TestOptionService.GetService(workspace); var optionSet = optionService.GetOptions(); var optionFalse = new Option<bool>("Test Feature", "Test Name", false); Assert.False(optionSet.GetOption(optionFalse)); var optionTrue = new Option<bool>("Test Feature", "Test Name", true); Assert.True(optionSet.GetOption(optionTrue)); var falseKey = new OptionKey(optionFalse); Assert.False((bool?)optionSet.GetOption(falseKey)); var trueKey = new OptionKey(optionTrue); Assert.True((bool?)optionSet.GetOption(trueKey)); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void GetKnownOptions() { using var workspace = new AdhocWorkspace(); var optionService = TestOptionService.GetService(workspace); var option = new Option<bool>("Test Feature", "Test Name", defaultValue: true); optionService.GetOption(option); var optionSet = optionService.GetOptions(); var value = optionSet.GetOption(option); Assert.True(value); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void GetKnownOptionsKey() { using var workspace = new AdhocWorkspace(); var optionService = TestOptionService.GetService(workspace); var option = new Option<bool>("Test Feature", "Test Name", defaultValue: true); optionService.GetOption(option); var optionSet = optionService.GetOptions(); var optionKey = new OptionKey(option); var value = (bool?)optionSet.GetOption(optionKey); Assert.True(value); } [Fact] public void SetKnownOptions() { using var workspace = new AdhocWorkspace(); var optionService = TestOptionService.GetService(workspace); var optionSet = optionService.GetOptions(); var option = new Option<bool>("Test Feature", "Test Name", defaultValue: true); var optionKey = new OptionKey(option); var newOptionSet = optionSet.WithChangedOption(optionKey, false); optionService.SetOptions(newOptionSet); var isOptionSet = (bool?)optionService.GetOptions().GetOption(optionKey); Assert.False(isOptionSet); } [Fact] public void OptionSetIsImmutable() { using var workspace = new AdhocWorkspace(); var optionService = TestOptionService.GetService(workspace); var optionSet = optionService.GetOptions(); var option = new Option<bool>("Test Feature", "Test Name", defaultValue: true); var optionKey = new OptionKey(option); var newOptionSet = optionSet.WithChangedOption(optionKey, false); Assert.NotSame(optionSet, newOptionSet); Assert.NotEqual(optionSet, newOptionSet); } [Fact] public void TestChangedOptions() { using var workspace = new AdhocWorkspace(); // Apply a serializable changed option to the option service // and verify that serializable options snapshot contains this changed option. TestChangedOptionsCore( workspace, GenerationOptions.PlaceSystemNamespaceFirst, optionProvider: ((IMefHostExportProvider)workspace.Services.HostServices).GetExportedValues<IOptionProvider>().OfType<GenerationOptionsProvider>().Single(), isSerializable: true); // Apply a non-serializable changed option to the option service // and verify that serializable options snapshot does not contain this changed option TestChangedOptionsCore( workspace, new PerLanguageOption2<bool>("Test Feature", "Test Name", defaultValue: true), optionProvider: new TestOptionService.TestOptionsProvider(), isSerializable: false); return; static void TestChangedOptionsCore(Workspace workspace, PerLanguageOption2<bool> option, IOptionProvider optionProvider, bool isSerializable) { var optionService = TestOptionService.GetService(workspace, optionProvider); var optionSet = optionService.GetOptions(); var optionKey = new OptionKey(option, LanguageNames.CSharp); var currentOptionValue = optionSet.GetOption(option, LanguageNames.CSharp); var newOptionValue = !currentOptionValue; var newOptionSet = (SerializableOptionSet)optionSet.WithChangedOption(optionKey, newOptionValue); optionService.SetOptions(newOptionSet); var isOptionSet = (bool?)optionService.GetOptions().GetOption(optionKey); Assert.Equal(newOptionValue, isOptionSet); // Verify the serializable option snapshot obtained option service has the changed option only if the option key is serializable. var languages = ImmutableHashSet.Create(LanguageNames.CSharp); var serializableOptionSet = optionService.GetSerializableOptionsSnapshot(languages); VerifyChangedOptionsCore(serializableOptionSet, optionKey, expectedChangedOption: isSerializable); // Serialize/deserialize the option set to test round tripping. serializableOptionSet = (SerializableOptionSet)serializableOptionSet.WithChangedOption(optionKey, newOptionValue); using var memoryStream = new MemoryStream(); using var writer = new ObjectWriter(memoryStream, leaveOpen: true); serializableOptionSet.Serialize(writer, CancellationToken.None); memoryStream.Position = 0; var originalChecksum = Checksum.Create(memoryStream); memoryStream.Position = 0; using var reader = ObjectReader.TryGetReader(memoryStream); serializableOptionSet = SerializableOptionSet.Deserialize(reader, optionService, CancellationToken.None); // Verify the option set obtained from round trip has the changed option only if the option key is serializable. VerifyChangedOptionsCore(serializableOptionSet, optionKey, expectedChangedOption: isSerializable); using var newMemoryStream = new MemoryStream(); using var newWriter = new ObjectWriter(newMemoryStream, leaveOpen: true); serializableOptionSet.Serialize(newWriter, CancellationToken.None); newMemoryStream.Position = 0; var newChecksum = Checksum.Create(newMemoryStream); Assert.Equal(originalChecksum, newChecksum); return; static void VerifyChangedOptionsCore(SerializableOptionSet serializableOptionSet, OptionKey optionKey, bool expectedChangedOption) { var changedOptions = serializableOptionSet.GetChangedOptions(); if (expectedChangedOption) { var changedOptionKey = Assert.Single(changedOptions); Assert.Equal(optionKey, changedOptionKey); } else { Assert.Empty(changedOptions); } } } } [Fact, WorkItem(43788, "https://github.com/dotnet/roslyn/issues/43788")] public void TestChangedTodoCommentOptions() { var hostServices = FeaturesTestCompositions.Features.AddParts(typeof(TestOptionsServiceFactory)).GetHostServices(); using var workspace = new AdhocWorkspace(hostServices); var option = TodoCommentOptions.TokenList; var provider = ((IMefHostExportProvider)hostServices).GetExportedValues<IOptionProvider>().OfType<TodoCommentOptionsProvider>().FirstOrDefault(); var optionService = TestOptionService.GetService(workspace, provider); var optionSet = optionService.GetOptions(); var optionKey = new OptionKey(option); var currentOptionValue = optionSet.GetOption(option); var newOptionValue = currentOptionValue + "newValue"; var newOptionSet = optionSet.WithChangedOption(optionKey, newOptionValue); optionService.SetOptions(newOptionSet); Assert.Equal(newOptionValue, (string?)optionService.GetOptions().GetOption(optionKey)); var languages = ImmutableHashSet.Create(LanguageNames.CSharp); var serializableOptionSet = optionService.GetSerializableOptionsSnapshot(languages); var changedOptions = serializableOptionSet.GetChangedOptions(); var changedOptionKey = Assert.Single(changedOptions); Assert.Equal(optionKey, changedOptionKey); Assert.Equal(newOptionValue, serializableOptionSet.GetOption(changedOptionKey)); } [Fact, WorkItem(1128126, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1128126")] public void TestPersistedTodoCommentOptions() { var hostServices = FeaturesTestCompositions.Features.AddParts(typeof(TestOptionsServiceFactory)).GetHostServices(); using var workspace = new AdhocWorkspace(hostServices); var option = TodoCommentOptions.TokenList; var newOptionValue = option.DefaultValue + "|name:value"; var persister = new TestOptionService.TestOptionsPersister(); var persisted = persister.TryPersist(option, newOptionValue); Assert.True(persisted); Assert.True(persister.TryFetch(option, out var persistedValue)); Assert.Equal(newOptionValue, persistedValue); var provider = ((IMefHostExportProvider)hostServices).GetExportedValues<IOptionProvider>().OfType<TodoCommentOptionsProvider>().FirstOrDefault(); var persisterProvider = new TestOptionService.TestOptionsPersisterProvider(persister); var optionService = TestOptionService.GetService(workspace, provider, persisterProvider); var optionSet = optionService.GetOptions(); var optionKey = new OptionKey(option); Assert.Equal(newOptionValue, (string?)optionSet.GetOption(optionKey)); var languages = ImmutableHashSet.Create(LanguageNames.CSharp); var serializableOptionSet = optionService.GetSerializableOptionsSnapshot(languages); var changedOptions = serializableOptionSet.GetChangedOptions(); var changedOptionKey = Assert.Single(changedOptions); Assert.Equal(optionKey, changedOptionKey); Assert.Equal(newOptionValue, serializableOptionSet.GetOption(changedOptionKey)); } [Fact] public void TestPerLanguageCodeStyleOptions() { using var workspace = new AdhocWorkspace(); var perLanguageOption2 = new PerLanguageOption2<CodeStyleOption2<bool>>("test", "test", new CodeStyleOption2<bool>(false, NotificationOption2.Warning)); var perLanguageOption = perLanguageOption2.ToPublicOption(); var newValueCodeStyleOption2 = new CodeStyleOption2<bool>(!perLanguageOption2.DefaultValue.Value, perLanguageOption2.DefaultValue.Notification); var newValueCodeStyleOption = (CodeStyleOption<bool>)newValueCodeStyleOption2!; // Test "OptionKey" based overloads for get/set options on OptionSet and OptionService using different public and internal type combinations. // 1. { PerLanguageOption, CodeStyleOption } TestCodeStyleOptionsCommon(workspace, perLanguageOption, LanguageNames.CSharp, newValueCodeStyleOption); // 2. { PerLanguageOption2, CodeStyleOption } TestCodeStyleOptionsCommon(workspace, perLanguageOption2, LanguageNames.CSharp, newValueCodeStyleOption); // 3. { PerLanguageOption, CodeStyleOption2 } TestCodeStyleOptionsCommon(workspace, perLanguageOption, LanguageNames.CSharp, newValueCodeStyleOption2); // 4. { PerLanguageOption2, CodeStyleOption2 } TestCodeStyleOptionsCommon(workspace, perLanguageOption2, LanguageNames.CSharp, newValueCodeStyleOption2); var optionService = TestOptionService.GetService(workspace); var originalOptionSet = optionService.GetOptions(); // Test "PerLanguageOption" and "PerLanguageOption2" overloads for OptionSet and OptionService. // 1. Verify default value. Assert.Equal(perLanguageOption.DefaultValue, originalOptionSet.GetOption(perLanguageOption, LanguageNames.CSharp)); Assert.Equal(perLanguageOption2.DefaultValue, originalOptionSet.GetOption(perLanguageOption2, LanguageNames.CSharp)); // 2. OptionSet validations. var newOptionSet = originalOptionSet.WithChangedOption(perLanguageOption, LanguageNames.CSharp, newValueCodeStyleOption); Assert.Equal(newValueCodeStyleOption, newOptionSet.GetOption(perLanguageOption, LanguageNames.CSharp)); Assert.Equal(newValueCodeStyleOption2, newOptionSet.GetOption(perLanguageOption2, LanguageNames.CSharp)); newOptionSet = originalOptionSet.WithChangedOption(perLanguageOption2, LanguageNames.CSharp, newValueCodeStyleOption2); Assert.Equal(newValueCodeStyleOption, newOptionSet.GetOption(perLanguageOption, LanguageNames.CSharp)); Assert.Equal(newValueCodeStyleOption2, newOptionSet.GetOption(perLanguageOption2, LanguageNames.CSharp)); // 3. IOptionService validation optionService.SetOptions(newOptionSet); Assert.Equal(newValueCodeStyleOption, optionService.GetOption(perLanguageOption, LanguageNames.CSharp)); Assert.Equal(newValueCodeStyleOption2, optionService.GetOption(perLanguageOption2, LanguageNames.CSharp)); } [Fact] public void TestLanguageSpecificCodeStyleOptions() { using var workspace = new AdhocWorkspace(); var option2 = new Option2<CodeStyleOption2<bool>>("test", "test", new CodeStyleOption2<bool>(false, NotificationOption2.Warning)); var option = option2.ToPublicOption(); var newValueCodeStyleOption2 = new CodeStyleOption2<bool>(!option2.DefaultValue.Value, option2.DefaultValue.Notification); var newValueCodeStyleOption = (CodeStyleOption<bool>)newValueCodeStyleOption2!; // Test "OptionKey" based overloads for get/set options on OptionSet and OptionService using different public and internal type combinations. // 1. { Option, CodeStyleOption } TestCodeStyleOptionsCommon(workspace, option, language: null, newValueCodeStyleOption); // 2. { Option2, CodeStyleOption } TestCodeStyleOptionsCommon(workspace, option2, language: null, newValueCodeStyleOption); // 3. { Option, CodeStyleOption2 } TestCodeStyleOptionsCommon(workspace, option, language: null, newValueCodeStyleOption2); // 4. { Option2, CodeStyleOption2 } TestCodeStyleOptionsCommon(workspace, option2, language: null, newValueCodeStyleOption2); var optionService = TestOptionService.GetService(workspace); var originalOptionSet = optionService.GetOptions(); // Test "Option" and "Option2" overloads for OptionSet and OptionService. // 1. Verify default value. Assert.Equal(option.DefaultValue, originalOptionSet.GetOption(option)); Assert.Equal(option2.DefaultValue, originalOptionSet.GetOption(option2)); // 2. OptionSet validations. var newOptionSet = originalOptionSet.WithChangedOption(option, newValueCodeStyleOption); Assert.Equal(newValueCodeStyleOption, newOptionSet.GetOption(option)); Assert.Equal(newValueCodeStyleOption2, newOptionSet.GetOption(option2)); newOptionSet = originalOptionSet.WithChangedOption(option2, newValueCodeStyleOption2); Assert.Equal(newValueCodeStyleOption, newOptionSet.GetOption(option)); Assert.Equal(newValueCodeStyleOption2, newOptionSet.GetOption(option2)); // 3. IOptionService validation optionService.SetOptions(newOptionSet); Assert.Equal(newValueCodeStyleOption, optionService.GetOption(option)); Assert.Equal(newValueCodeStyleOption2, optionService.GetOption(option2)); } private static void TestCodeStyleOptionsCommon<TCodeStyleOption>(Workspace workspace, IOption2 option, string? language, TCodeStyleOption newValue) where TCodeStyleOption : ICodeStyleOption { var optionService = TestOptionService.GetService(workspace); var originalOptionSet = optionService.GetOptions(); // Test matrix using different OptionKey and OptionKey2 get/set operations. var optionKey = new OptionKey(option, language); var optionKey2 = new OptionKey2(option, language); // Value return from "object GetOption(OptionKey)" should always be public CodeStyleOption type. var newPublicValue = newValue.AsPublicCodeStyleOption(); // 1. WithChangedOption(OptionKey), GetOption(OptionKey)/GetOption<T>(OptionKey) var newOptionSet = originalOptionSet.WithChangedOption(optionKey, newValue); Assert.Equal(newPublicValue, newOptionSet.GetOption(optionKey)); // Value returned from public API should always be castable to public CodeStyleOption type. Assert.NotNull((CodeStyleOption<bool>)newOptionSet.GetOption(optionKey)!); // Verify "T GetOption<T>(OptionKey)" works for both cases of T being a public and internal code style option type. Assert.Equal(newPublicValue, newOptionSet.GetOption<CodeStyleOption<bool>>(optionKey)); Assert.Equal(newValue, newOptionSet.GetOption<TCodeStyleOption>(optionKey)); // 2. WithChangedOption(OptionKey), GetOption(OptionKey2)/GetOption<T>(OptionKey2) newOptionSet = originalOptionSet.WithChangedOption(optionKey, newValue); Assert.Equal(newPublicValue, newOptionSet.GetOption(optionKey2)); // Verify "T GetOption<T>(OptionKey2)" works for both cases of T being a public and internal code style option type. Assert.Equal(newPublicValue, newOptionSet.GetOption<CodeStyleOption<bool>>(optionKey2)); Assert.Equal(newValue, newOptionSet.GetOption<TCodeStyleOption>(optionKey2)); // 3. WithChangedOption(OptionKey2), GetOption(OptionKey)/GetOption<T>(OptionKey) newOptionSet = originalOptionSet.WithChangedOption(optionKey2, newValue); Assert.Equal(newPublicValue, newOptionSet.GetOption(optionKey)); // Value returned from public API should always be castable to public CodeStyleOption type. Assert.NotNull((CodeStyleOption<bool>)newOptionSet.GetOption(optionKey)!); // Verify "T GetOption<T>(OptionKey)" works for both cases of T being a public and internal code style option type. Assert.Equal(newPublicValue, newOptionSet.GetOption<CodeStyleOption<bool>>(optionKey)); Assert.Equal(newValue, newOptionSet.GetOption<TCodeStyleOption>(optionKey)); // 4. WithChangedOption(OptionKey2), GetOption(OptionKey2)/GetOption<T>(OptionKey2) newOptionSet = originalOptionSet.WithChangedOption(optionKey2, newValue); Assert.Equal(newPublicValue, newOptionSet.GetOption(optionKey2)); // Verify "T GetOption<T>(OptionKey2)" works for both cases of T being a public and internal code style option type. Assert.Equal(newPublicValue, newOptionSet.GetOption<CodeStyleOption<bool>>(optionKey2)); Assert.Equal(newValue, newOptionSet.GetOption<TCodeStyleOption>(optionKey2)); // 5. IOptionService.GetOption(OptionKey) optionService.SetOptions(newOptionSet); Assert.Equal(newPublicValue, optionService.GetOption(optionKey)); } } }
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/VisualStudio/Core/Def/Implementation/ChangeSignature/ChangeSignatureDialogViewModel.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.Windows; using System.Windows.Controls; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.ChangeSignature; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.Text.Classification; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ChangeSignature { internal partial class ChangeSignatureDialogViewModel : AbstractNotifyPropertyChanged { private readonly IClassificationFormatMap _classificationFormatMap; private readonly ClassificationTypeMap _classificationTypeMap; private readonly INotificationService _notificationService; private readonly ParameterConfiguration _originalParameterConfiguration; // This can be changed to ParameterViewModel if we will allow adding 'this' parameter. private readonly ExistingParameterViewModel? _thisParameter; private readonly List<ParameterViewModel> _parametersWithoutDefaultValues; private readonly List<ParameterViewModel> _parametersWithDefaultValues; // This can be changed to ParameterViewModel if we will allow adding 'params' parameter. private readonly ExistingParameterViewModel? _paramsParameter; private readonly HashSet<ParameterViewModel> _disabledParameters = new(); private ImmutableArray<SymbolDisplayPart> _declarationParts; private bool _previewChanges; /// <summary> /// The document where the symbol we are changing signature is defined. /// </summary> private readonly Document _document; private readonly int _positionForTypeBinding; internal ChangeSignatureDialogViewModel( ParameterConfiguration parameters, ISymbol symbol, Document document, int positionForTypeBinding, IClassificationFormatMap classificationFormatMap, ClassificationTypeMap classificationTypeMap) { _originalParameterConfiguration = parameters; _document = document; _positionForTypeBinding = positionForTypeBinding; _classificationFormatMap = classificationFormatMap; _classificationTypeMap = classificationTypeMap; _notificationService = document.Project.Solution.Workspace.Services.GetRequiredService<INotificationService>(); // This index is displayed to users. That is why we start it from 1. var initialDisplayIndex = 1; if (parameters.ThisParameter != null) { _thisParameter = new ExistingParameterViewModel(this, parameters.ThisParameter, initialDisplayIndex++); _disabledParameters.Add(_thisParameter); } _declarationParts = symbol.ToDisplayParts(s_symbolDeclarationDisplayFormat); _parametersWithoutDefaultValues = CreateParameterViewModels(parameters.ParametersWithoutDefaultValues, ref initialDisplayIndex); _parametersWithDefaultValues = CreateParameterViewModels(parameters.RemainingEditableParameters, ref initialDisplayIndex); if (parameters.ParamsParameter != null) { _paramsParameter = new ExistingParameterViewModel(this, parameters.ParamsParameter, initialDisplayIndex++); } UpdateNameConflictMarkers(); var selectedIndex = parameters.SelectedIndex; // Currently, we do not support editing the ThisParameter. // Therefore, if there is such parameter, we should move the selectedIndex. if (parameters.ThisParameter != null && selectedIndex == 0) { // If we have at least one parameter after the ThisParameter, select the first one after This. // Otherwise, do not select anything. if (parameters.ParametersWithoutDefaultValues.Length + parameters.RemainingEditableParameters.Length > 0) { this.SelectedIndex = 1; } else { this.SelectedIndex = null; } } else { this.SelectedIndex = selectedIndex; } } private void UpdateNameConflictMarkers() { var parameterNameOverlapMap = new Dictionary<string, List<ParameterViewModel>>(); foreach (var parameter in AllParameters) { if (!parameter.IsRemoved) { parameterNameOverlapMap .GetOrAdd(parameter.ParameterName, _ => new List<ParameterViewModel>()) .Add(parameter); } else { parameter.HasParameterNameConflict = Visibility.Collapsed; } } foreach (var parameterName in parameterNameOverlapMap.Keys) { var matchingParameters = parameterNameOverlapMap[parameterName]; if (matchingParameters.Count > 1) { foreach (var matchingParameter in matchingParameters) { matchingParameter.HasParameterNameConflict = Visibility.Visible; } } else { matchingParameters.Single().HasParameterNameConflict = Visibility.Collapsed; } } NotifyPropertyChanged(nameof(AllParameters)); } public AddParameterDialogViewModel CreateAddParameterDialogViewModel() => new(_document, _positionForTypeBinding); private List<ParameterViewModel> CreateParameterViewModels(ImmutableArray<Parameter> parameters, ref int initialIndex) { var list = new List<ParameterViewModel>(); foreach (ExistingParameter existingParameter in parameters) { list.Add(new ExistingParameterViewModel(this, existingParameter, initialIndex)); initialIndex++; } return list; } public int GetStartingSelectionIndex() { if (_thisParameter == null) { return 0; } if (_parametersWithDefaultValues.Count + _parametersWithoutDefaultValues.Count > 0) { return 1; } return -1; } public bool PreviewChanges { get { return _previewChanges; } set { _previewChanges = value; } } public bool CanRemove { get { if (!EditableParameterSelected(out var index)) { return false; } return !AllParameters[index].IsRemoved; } } public bool CanRestore { get { if (!EditableParameterSelected(out var index)) { return false; } return AllParameters[index].IsRemoved; } } private bool EditableParameterSelected(out int index) { index = -1; if (!AllParameters.Any()) { return false; } if (!SelectedIndex.HasValue) { return false; } index = SelectedIndex.Value; if (index == 0 && _thisParameter != null) { return false; } return true; } internal void Remove() { if (AllParameters[_selectedIndex!.Value] is AddedParameterViewModel) { var parameterToRemove = AllParameters[_selectedIndex!.Value]; if (_parametersWithoutDefaultValues.Contains(parameterToRemove)) { _parametersWithoutDefaultValues.Remove(parameterToRemove); } else { _parametersWithDefaultValues.Remove(parameterToRemove); } } else { AllParameters[_selectedIndex!.Value].IsRemoved = true; } UpdateNameConflictMarkers(); RemoveRestoreNotifyPropertyChanged(); } internal void Restore() { AllParameters[_selectedIndex!.Value].IsRemoved = false; UpdateNameConflictMarkers(); RemoveRestoreNotifyPropertyChanged(); } internal void AddParameter(AddedParameter addedParameter) { if (addedParameter.IsRequired) { _parametersWithoutDefaultValues.Add(new AddedParameterViewModel(this, addedParameter)); } else { _parametersWithDefaultValues.Add(new AddedParameterViewModel(this, addedParameter)); } UpdateNameConflictMarkers(); RemoveRestoreNotifyPropertyChanged(); } internal void RemoveRestoreNotifyPropertyChanged() { NotifyPropertyChanged(nameof(AllParameters)); NotifyPropertyChanged(nameof(SignatureDisplay)); NotifyPropertyChanged(nameof(SignaturePreviewAutomationText)); NotifyPropertyChanged(nameof(CanRemove)); NotifyPropertyChanged(nameof(RemoveAutomationText)); NotifyPropertyChanged(nameof(CanRestore)); NotifyPropertyChanged(nameof(RestoreAutomationText)); } internal ParameterConfiguration GetParameterConfiguration() { return new ParameterConfiguration( _originalParameterConfiguration.ThisParameter, _parametersWithoutDefaultValues.Where(p => !p.IsRemoved).Select(p => p.Parameter).ToImmutableArray(), _parametersWithDefaultValues.Where(p => !p.IsRemoved).Select(p => p.Parameter).ToImmutableArray(), (_paramsParameter == null || _paramsParameter.IsRemoved) ? null : (ExistingParameter)_paramsParameter.Parameter, selectedIndex: -1); } private static readonly SymbolDisplayFormat s_symbolDeclarationDisplayFormat = new( genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier, extensionMethodStyle: SymbolDisplayExtensionMethodStyle.StaticMethod, memberOptions: SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeAccessibility | SymbolDisplayMemberOptions.IncludeModifiers | SymbolDisplayMemberOptions.IncludeRef); private static readonly SymbolDisplayFormat s_parameterDisplayFormat = new( genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier, parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeDefaultValue | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeName); public TextBlock SignatureDisplay { get { // TODO: Should probably use original syntax & formatting exactly instead of regenerating here var displayParts = GetSignatureDisplayParts(); var textBlock = displayParts.ToTaggedText().ToTextBlock(_classificationFormatMap, _classificationTypeMap); foreach (var inline in textBlock.Inlines) { inline.FontSize = 12; } textBlock.IsEnabled = false; return textBlock; } } public string SignaturePreviewAutomationText { get { return GetSignatureDisplayParts().Select(sdp => sdp.ToString()).Join(" "); } } internal string TEST_GetSignatureDisplayText() => GetSignatureDisplayParts().Select(p => p.ToString()).Join(""); private List<SymbolDisplayPart> GetSignatureDisplayParts() { var displayParts = new List<SymbolDisplayPart>(); displayParts.AddRange(_declarationParts); displayParts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, null, "(")); var first = true; foreach (var parameter in AllParameters.Where(p => !p.IsRemoved)) { if (!first) { displayParts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, null, ",")); displayParts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Space, null, " ")); } first = false; switch (parameter) { case ExistingParameterViewModel existingParameter: displayParts.AddRange(existingParameter.ParameterSymbol.ToDisplayParts(s_parameterDisplayFormat)); break; case AddedParameterViewModel addedParameterViewModel: var languageService = _document.GetRequiredLanguageService<IChangeSignatureViewModelFactoryService>(); displayParts.AddRange(languageService.GeneratePreviewDisplayParts(addedParameterViewModel)); break; default: throw ExceptionUtilities.UnexpectedValue(parameter.GetType().ToString()); } } displayParts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, null, ")")); return displayParts; } public List<ParameterViewModel> AllParameters { get { var list = new List<ParameterViewModel>(); if (_thisParameter != null) { list.Add(_thisParameter); } list.AddRange(_parametersWithoutDefaultValues); list.AddRange(_parametersWithDefaultValues); if (_paramsParameter != null) { list.Add(_paramsParameter); } return list; } } public bool CanMoveUp { get { if (!SelectedIndex.HasValue) { return false; } var index = SelectedIndex.Value; index = _thisParameter == null ? index : index - 1; if (index <= 0 || index == _parametersWithoutDefaultValues.Count || index >= _parametersWithoutDefaultValues.Count + _parametersWithDefaultValues.Count) { return false; } return true; } } public bool CanMoveDown { get { if (!SelectedIndex.HasValue) { return false; } var index = SelectedIndex.Value; index = _thisParameter == null ? index : index - 1; if (index < 0 || index == _parametersWithoutDefaultValues.Count - 1 || index >= _parametersWithoutDefaultValues.Count + _parametersWithDefaultValues.Count - 1) { return false; } return true; } } internal void MoveUp() { Debug.Assert(CanMoveUp); var index = SelectedIndex!.Value; index = _thisParameter == null ? index : index - 1; Move(index < _parametersWithoutDefaultValues.Count ? _parametersWithoutDefaultValues : _parametersWithDefaultValues, index < _parametersWithoutDefaultValues.Count ? index : index - _parametersWithoutDefaultValues.Count, delta: -1); } internal void MoveDown() { Debug.Assert(CanMoveDown); var index = SelectedIndex!.Value; index = _thisParameter == null ? index : index - 1; Move(index < _parametersWithoutDefaultValues.Count ? _parametersWithoutDefaultValues : _parametersWithDefaultValues, index < _parametersWithoutDefaultValues.Count ? index : index - _parametersWithoutDefaultValues.Count, delta: 1); } private void Move(List<ParameterViewModel> list, int index, int delta) { var param = list[index]; list.RemoveAt(index); list.Insert(index + delta, param); SelectedIndex += delta; NotifyPropertyChanged(nameof(AllParameters)); NotifyPropertyChanged(nameof(SignatureDisplay)); NotifyPropertyChanged(nameof(SignaturePreviewAutomationText)); } internal bool CanSubmit([NotNullWhen(false)] out string? message) { var canSubmit = AllParameters.Any(p => p.IsRemoved) || AllParameters.Any(p => p is AddedParameterViewModel) || !_parametersWithoutDefaultValues.OfType<ExistingParameterViewModel>().Select(p => p.ParameterSymbol).SequenceEqual(_originalParameterConfiguration.ParametersWithoutDefaultValues.Cast<ExistingParameter>().Select(p => p.Symbol)) || !_parametersWithDefaultValues.OfType<ExistingParameterViewModel>().Select(p => p.ParameterSymbol).SequenceEqual(_originalParameterConfiguration.RemainingEditableParameters.Cast<ExistingParameter>().Select(p => p.Symbol)); if (!canSubmit) { message = ServicesVSResources.You_must_change_the_signature; return false; } message = null; return true; } internal bool TrySubmit() { if (!CanSubmit(out var message)) { _notificationService.SendNotification(message, severity: NotificationSeverity.Information); return false; } return true; } private bool IsDisabled(ParameterViewModel parameterViewModel) { return _disabledParameters.Contains(parameterViewModel); } private int? _selectedIndex; public int? SelectedIndex { get { return _selectedIndex; } set { var newSelectedIndex = value == -1 ? null : value; if (newSelectedIndex == _selectedIndex) { return; } _selectedIndex = newSelectedIndex; NotifyPropertyChanged(nameof(CanMoveUp)); NotifyPropertyChanged(nameof(MoveUpAutomationText)); NotifyPropertyChanged(nameof(CanMoveDown)); NotifyPropertyChanged(nameof(MoveDownAutomationText)); NotifyPropertyChanged(nameof(CanRemove)); NotifyPropertyChanged(nameof(RemoveAutomationText)); NotifyPropertyChanged(nameof(CanRestore)); NotifyPropertyChanged(nameof(RestoreAutomationText)); } } public string MoveUpAutomationText { get { if (!CanMoveUp) { return string.Empty; } return string.Format(ServicesVSResources.Move_0_above_1, AllParameters[SelectedIndex!.Value].ShortAutomationText, AllParameters[SelectedIndex!.Value - 1].ShortAutomationText); } } public string MoveDownAutomationText { get { if (!CanMoveDown) { return string.Empty; } return string.Format(ServicesVSResources.Move_0_below_1, AllParameters[SelectedIndex!.Value].ShortAutomationText, AllParameters[SelectedIndex!.Value + 1].ShortAutomationText); } } public string RemoveAutomationText { get { if (!CanRemove) { return string.Empty; } return string.Format(ServicesVSResources.Remove_0, AllParameters[SelectedIndex!.Value].ShortAutomationText); } } public string RestoreAutomationText { get { if (!CanRestore) { return string.Empty; } return string.Format(ServicesVSResources.Restore_0, AllParameters[SelectedIndex!.Value].ShortAutomationText); } } } }
// Licensed to the .NET Foundation under one or more 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.Windows; using System.Windows.Controls; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.ChangeSignature; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.Text.Classification; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ChangeSignature { internal partial class ChangeSignatureDialogViewModel : AbstractNotifyPropertyChanged { private readonly IClassificationFormatMap _classificationFormatMap; private readonly ClassificationTypeMap _classificationTypeMap; private readonly INotificationService _notificationService; private readonly ParameterConfiguration _originalParameterConfiguration; // This can be changed to ParameterViewModel if we will allow adding 'this' parameter. private readonly ExistingParameterViewModel? _thisParameter; private readonly List<ParameterViewModel> _parametersWithoutDefaultValues; private readonly List<ParameterViewModel> _parametersWithDefaultValues; // This can be changed to ParameterViewModel if we will allow adding 'params' parameter. private readonly ExistingParameterViewModel? _paramsParameter; private readonly HashSet<ParameterViewModel> _disabledParameters = new(); private ImmutableArray<SymbolDisplayPart> _declarationParts; private bool _previewChanges; /// <summary> /// The document where the symbol we are changing signature is defined. /// </summary> private readonly Document _document; private readonly int _positionForTypeBinding; internal ChangeSignatureDialogViewModel( ParameterConfiguration parameters, ISymbol symbol, Document document, int positionForTypeBinding, IClassificationFormatMap classificationFormatMap, ClassificationTypeMap classificationTypeMap) { _originalParameterConfiguration = parameters; _document = document; _positionForTypeBinding = positionForTypeBinding; _classificationFormatMap = classificationFormatMap; _classificationTypeMap = classificationTypeMap; _notificationService = document.Project.Solution.Workspace.Services.GetRequiredService<INotificationService>(); // This index is displayed to users. That is why we start it from 1. var initialDisplayIndex = 1; if (parameters.ThisParameter != null) { _thisParameter = new ExistingParameterViewModel(this, parameters.ThisParameter, initialDisplayIndex++); _disabledParameters.Add(_thisParameter); } _declarationParts = symbol.ToDisplayParts(s_symbolDeclarationDisplayFormat); _parametersWithoutDefaultValues = CreateParameterViewModels(parameters.ParametersWithoutDefaultValues, ref initialDisplayIndex); _parametersWithDefaultValues = CreateParameterViewModels(parameters.RemainingEditableParameters, ref initialDisplayIndex); if (parameters.ParamsParameter != null) { _paramsParameter = new ExistingParameterViewModel(this, parameters.ParamsParameter, initialDisplayIndex++); } UpdateNameConflictMarkers(); var selectedIndex = parameters.SelectedIndex; // Currently, we do not support editing the ThisParameter. // Therefore, if there is such parameter, we should move the selectedIndex. if (parameters.ThisParameter != null && selectedIndex == 0) { // If we have at least one parameter after the ThisParameter, select the first one after This. // Otherwise, do not select anything. if (parameters.ParametersWithoutDefaultValues.Length + parameters.RemainingEditableParameters.Length > 0) { this.SelectedIndex = 1; } else { this.SelectedIndex = null; } } else { this.SelectedIndex = selectedIndex; } } private void UpdateNameConflictMarkers() { var parameterNameOverlapMap = new Dictionary<string, List<ParameterViewModel>>(); foreach (var parameter in AllParameters) { if (!parameter.IsRemoved) { parameterNameOverlapMap .GetOrAdd(parameter.ParameterName, _ => new List<ParameterViewModel>()) .Add(parameter); } else { parameter.HasParameterNameConflict = Visibility.Collapsed; } } foreach (var parameterName in parameterNameOverlapMap.Keys) { var matchingParameters = parameterNameOverlapMap[parameterName]; if (matchingParameters.Count > 1) { foreach (var matchingParameter in matchingParameters) { matchingParameter.HasParameterNameConflict = Visibility.Visible; } } else { matchingParameters.Single().HasParameterNameConflict = Visibility.Collapsed; } } NotifyPropertyChanged(nameof(AllParameters)); } public AddParameterDialogViewModel CreateAddParameterDialogViewModel() => new(_document, _positionForTypeBinding); private List<ParameterViewModel> CreateParameterViewModels(ImmutableArray<Parameter> parameters, ref int initialIndex) { var list = new List<ParameterViewModel>(); foreach (ExistingParameter existingParameter in parameters) { list.Add(new ExistingParameterViewModel(this, existingParameter, initialIndex)); initialIndex++; } return list; } public int GetStartingSelectionIndex() { if (_thisParameter == null) { return 0; } if (_parametersWithDefaultValues.Count + _parametersWithoutDefaultValues.Count > 0) { return 1; } return -1; } public bool PreviewChanges { get { return _previewChanges; } set { _previewChanges = value; } } public bool CanRemove { get { if (!EditableParameterSelected(out var index)) { return false; } return !AllParameters[index].IsRemoved; } } public bool CanRestore { get { if (!EditableParameterSelected(out var index)) { return false; } return AllParameters[index].IsRemoved; } } private bool EditableParameterSelected(out int index) { index = -1; if (!AllParameters.Any()) { return false; } if (!SelectedIndex.HasValue) { return false; } index = SelectedIndex.Value; if (index == 0 && _thisParameter != null) { return false; } return true; } internal void Remove() { if (AllParameters[_selectedIndex!.Value] is AddedParameterViewModel) { var parameterToRemove = AllParameters[_selectedIndex!.Value]; if (_parametersWithoutDefaultValues.Contains(parameterToRemove)) { _parametersWithoutDefaultValues.Remove(parameterToRemove); } else { _parametersWithDefaultValues.Remove(parameterToRemove); } } else { AllParameters[_selectedIndex!.Value].IsRemoved = true; } UpdateNameConflictMarkers(); RemoveRestoreNotifyPropertyChanged(); } internal void Restore() { AllParameters[_selectedIndex!.Value].IsRemoved = false; UpdateNameConflictMarkers(); RemoveRestoreNotifyPropertyChanged(); } internal void AddParameter(AddedParameter addedParameter) { if (addedParameter.IsRequired) { _parametersWithoutDefaultValues.Add(new AddedParameterViewModel(this, addedParameter)); } else { _parametersWithDefaultValues.Add(new AddedParameterViewModel(this, addedParameter)); } UpdateNameConflictMarkers(); RemoveRestoreNotifyPropertyChanged(); } internal void RemoveRestoreNotifyPropertyChanged() { NotifyPropertyChanged(nameof(AllParameters)); NotifyPropertyChanged(nameof(SignatureDisplay)); NotifyPropertyChanged(nameof(SignaturePreviewAutomationText)); NotifyPropertyChanged(nameof(CanRemove)); NotifyPropertyChanged(nameof(RemoveAutomationText)); NotifyPropertyChanged(nameof(CanRestore)); NotifyPropertyChanged(nameof(RestoreAutomationText)); } internal ParameterConfiguration GetParameterConfiguration() { return new ParameterConfiguration( _originalParameterConfiguration.ThisParameter, _parametersWithoutDefaultValues.Where(p => !p.IsRemoved).Select(p => p.Parameter).ToImmutableArray(), _parametersWithDefaultValues.Where(p => !p.IsRemoved).Select(p => p.Parameter).ToImmutableArray(), (_paramsParameter == null || _paramsParameter.IsRemoved) ? null : (ExistingParameter)_paramsParameter.Parameter, selectedIndex: -1); } private static readonly SymbolDisplayFormat s_symbolDeclarationDisplayFormat = new( genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier, extensionMethodStyle: SymbolDisplayExtensionMethodStyle.StaticMethod, memberOptions: SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeAccessibility | SymbolDisplayMemberOptions.IncludeModifiers | SymbolDisplayMemberOptions.IncludeRef); private static readonly SymbolDisplayFormat s_parameterDisplayFormat = new( genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier, parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeDefaultValue | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeName); public TextBlock SignatureDisplay { get { // TODO: Should probably use original syntax & formatting exactly instead of regenerating here var displayParts = GetSignatureDisplayParts(); var textBlock = displayParts.ToTaggedText().ToTextBlock(_classificationFormatMap, _classificationTypeMap); foreach (var inline in textBlock.Inlines) { inline.FontSize = 12; } textBlock.IsEnabled = false; return textBlock; } } public string SignaturePreviewAutomationText { get { return GetSignatureDisplayParts().Select(sdp => sdp.ToString()).Join(" "); } } internal string TEST_GetSignatureDisplayText() => GetSignatureDisplayParts().Select(p => p.ToString()).Join(""); private List<SymbolDisplayPart> GetSignatureDisplayParts() { var displayParts = new List<SymbolDisplayPart>(); displayParts.AddRange(_declarationParts); displayParts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, null, "(")); var first = true; foreach (var parameter in AllParameters.Where(p => !p.IsRemoved)) { if (!first) { displayParts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, null, ",")); displayParts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Space, null, " ")); } first = false; switch (parameter) { case ExistingParameterViewModel existingParameter: displayParts.AddRange(existingParameter.ParameterSymbol.ToDisplayParts(s_parameterDisplayFormat)); break; case AddedParameterViewModel addedParameterViewModel: var languageService = _document.GetRequiredLanguageService<IChangeSignatureViewModelFactoryService>(); displayParts.AddRange(languageService.GeneratePreviewDisplayParts(addedParameterViewModel)); break; default: throw ExceptionUtilities.UnexpectedValue(parameter.GetType().ToString()); } } displayParts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, null, ")")); return displayParts; } public List<ParameterViewModel> AllParameters { get { var list = new List<ParameterViewModel>(); if (_thisParameter != null) { list.Add(_thisParameter); } list.AddRange(_parametersWithoutDefaultValues); list.AddRange(_parametersWithDefaultValues); if (_paramsParameter != null) { list.Add(_paramsParameter); } return list; } } public bool CanMoveUp { get { if (!SelectedIndex.HasValue) { return false; } var index = SelectedIndex.Value; index = _thisParameter == null ? index : index - 1; if (index <= 0 || index == _parametersWithoutDefaultValues.Count || index >= _parametersWithoutDefaultValues.Count + _parametersWithDefaultValues.Count) { return false; } return true; } } public bool CanMoveDown { get { if (!SelectedIndex.HasValue) { return false; } var index = SelectedIndex.Value; index = _thisParameter == null ? index : index - 1; if (index < 0 || index == _parametersWithoutDefaultValues.Count - 1 || index >= _parametersWithoutDefaultValues.Count + _parametersWithDefaultValues.Count - 1) { return false; } return true; } } internal void MoveUp() { Debug.Assert(CanMoveUp); var index = SelectedIndex!.Value; index = _thisParameter == null ? index : index - 1; Move(index < _parametersWithoutDefaultValues.Count ? _parametersWithoutDefaultValues : _parametersWithDefaultValues, index < _parametersWithoutDefaultValues.Count ? index : index - _parametersWithoutDefaultValues.Count, delta: -1); } internal void MoveDown() { Debug.Assert(CanMoveDown); var index = SelectedIndex!.Value; index = _thisParameter == null ? index : index - 1; Move(index < _parametersWithoutDefaultValues.Count ? _parametersWithoutDefaultValues : _parametersWithDefaultValues, index < _parametersWithoutDefaultValues.Count ? index : index - _parametersWithoutDefaultValues.Count, delta: 1); } private void Move(List<ParameterViewModel> list, int index, int delta) { var param = list[index]; list.RemoveAt(index); list.Insert(index + delta, param); SelectedIndex += delta; NotifyPropertyChanged(nameof(AllParameters)); NotifyPropertyChanged(nameof(SignatureDisplay)); NotifyPropertyChanged(nameof(SignaturePreviewAutomationText)); } internal bool CanSubmit([NotNullWhen(false)] out string? message) { var canSubmit = AllParameters.Any(p => p.IsRemoved) || AllParameters.Any(p => p is AddedParameterViewModel) || !_parametersWithoutDefaultValues.OfType<ExistingParameterViewModel>().Select(p => p.ParameterSymbol).SequenceEqual(_originalParameterConfiguration.ParametersWithoutDefaultValues.Cast<ExistingParameter>().Select(p => p.Symbol)) || !_parametersWithDefaultValues.OfType<ExistingParameterViewModel>().Select(p => p.ParameterSymbol).SequenceEqual(_originalParameterConfiguration.RemainingEditableParameters.Cast<ExistingParameter>().Select(p => p.Symbol)); if (!canSubmit) { message = ServicesVSResources.You_must_change_the_signature; return false; } message = null; return true; } internal bool TrySubmit() { if (!CanSubmit(out var message)) { _notificationService.SendNotification(message, severity: NotificationSeverity.Information); return false; } return true; } private bool IsDisabled(ParameterViewModel parameterViewModel) { return _disabledParameters.Contains(parameterViewModel); } private int? _selectedIndex; public int? SelectedIndex { get { return _selectedIndex; } set { var newSelectedIndex = value == -1 ? null : value; if (newSelectedIndex == _selectedIndex) { return; } _selectedIndex = newSelectedIndex; NotifyPropertyChanged(nameof(CanMoveUp)); NotifyPropertyChanged(nameof(MoveUpAutomationText)); NotifyPropertyChanged(nameof(CanMoveDown)); NotifyPropertyChanged(nameof(MoveDownAutomationText)); NotifyPropertyChanged(nameof(CanRemove)); NotifyPropertyChanged(nameof(RemoveAutomationText)); NotifyPropertyChanged(nameof(CanRestore)); NotifyPropertyChanged(nameof(RestoreAutomationText)); } } public string MoveUpAutomationText { get { if (!CanMoveUp) { return string.Empty; } return string.Format(ServicesVSResources.Move_0_above_1, AllParameters[SelectedIndex!.Value].ShortAutomationText, AllParameters[SelectedIndex!.Value - 1].ShortAutomationText); } } public string MoveDownAutomationText { get { if (!CanMoveDown) { return string.Empty; } return string.Format(ServicesVSResources.Move_0_below_1, AllParameters[SelectedIndex!.Value].ShortAutomationText, AllParameters[SelectedIndex!.Value + 1].ShortAutomationText); } } public string RemoveAutomationText { get { if (!CanRemove) { return string.Empty; } return string.Format(ServicesVSResources.Remove_0, AllParameters[SelectedIndex!.Value].ShortAutomationText); } } public string RestoreAutomationText { get { if (!CanRestore) { return string.Empty; } return string.Format(ServicesVSResources.Restore_0, AllParameters[SelectedIndex!.Value].ShortAutomationText); } } } }
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/Workspaces/VisualBasic/Portable/Utilities/IntrinsicOperators/PredefinedCastExpressionDocumentation.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.VisualBasic.Utilities.IntrinsicOperators Friend NotInheritable Class PredefinedCastExpressionDocumentation Inherits AbstractIntrinsicOperatorDocumentation Private ReadOnly _resultingType As ITypeSymbol Private ReadOnly _keywordText As String Public Sub New(keywordKind As SyntaxKind, compilation As Compilation) _resultingType = compilation.GetTypeFromPredefinedCastKeyword(keywordKind) _keywordText = SyntaxFacts.GetText(keywordKind) End Sub Public Overrides ReadOnly Property DocumentationText As String Get Return String.Format(VBWorkspaceResources.Converts_an_expression_to_the_0_data_type, _resultingType.ToDisplayString()) End Get End Property Public Overrides Function GetParameterDocumentation(index As Integer) As String Select Case index Case 0 Return VBWorkspaceResources.The_expression_to_be_evaluated_and_converted Case Else Throw New ArgumentException(NameOf(index)) End Select End Function Public Overrides Function GetParameterName(index As Integer) As String Select Case index Case 0 Return VBWorkspaceResources.expression Case Else Throw New ArgumentException(NameOf(index)) End Select End Function Public Overrides ReadOnly Property IncludeAsType As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property ParameterCount As Integer Get Return 1 End Get End Property Public Overrides ReadOnly Property PrefixParts As IList(Of SymbolDisplayPart) Get Return {New SymbolDisplayPart(SymbolDisplayPartKind.Keyword, Nothing, _keywordText), New SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, Nothing, "(")} End Get End Property Public Overrides ReadOnly Property ReturnTypeMetadataName As String Get Return _resultingType.ContainingNamespace.Name + "." + _resultingType.MetadataName 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. Namespace Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators Friend NotInheritable Class PredefinedCastExpressionDocumentation Inherits AbstractIntrinsicOperatorDocumentation Private ReadOnly _resultingType As ITypeSymbol Private ReadOnly _keywordText As String Public Sub New(keywordKind As SyntaxKind, compilation As Compilation) _resultingType = compilation.GetTypeFromPredefinedCastKeyword(keywordKind) _keywordText = SyntaxFacts.GetText(keywordKind) End Sub Public Overrides ReadOnly Property DocumentationText As String Get Return String.Format(VBWorkspaceResources.Converts_an_expression_to_the_0_data_type, _resultingType.ToDisplayString()) End Get End Property Public Overrides Function GetParameterDocumentation(index As Integer) As String Select Case index Case 0 Return VBWorkspaceResources.The_expression_to_be_evaluated_and_converted Case Else Throw New ArgumentException(NameOf(index)) End Select End Function Public Overrides Function GetParameterName(index As Integer) As String Select Case index Case 0 Return VBWorkspaceResources.expression Case Else Throw New ArgumentException(NameOf(index)) End Select End Function Public Overrides ReadOnly Property IncludeAsType As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property ParameterCount As Integer Get Return 1 End Get End Property Public Overrides ReadOnly Property PrefixParts As IList(Of SymbolDisplayPart) Get Return {New SymbolDisplayPart(SymbolDisplayPartKind.Keyword, Nothing, _keywordText), New SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, Nothing, "(")} End Get End Property Public Overrides ReadOnly Property ReturnTypeMetadataName As String Get Return _resultingType.ContainingNamespace.Name + "." + _resultingType.MetadataName End Get End Property End Class End Namespace
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/VisualStudio/CSharp/Impl/CodeModel/CSharpCodeModelService.NodeLocator.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.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel { internal partial class CSharpCodeModelService { protected override AbstractNodeLocator CreateNodeLocator() => new NodeLocator(); private class NodeLocator : AbstractNodeLocator { protected override string LanguageName => LanguageNames.CSharp; protected override EnvDTE.vsCMPart DefaultPart => EnvDTE.vsCMPart.vsCMPartWholeWithAttributes; protected override VirtualTreePoint? GetStartPoint(SourceText text, OptionSet options, SyntaxNode node, EnvDTE.vsCMPart part) { switch (node.Kind()) { case SyntaxKind.ArrowExpressionClause: return GetStartPoint(text, (ArrowExpressionClauseSyntax)node, part); case SyntaxKind.Attribute: return GetStartPoint(text, (AttributeSyntax)node, part); case SyntaxKind.AttributeArgument: return GetStartPoint(text, (AttributeArgumentSyntax)node, part); case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: case SyntaxKind.EnumDeclaration: return GetStartPoint(text, (BaseTypeDeclarationSyntax)node, part); case SyntaxKind.MethodDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: return GetStartPoint(text, options, (BaseMethodDeclarationSyntax)node, part); case SyntaxKind.PropertyDeclaration: case SyntaxKind.IndexerDeclaration: case SyntaxKind.EventDeclaration: return GetStartPoint(text, options, (BasePropertyDeclarationSyntax)node, part); case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return GetStartPoint(text, options, (AccessorDeclarationSyntax)node, part); case SyntaxKind.DelegateDeclaration: return GetStartPoint(text, (DelegateDeclarationSyntax)node, part); case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return GetStartPoint(text, (BaseNamespaceDeclarationSyntax)node, part); case SyntaxKind.UsingDirective: return GetStartPoint(text, (UsingDirectiveSyntax)node, part); case SyntaxKind.EnumMemberDeclaration: return GetStartPoint(text, (EnumMemberDeclarationSyntax)node, part); case SyntaxKind.VariableDeclarator: return GetStartPoint(text, (VariableDeclaratorSyntax)node, part); case SyntaxKind.Parameter: return GetStartPoint(text, (ParameterSyntax)node, part); default: Debug.Fail("Unsupported node kind: " + node.Kind()); throw new NotSupportedException(); } } protected override VirtualTreePoint? GetEndPoint(SourceText text, OptionSet options, SyntaxNode node, EnvDTE.vsCMPart part) { switch (node.Kind()) { case SyntaxKind.ArrowExpressionClause: return GetEndPoint(text, (ArrowExpressionClauseSyntax)node, part); case SyntaxKind.Attribute: return GetEndPoint(text, (AttributeSyntax)node, part); case SyntaxKind.AttributeArgument: return GetEndPoint(text, (AttributeArgumentSyntax)node, part); case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: case SyntaxKind.EnumDeclaration: return GetEndPoint(text, (BaseTypeDeclarationSyntax)node, part); case SyntaxKind.MethodDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: return GetEndPoint(text, (BaseMethodDeclarationSyntax)node, part); case SyntaxKind.PropertyDeclaration: case SyntaxKind.IndexerDeclaration: case SyntaxKind.EventDeclaration: return GetEndPoint(text, (BasePropertyDeclarationSyntax)node, part); case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return GetEndPoint(text, (AccessorDeclarationSyntax)node, part); case SyntaxKind.DelegateDeclaration: return GetEndPoint(text, (DelegateDeclarationSyntax)node, part); case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return GetEndPoint(text, (BaseNamespaceDeclarationSyntax)node, part); case SyntaxKind.UsingDirective: return GetEndPoint(text, (UsingDirectiveSyntax)node, part); case SyntaxKind.EnumMemberDeclaration: return GetEndPoint(text, (EnumMemberDeclarationSyntax)node, part); case SyntaxKind.VariableDeclarator: return GetEndPoint(text, (VariableDeclaratorSyntax)node, part); case SyntaxKind.Parameter: return GetEndPoint(text, (ParameterSyntax)node, part); default: Debug.Fail("Unsupported node kind: " + node.Kind()); throw new NotSupportedException(); } } private VirtualTreePoint GetBodyStartPoint(SourceText text, SyntaxToken openBrace) { Debug.Assert(!openBrace.IsMissing); var openBraceLine = text.Lines.GetLineFromPosition(openBrace.Span.End); var textAfterBrace = text.ToString(TextSpan.FromBounds(openBrace.Span.End, openBraceLine.End)); return string.IsNullOrWhiteSpace(textAfterBrace) ? new VirtualTreePoint(openBrace.SyntaxTree, text, text.Lines[openBraceLine.LineNumber + 1].Start) : new VirtualTreePoint(openBrace.SyntaxTree, text, openBrace.Span.End); } private VirtualTreePoint GetBodyStartPoint(SourceText text, OptionSet options, SyntaxToken openBrace, SyntaxToken closeBrace, int memberStartColumn) { Debug.Assert(!openBrace.IsMissing); Debug.Assert(!closeBrace.IsMissing); Debug.Assert(memberStartColumn >= 0); var openBraceLine = text.Lines.GetLineFromPosition(openBrace.SpanStart); var closeBraceLine = text.Lines.GetLineFromPosition(closeBrace.SpanStart); var tokenAfterOpenBrace = openBrace.GetNextToken(); var nextPosition = tokenAfterOpenBrace.SpanStart; // We need to check if there is any significant trivia trailing this token or leading // to the next token. This accounts for the fact that comments were included in the token // stream in Dev10. var significantTrivia = openBrace.GetAllTrailingTrivia() .Where(t => !t.MatchesKind(SyntaxKind.WhitespaceTrivia, SyntaxKind.EndOfLineTrivia)) .FirstOrDefault(); if (significantTrivia.Kind() != SyntaxKind.None) { nextPosition = significantTrivia.SpanStart; } // If the opening and closing curlies are at least two lines apart then place the cursor // on the next line provided that there isn't any token on the line with the open curly. if (openBraceLine.LineNumber + 1 < closeBraceLine.LineNumber && openBraceLine.LineNumber < text.Lines.IndexOf(tokenAfterOpenBrace.SpanStart)) { var lineAfterOpenBrace = text.Lines[openBraceLine.LineNumber + 1]; var firstNonWhitespaceOffset = lineAfterOpenBrace.GetFirstNonWhitespaceOffset() ?? -1; // If the line contains any text, we return the start of the first non-whitespace character. if (firstNonWhitespaceOffset >= 0) { return new VirtualTreePoint(openBrace.SyntaxTree, text, lineAfterOpenBrace.Start + firstNonWhitespaceOffset); } // If the line is all whitespace then place the caret at the first indent after the start // of the member. var indentSize = GetTabSize(options); var lineText = lineAfterOpenBrace.ToString(); var lineEndColumn = lineText.GetColumnFromLineOffset(lineText.Length, indentSize); var indentColumn = memberStartColumn + indentSize; var virtualSpaces = indentColumn - lineEndColumn; return new VirtualTreePoint(openBrace.SyntaxTree, text, lineAfterOpenBrace.End, virtualSpaces); } else { // If the body is empty then place it after the open brace; otherwise, place // at the start of the first token after the open curly. if (closeBrace.SpanStart == nextPosition) { return new VirtualTreePoint(openBrace.SyntaxTree, text, openBrace.Span.End); } else { return new VirtualTreePoint(openBrace.SyntaxTree, text, nextPosition); } } } private VirtualTreePoint GetBodyEndPoint(SourceText text, SyntaxToken closeBrace) { var closeBraceLine = text.Lines.GetLineFromPosition(closeBrace.SpanStart); var textBeforeBrace = text.ToString(TextSpan.FromBounds(closeBraceLine.Start, closeBrace.SpanStart)); return string.IsNullOrWhiteSpace(textBeforeBrace) ? new VirtualTreePoint(closeBrace.SyntaxTree, text, closeBraceLine.Start) : new VirtualTreePoint(closeBrace.SyntaxTree, text, closeBrace.SpanStart); } private VirtualTreePoint GetStartPoint(SourceText text, ArrowExpressionClauseSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartWhole: startPosition = node.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartBody: startPosition = node.Expression.SpanStart; break; default: throw Exceptions.ThrowENotImpl(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, AttributeSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.GetFirstToken().SpanStart; break; case EnvDTE.vsCMPart.vsCMPartNavigate: startPosition = node.Name.SpanStart; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, AttributeArgumentSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: case EnvDTE.vsCMPart.vsCMPartBody: case EnvDTE.vsCMPart.vsCMPartNavigate: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.SpanStart; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, BaseTypeDeclarationSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartHeader: startPosition = node.GetFirstTokenAfterAttributes().SpanStart; break; case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.GetFirstToken().SpanStart; break; case EnvDTE.vsCMPart.vsCMPartNavigate: startPosition = node.Identifier.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartBody: if (node.OpenBraceToken.IsMissing || node.CloseBraceToken.IsMissing) { throw Exceptions.ThrowEFail(); } return GetBodyStartPoint(text, node.OpenBraceToken); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, OptionSet options, BaseMethodDeclarationSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartHeader: startPosition = node.GetFirstTokenAfterAttributes().SpanStart; break; case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.GetFirstToken().SpanStart; break; case EnvDTE.vsCMPart.vsCMPartNavigate: if (node.Body != null && !node.Body.OpenBraceToken.IsMissing) { var line = text.Lines.GetLineFromPosition(node.SpanStart); var indentation = line.GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(GetTabSize(options)); return GetBodyStartPoint(text, options, node.Body.OpenBraceToken, node.Body.CloseBraceToken, indentation); } else { switch (node.Kind()) { case SyntaxKind.MethodDeclaration: startPosition = ((MethodDeclarationSyntax)node).Identifier.SpanStart; break; case SyntaxKind.ConstructorDeclaration: startPosition = ((ConstructorDeclarationSyntax)node).Identifier.SpanStart; break; case SyntaxKind.DestructorDeclaration: startPosition = ((DestructorDeclarationSyntax)node).Identifier.SpanStart; break; case SyntaxKind.ConversionOperatorDeclaration: startPosition = ((ConversionOperatorDeclarationSyntax)node).ImplicitOrExplicitKeyword.SpanStart; break; case SyntaxKind.OperatorDeclaration: startPosition = ((OperatorDeclarationSyntax)node).OperatorToken.SpanStart; break; default: startPosition = node.GetFirstTokenAfterAttributes().SpanStart; break; } } break; case EnvDTE.vsCMPart.vsCMPartBody: if (node.Body == null || node.Body.OpenBraceToken.IsMissing || node.Body.CloseBraceToken.IsMissing) { throw Exceptions.ThrowEFail(); } return GetBodyStartPoint(text, node.Body.OpenBraceToken); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private AccessorDeclarationSyntax FindFirstAccessorNode(BasePropertyDeclarationSyntax node) { if (node.AccessorList == null) { return null; } return node.AccessorList.Accessors.FirstOrDefault(); } private VirtualTreePoint GetStartPoint(SourceText text, OptionSet options, BasePropertyDeclarationSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartNavigate: var firstAccessorNode = FindFirstAccessorNode(node); if (firstAccessorNode != null) { var line = text.Lines.GetLineFromPosition(firstAccessorNode.SpanStart); var indentation = line.GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(GetTabSize(options)); if (firstAccessorNode.Body != null) { return GetBodyStartPoint(text, options, firstAccessorNode.Body.OpenBraceToken, firstAccessorNode.Body.CloseBraceToken, indentation); } else if (!firstAccessorNode.SemicolonToken.IsMissing) { // This is total weirdness from the old C# code model with auto props. // If there isn't a body, the semi-colon is used return GetBodyStartPoint(text, options, firstAccessorNode.SemicolonToken, firstAccessorNode.SemicolonToken, indentation); } } throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartBody: if (node.AccessorList != null && !node.AccessorList.OpenBraceToken.IsMissing) { var line = text.Lines.GetLineFromPosition(node.SpanStart); var indentation = line.GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(GetTabSize(options)); return GetBodyStartPoint(text, options, node.AccessorList.OpenBraceToken, node.AccessorList.CloseBraceToken, indentation); } throw Exceptions.ThrowEFail(); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, OptionSet options, AccessorDeclarationSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartNavigate: if (node.Body != null && !node.Body.OpenBraceToken.IsMissing) { var line = text.Lines.GetLineFromPosition(node.SpanStart); var indentation = line.GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(GetTabSize(options)); return GetBodyStartPoint(text, options, node.Body.OpenBraceToken, node.Body.CloseBraceToken, indentation); } throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartBody: if (node.Body == null || node.Body.OpenBraceToken.IsMissing || node.Body.CloseBraceToken.IsMissing) { throw Exceptions.ThrowEFail(); } return GetBodyStartPoint(text, node.Body.OpenBraceToken); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, BaseNamespaceDeclarationSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.GetFirstToken().SpanStart; break; case EnvDTE.vsCMPart.vsCMPartNavigate: startPosition = node.Name.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartBody: if (node is NamespaceDeclarationSyntax namespaceDeclaration) { if (namespaceDeclaration.OpenBraceToken.IsMissing || namespaceDeclaration.CloseBraceToken.IsMissing) throw Exceptions.ThrowEFail(); return GetBodyStartPoint(text, namespaceDeclaration.OpenBraceToken); } else if (node is FileScopedNamespaceDeclarationSyntax fileScopedNamespace) { return GetBodyStartPoint(text, fileScopedNamespace.SemicolonToken); } else { throw Exceptions.ThrowEFail(); } default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, DelegateDeclarationSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.GetFirstToken().SpanStart; break; case EnvDTE.vsCMPart.vsCMPartNavigate: startPosition = node.Identifier.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, UsingDirectiveSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartNavigate: startPosition = node.Name.SpanStart; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, VariableDeclaratorSyntax node, EnvDTE.vsCMPart part) { var field = node.FirstAncestorOrSelf<BaseFieldDeclarationSyntax>(); int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (field.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = field.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartNavigate: startPosition = node.Identifier.SpanStart; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, EnumMemberDeclarationSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartNavigate: startPosition = node.Identifier.SpanStart; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, ParameterSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartNavigate: startPosition = node.Identifier.SpanStart; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetEndPoint(SourceText text, ArrowExpressionClauseSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBody: endPosition = node.Span.End; break; default: throw Exceptions.ThrowENotImpl(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, AttributeSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartNavigate: endPosition = node.Name.Span.End; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, AttributeArgumentSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: case EnvDTE.vsCMPart.vsCMPartBody: case EnvDTE.vsCMPart.vsCMPartNavigate: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, BaseTypeDeclarationSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } endPosition = node.AttributeLists.Last().GetLastToken().Span.End; break; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartNavigate: endPosition = node.Identifier.Span.End; break; case EnvDTE.vsCMPart.vsCMPartBody: return GetBodyEndPoint(text, node.CloseBraceToken); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, BaseMethodDeclarationSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } endPosition = node.AttributeLists.Last().GetLastToken().Span.End; break; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartNavigate: if (node.Body != null && !node.Body.CloseBraceToken.IsMissing) { return GetBodyEndPoint(text, node.Body.CloseBraceToken); } else { switch (node.Kind()) { case SyntaxKind.MethodDeclaration: endPosition = ((MethodDeclarationSyntax)node).Identifier.Span.End; break; case SyntaxKind.ConstructorDeclaration: endPosition = ((ConstructorDeclarationSyntax)node).Identifier.Span.End; break; case SyntaxKind.DestructorDeclaration: endPosition = ((DestructorDeclarationSyntax)node).Identifier.Span.End; break; case SyntaxKind.ConversionOperatorDeclaration: endPosition = ((ConversionOperatorDeclarationSyntax)node).ImplicitOrExplicitKeyword.Span.End; break; case SyntaxKind.OperatorDeclaration: endPosition = ((OperatorDeclarationSyntax)node).OperatorToken.Span.End; break; default: endPosition = node.GetFirstTokenAfterAttributes().Span.End; break; } } break; case EnvDTE.vsCMPart.vsCMPartBody: if (node.Body == null || node.Body.OpenBraceToken.IsMissing || node.Body.CloseBraceToken.IsMissing) { throw Exceptions.ThrowEFail(); } return GetBodyEndPoint(text, node.Body.CloseBraceToken); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, BasePropertyDeclarationSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } endPosition = node.AttributeLists.Last().Span.End; break; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartNavigate: var firstAccessorNode = FindFirstAccessorNode(node); if (firstAccessorNode != null) { if (firstAccessorNode.Body != null) { return GetBodyEndPoint(text, firstAccessorNode.Body.CloseBraceToken); } else { // This is total weirdness from the old C# code model with auto props. // If there isn't a body, the semi-colon is used return GetBodyEndPoint(text, firstAccessorNode.SemicolonToken); } } throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartBody: if (node.AccessorList != null && !node.AccessorList.CloseBraceToken.IsMissing) { return GetBodyEndPoint(text, node.AccessorList.CloseBraceToken); } throw Exceptions.ThrowEFail(); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, AccessorDeclarationSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartBody: case EnvDTE.vsCMPart.vsCMPartNavigate: if (node.Body == null || node.Body.OpenBraceToken.IsMissing || node.Body.CloseBraceToken.IsMissing) { throw Exceptions.ThrowEFail(); } return GetBodyEndPoint(text, node.Body.CloseBraceToken); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, DelegateDeclarationSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } endPosition = node.AttributeLists.Last().Span.End; break; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartNavigate: endPosition = node.Identifier.Span.End; break; case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, BaseNamespaceDeclarationSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartNavigate: endPosition = node.Name.Span.End; break; case EnvDTE.vsCMPart.vsCMPartBody: if (node is NamespaceDeclarationSyntax namespaceDeclaration) { if (namespaceDeclaration.OpenBraceToken.IsMissing || namespaceDeclaration.CloseBraceToken.IsMissing) throw Exceptions.ThrowEFail(); return GetBodyEndPoint(text, namespaceDeclaration.CloseBraceToken); } else if (node is FileScopedNamespaceDeclarationSyntax fileScopedNamespace) { return new VirtualTreePoint(fileScopedNamespace.SyntaxTree, text, fileScopedNamespace.Parent.Span.End); } else { throw Exceptions.ThrowEFail(); } default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, UsingDirectiveSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartNavigate: endPosition = node.Name.Span.End; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, EnumMemberDeclarationSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } endPosition = node.AttributeLists.Last().GetLastToken().Span.End; break; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartNavigate: endPosition = node.Identifier.Span.End; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, VariableDeclaratorSyntax node, EnvDTE.vsCMPart part) { var field = node.FirstAncestorOrSelf<BaseFieldDeclarationSyntax>(); int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (field.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } endPosition = field.AttributeLists.Last().GetLastToken().Span.End; break; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = field.Span.End; break; case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartNavigate: endPosition = node.Identifier.Span.End; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, ParameterSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } endPosition = node.AttributeLists.Last().GetLastToken().Span.End; break; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartNavigate: endPosition = node.Identifier.Span.End; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel { internal partial class CSharpCodeModelService { protected override AbstractNodeLocator CreateNodeLocator() => new NodeLocator(); private class NodeLocator : AbstractNodeLocator { protected override string LanguageName => LanguageNames.CSharp; protected override EnvDTE.vsCMPart DefaultPart => EnvDTE.vsCMPart.vsCMPartWholeWithAttributes; protected override VirtualTreePoint? GetStartPoint(SourceText text, OptionSet options, SyntaxNode node, EnvDTE.vsCMPart part) { switch (node.Kind()) { case SyntaxKind.ArrowExpressionClause: return GetStartPoint(text, (ArrowExpressionClauseSyntax)node, part); case SyntaxKind.Attribute: return GetStartPoint(text, (AttributeSyntax)node, part); case SyntaxKind.AttributeArgument: return GetStartPoint(text, (AttributeArgumentSyntax)node, part); case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: case SyntaxKind.EnumDeclaration: return GetStartPoint(text, (BaseTypeDeclarationSyntax)node, part); case SyntaxKind.MethodDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: return GetStartPoint(text, options, (BaseMethodDeclarationSyntax)node, part); case SyntaxKind.PropertyDeclaration: case SyntaxKind.IndexerDeclaration: case SyntaxKind.EventDeclaration: return GetStartPoint(text, options, (BasePropertyDeclarationSyntax)node, part); case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return GetStartPoint(text, options, (AccessorDeclarationSyntax)node, part); case SyntaxKind.DelegateDeclaration: return GetStartPoint(text, (DelegateDeclarationSyntax)node, part); case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return GetStartPoint(text, (BaseNamespaceDeclarationSyntax)node, part); case SyntaxKind.UsingDirective: return GetStartPoint(text, (UsingDirectiveSyntax)node, part); case SyntaxKind.EnumMemberDeclaration: return GetStartPoint(text, (EnumMemberDeclarationSyntax)node, part); case SyntaxKind.VariableDeclarator: return GetStartPoint(text, (VariableDeclaratorSyntax)node, part); case SyntaxKind.Parameter: return GetStartPoint(text, (ParameterSyntax)node, part); default: Debug.Fail("Unsupported node kind: " + node.Kind()); throw new NotSupportedException(); } } protected override VirtualTreePoint? GetEndPoint(SourceText text, OptionSet options, SyntaxNode node, EnvDTE.vsCMPart part) { switch (node.Kind()) { case SyntaxKind.ArrowExpressionClause: return GetEndPoint(text, (ArrowExpressionClauseSyntax)node, part); case SyntaxKind.Attribute: return GetEndPoint(text, (AttributeSyntax)node, part); case SyntaxKind.AttributeArgument: return GetEndPoint(text, (AttributeArgumentSyntax)node, part); case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: case SyntaxKind.EnumDeclaration: return GetEndPoint(text, (BaseTypeDeclarationSyntax)node, part); case SyntaxKind.MethodDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: return GetEndPoint(text, (BaseMethodDeclarationSyntax)node, part); case SyntaxKind.PropertyDeclaration: case SyntaxKind.IndexerDeclaration: case SyntaxKind.EventDeclaration: return GetEndPoint(text, (BasePropertyDeclarationSyntax)node, part); case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return GetEndPoint(text, (AccessorDeclarationSyntax)node, part); case SyntaxKind.DelegateDeclaration: return GetEndPoint(text, (DelegateDeclarationSyntax)node, part); case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return GetEndPoint(text, (BaseNamespaceDeclarationSyntax)node, part); case SyntaxKind.UsingDirective: return GetEndPoint(text, (UsingDirectiveSyntax)node, part); case SyntaxKind.EnumMemberDeclaration: return GetEndPoint(text, (EnumMemberDeclarationSyntax)node, part); case SyntaxKind.VariableDeclarator: return GetEndPoint(text, (VariableDeclaratorSyntax)node, part); case SyntaxKind.Parameter: return GetEndPoint(text, (ParameterSyntax)node, part); default: Debug.Fail("Unsupported node kind: " + node.Kind()); throw new NotSupportedException(); } } private VirtualTreePoint GetBodyStartPoint(SourceText text, SyntaxToken openBrace) { Debug.Assert(!openBrace.IsMissing); var openBraceLine = text.Lines.GetLineFromPosition(openBrace.Span.End); var textAfterBrace = text.ToString(TextSpan.FromBounds(openBrace.Span.End, openBraceLine.End)); return string.IsNullOrWhiteSpace(textAfterBrace) ? new VirtualTreePoint(openBrace.SyntaxTree, text, text.Lines[openBraceLine.LineNumber + 1].Start) : new VirtualTreePoint(openBrace.SyntaxTree, text, openBrace.Span.End); } private VirtualTreePoint GetBodyStartPoint(SourceText text, OptionSet options, SyntaxToken openBrace, SyntaxToken closeBrace, int memberStartColumn) { Debug.Assert(!openBrace.IsMissing); Debug.Assert(!closeBrace.IsMissing); Debug.Assert(memberStartColumn >= 0); var openBraceLine = text.Lines.GetLineFromPosition(openBrace.SpanStart); var closeBraceLine = text.Lines.GetLineFromPosition(closeBrace.SpanStart); var tokenAfterOpenBrace = openBrace.GetNextToken(); var nextPosition = tokenAfterOpenBrace.SpanStart; // We need to check if there is any significant trivia trailing this token or leading // to the next token. This accounts for the fact that comments were included in the token // stream in Dev10. var significantTrivia = openBrace.GetAllTrailingTrivia() .Where(t => !t.MatchesKind(SyntaxKind.WhitespaceTrivia, SyntaxKind.EndOfLineTrivia)) .FirstOrDefault(); if (significantTrivia.Kind() != SyntaxKind.None) { nextPosition = significantTrivia.SpanStart; } // If the opening and closing curlies are at least two lines apart then place the cursor // on the next line provided that there isn't any token on the line with the open curly. if (openBraceLine.LineNumber + 1 < closeBraceLine.LineNumber && openBraceLine.LineNumber < text.Lines.IndexOf(tokenAfterOpenBrace.SpanStart)) { var lineAfterOpenBrace = text.Lines[openBraceLine.LineNumber + 1]; var firstNonWhitespaceOffset = lineAfterOpenBrace.GetFirstNonWhitespaceOffset() ?? -1; // If the line contains any text, we return the start of the first non-whitespace character. if (firstNonWhitespaceOffset >= 0) { return new VirtualTreePoint(openBrace.SyntaxTree, text, lineAfterOpenBrace.Start + firstNonWhitespaceOffset); } // If the line is all whitespace then place the caret at the first indent after the start // of the member. var indentSize = GetTabSize(options); var lineText = lineAfterOpenBrace.ToString(); var lineEndColumn = lineText.GetColumnFromLineOffset(lineText.Length, indentSize); var indentColumn = memberStartColumn + indentSize; var virtualSpaces = indentColumn - lineEndColumn; return new VirtualTreePoint(openBrace.SyntaxTree, text, lineAfterOpenBrace.End, virtualSpaces); } else { // If the body is empty then place it after the open brace; otherwise, place // at the start of the first token after the open curly. if (closeBrace.SpanStart == nextPosition) { return new VirtualTreePoint(openBrace.SyntaxTree, text, openBrace.Span.End); } else { return new VirtualTreePoint(openBrace.SyntaxTree, text, nextPosition); } } } private VirtualTreePoint GetBodyEndPoint(SourceText text, SyntaxToken closeBrace) { var closeBraceLine = text.Lines.GetLineFromPosition(closeBrace.SpanStart); var textBeforeBrace = text.ToString(TextSpan.FromBounds(closeBraceLine.Start, closeBrace.SpanStart)); return string.IsNullOrWhiteSpace(textBeforeBrace) ? new VirtualTreePoint(closeBrace.SyntaxTree, text, closeBraceLine.Start) : new VirtualTreePoint(closeBrace.SyntaxTree, text, closeBrace.SpanStart); } private VirtualTreePoint GetStartPoint(SourceText text, ArrowExpressionClauseSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartWhole: startPosition = node.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartBody: startPosition = node.Expression.SpanStart; break; default: throw Exceptions.ThrowENotImpl(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, AttributeSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.GetFirstToken().SpanStart; break; case EnvDTE.vsCMPart.vsCMPartNavigate: startPosition = node.Name.SpanStart; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, AttributeArgumentSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: case EnvDTE.vsCMPart.vsCMPartBody: case EnvDTE.vsCMPart.vsCMPartNavigate: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.SpanStart; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, BaseTypeDeclarationSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartHeader: startPosition = node.GetFirstTokenAfterAttributes().SpanStart; break; case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.GetFirstToken().SpanStart; break; case EnvDTE.vsCMPart.vsCMPartNavigate: startPosition = node.Identifier.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartBody: if (node.OpenBraceToken.IsMissing || node.CloseBraceToken.IsMissing) { throw Exceptions.ThrowEFail(); } return GetBodyStartPoint(text, node.OpenBraceToken); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, OptionSet options, BaseMethodDeclarationSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartHeader: startPosition = node.GetFirstTokenAfterAttributes().SpanStart; break; case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.GetFirstToken().SpanStart; break; case EnvDTE.vsCMPart.vsCMPartNavigate: if (node.Body != null && !node.Body.OpenBraceToken.IsMissing) { var line = text.Lines.GetLineFromPosition(node.SpanStart); var indentation = line.GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(GetTabSize(options)); return GetBodyStartPoint(text, options, node.Body.OpenBraceToken, node.Body.CloseBraceToken, indentation); } else { switch (node.Kind()) { case SyntaxKind.MethodDeclaration: startPosition = ((MethodDeclarationSyntax)node).Identifier.SpanStart; break; case SyntaxKind.ConstructorDeclaration: startPosition = ((ConstructorDeclarationSyntax)node).Identifier.SpanStart; break; case SyntaxKind.DestructorDeclaration: startPosition = ((DestructorDeclarationSyntax)node).Identifier.SpanStart; break; case SyntaxKind.ConversionOperatorDeclaration: startPosition = ((ConversionOperatorDeclarationSyntax)node).ImplicitOrExplicitKeyword.SpanStart; break; case SyntaxKind.OperatorDeclaration: startPosition = ((OperatorDeclarationSyntax)node).OperatorToken.SpanStart; break; default: startPosition = node.GetFirstTokenAfterAttributes().SpanStart; break; } } break; case EnvDTE.vsCMPart.vsCMPartBody: if (node.Body == null || node.Body.OpenBraceToken.IsMissing || node.Body.CloseBraceToken.IsMissing) { throw Exceptions.ThrowEFail(); } return GetBodyStartPoint(text, node.Body.OpenBraceToken); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private AccessorDeclarationSyntax FindFirstAccessorNode(BasePropertyDeclarationSyntax node) { if (node.AccessorList == null) { return null; } return node.AccessorList.Accessors.FirstOrDefault(); } private VirtualTreePoint GetStartPoint(SourceText text, OptionSet options, BasePropertyDeclarationSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartNavigate: var firstAccessorNode = FindFirstAccessorNode(node); if (firstAccessorNode != null) { var line = text.Lines.GetLineFromPosition(firstAccessorNode.SpanStart); var indentation = line.GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(GetTabSize(options)); if (firstAccessorNode.Body != null) { return GetBodyStartPoint(text, options, firstAccessorNode.Body.OpenBraceToken, firstAccessorNode.Body.CloseBraceToken, indentation); } else if (!firstAccessorNode.SemicolonToken.IsMissing) { // This is total weirdness from the old C# code model with auto props. // If there isn't a body, the semi-colon is used return GetBodyStartPoint(text, options, firstAccessorNode.SemicolonToken, firstAccessorNode.SemicolonToken, indentation); } } throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartBody: if (node.AccessorList != null && !node.AccessorList.OpenBraceToken.IsMissing) { var line = text.Lines.GetLineFromPosition(node.SpanStart); var indentation = line.GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(GetTabSize(options)); return GetBodyStartPoint(text, options, node.AccessorList.OpenBraceToken, node.AccessorList.CloseBraceToken, indentation); } throw Exceptions.ThrowEFail(); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, OptionSet options, AccessorDeclarationSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartNavigate: if (node.Body != null && !node.Body.OpenBraceToken.IsMissing) { var line = text.Lines.GetLineFromPosition(node.SpanStart); var indentation = line.GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(GetTabSize(options)); return GetBodyStartPoint(text, options, node.Body.OpenBraceToken, node.Body.CloseBraceToken, indentation); } throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartBody: if (node.Body == null || node.Body.OpenBraceToken.IsMissing || node.Body.CloseBraceToken.IsMissing) { throw Exceptions.ThrowEFail(); } return GetBodyStartPoint(text, node.Body.OpenBraceToken); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, BaseNamespaceDeclarationSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.GetFirstToken().SpanStart; break; case EnvDTE.vsCMPart.vsCMPartNavigate: startPosition = node.Name.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartBody: if (node is NamespaceDeclarationSyntax namespaceDeclaration) { if (namespaceDeclaration.OpenBraceToken.IsMissing || namespaceDeclaration.CloseBraceToken.IsMissing) throw Exceptions.ThrowEFail(); return GetBodyStartPoint(text, namespaceDeclaration.OpenBraceToken); } else if (node is FileScopedNamespaceDeclarationSyntax fileScopedNamespace) { return GetBodyStartPoint(text, fileScopedNamespace.SemicolonToken); } else { throw Exceptions.ThrowEFail(); } default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, DelegateDeclarationSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.GetFirstToken().SpanStart; break; case EnvDTE.vsCMPart.vsCMPartNavigate: startPosition = node.Identifier.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, UsingDirectiveSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartNavigate: startPosition = node.Name.SpanStart; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, VariableDeclaratorSyntax node, EnvDTE.vsCMPart part) { var field = node.FirstAncestorOrSelf<BaseFieldDeclarationSyntax>(); int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (field.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = field.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartNavigate: startPosition = node.Identifier.SpanStart; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, EnumMemberDeclarationSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartNavigate: startPosition = node.Identifier.SpanStart; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetStartPoint(SourceText text, ParameterSyntax node, EnvDTE.vsCMPart part) { int startPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } goto case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: startPosition = node.SpanStart; break; case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartNavigate: startPosition = node.Identifier.SpanStart; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, startPosition); } private VirtualTreePoint GetEndPoint(SourceText text, ArrowExpressionClauseSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBody: endPosition = node.Span.End; break; default: throw Exceptions.ThrowENotImpl(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, AttributeSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartNavigate: endPosition = node.Name.Span.End; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, AttributeArgumentSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: case EnvDTE.vsCMPart.vsCMPartBody: case EnvDTE.vsCMPart.vsCMPartNavigate: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, BaseTypeDeclarationSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } endPosition = node.AttributeLists.Last().GetLastToken().Span.End; break; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartNavigate: endPosition = node.Identifier.Span.End; break; case EnvDTE.vsCMPart.vsCMPartBody: return GetBodyEndPoint(text, node.CloseBraceToken); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, BaseMethodDeclarationSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } endPosition = node.AttributeLists.Last().GetLastToken().Span.End; break; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartNavigate: if (node.Body != null && !node.Body.CloseBraceToken.IsMissing) { return GetBodyEndPoint(text, node.Body.CloseBraceToken); } else { switch (node.Kind()) { case SyntaxKind.MethodDeclaration: endPosition = ((MethodDeclarationSyntax)node).Identifier.Span.End; break; case SyntaxKind.ConstructorDeclaration: endPosition = ((ConstructorDeclarationSyntax)node).Identifier.Span.End; break; case SyntaxKind.DestructorDeclaration: endPosition = ((DestructorDeclarationSyntax)node).Identifier.Span.End; break; case SyntaxKind.ConversionOperatorDeclaration: endPosition = ((ConversionOperatorDeclarationSyntax)node).ImplicitOrExplicitKeyword.Span.End; break; case SyntaxKind.OperatorDeclaration: endPosition = ((OperatorDeclarationSyntax)node).OperatorToken.Span.End; break; default: endPosition = node.GetFirstTokenAfterAttributes().Span.End; break; } } break; case EnvDTE.vsCMPart.vsCMPartBody: if (node.Body == null || node.Body.OpenBraceToken.IsMissing || node.Body.CloseBraceToken.IsMissing) { throw Exceptions.ThrowEFail(); } return GetBodyEndPoint(text, node.Body.CloseBraceToken); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, BasePropertyDeclarationSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } endPosition = node.AttributeLists.Last().Span.End; break; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartNavigate: var firstAccessorNode = FindFirstAccessorNode(node); if (firstAccessorNode != null) { if (firstAccessorNode.Body != null) { return GetBodyEndPoint(text, firstAccessorNode.Body.CloseBraceToken); } else { // This is total weirdness from the old C# code model with auto props. // If there isn't a body, the semi-colon is used return GetBodyEndPoint(text, firstAccessorNode.SemicolonToken); } } throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartBody: if (node.AccessorList != null && !node.AccessorList.CloseBraceToken.IsMissing) { return GetBodyEndPoint(text, node.AccessorList.CloseBraceToken); } throw Exceptions.ThrowEFail(); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, AccessorDeclarationSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartBody: case EnvDTE.vsCMPart.vsCMPartNavigate: if (node.Body == null || node.Body.OpenBraceToken.IsMissing || node.Body.CloseBraceToken.IsMissing) { throw Exceptions.ThrowEFail(); } return GetBodyEndPoint(text, node.Body.CloseBraceToken); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, DelegateDeclarationSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } endPosition = node.AttributeLists.Last().Span.End; break; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartNavigate: endPosition = node.Identifier.Span.End; break; case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, BaseNamespaceDeclarationSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartNavigate: endPosition = node.Name.Span.End; break; case EnvDTE.vsCMPart.vsCMPartBody: if (node is NamespaceDeclarationSyntax namespaceDeclaration) { if (namespaceDeclaration.OpenBraceToken.IsMissing || namespaceDeclaration.CloseBraceToken.IsMissing) throw Exceptions.ThrowEFail(); return GetBodyEndPoint(text, namespaceDeclaration.CloseBraceToken); } else if (node is FileScopedNamespaceDeclarationSyntax fileScopedNamespace) { return new VirtualTreePoint(fileScopedNamespace.SyntaxTree, text, fileScopedNamespace.Parent.Span.End); } else { throw Exceptions.ThrowEFail(); } default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, UsingDirectiveSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartNavigate: endPosition = node.Name.Span.End; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, EnumMemberDeclarationSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } endPosition = node.AttributeLists.Last().GetLastToken().Span.End; break; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartNavigate: endPosition = node.Identifier.Span.End; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, VariableDeclaratorSyntax node, EnvDTE.vsCMPart part) { var field = node.FirstAncestorOrSelf<BaseFieldDeclarationSyntax>(); int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (field.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } endPosition = field.AttributeLists.Last().GetLastToken().Span.End; break; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = field.Span.End; break; case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartNavigate: endPosition = node.Identifier.Span.End; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } private VirtualTreePoint GetEndPoint(SourceText text, ParameterSyntax node, EnvDTE.vsCMPart part) { int endPosition; switch (part) { case EnvDTE.vsCMPart.vsCMPartName: case EnvDTE.vsCMPart.vsCMPartAttributes: case EnvDTE.vsCMPart.vsCMPartHeader: case EnvDTE.vsCMPart.vsCMPartWhole: case EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter: case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes: throw Exceptions.ThrowENotImpl(); case EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter: if (node.AttributeLists.Count == 0) { throw Exceptions.ThrowEFail(); } endPosition = node.AttributeLists.Last().GetLastToken().Span.End; break; case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes: endPosition = node.Span.End; break; case EnvDTE.vsCMPart.vsCMPartBody: throw Exceptions.ThrowEFail(); case EnvDTE.vsCMPart.vsCMPartNavigate: endPosition = node.Identifier.Span.End; break; default: throw Exceptions.ThrowEInvalidArg(); } return new VirtualTreePoint(node.SyntaxTree, text, endPosition); } } } }
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/EditorFeatures/Test/Structure/StructureTaggerTests.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.Editor.Implementation.Structure; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Text.Adornments; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Structure { [UseExportProvider] public class StructureTaggerTests { [WpfTheory, Trait(Traits.Feature, Traits.Features.Outlining)] [CombinatorialData] public async Task CSharpOutliningTagger( bool collapseRegionsWhenCollapsingToDefinitions, bool showBlockStructureGuidesForDeclarationLevelConstructs, bool showBlockStructureGuidesForCodeLevelConstructs) { var code = @"using System; namespace MyNamespace { #region MyRegion public class MyClass { static void Main(string[] args) { if (false) { return; } int x = 5; } } #endregion }"; using var workspace = TestWorkspace.CreateCSharp(code, composition: EditorTestCompositions.EditorFeaturesWpf); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(BlockStructureOptions.CollapseRegionsWhenCollapsingToDefinitions, LanguageNames.CSharp, collapseRegionsWhenCollapsingToDefinitions) .WithChangedOption(BlockStructureOptions.ShowBlockStructureGuidesForDeclarationLevelConstructs, LanguageNames.CSharp, showBlockStructureGuidesForDeclarationLevelConstructs) .WithChangedOption(BlockStructureOptions.ShowBlockStructureGuidesForCodeLevelConstructs, LanguageNames.CSharp, showBlockStructureGuidesForCodeLevelConstructs))); var tags = await GetTagsFromWorkspaceAsync(workspace); Assert.Collection(tags, namespaceTag => { Assert.False(namespaceTag.IsImplementation); Assert.Equal(17, GetCollapsedHintLineCount(namespaceTag)); Assert.Equal(showBlockStructureGuidesForDeclarationLevelConstructs ? PredefinedStructureTagTypes.Namespace : PredefinedStructureTagTypes.Nonstructural, namespaceTag.Type); Assert.Equal("namespace MyNamespace", GetHeaderText(namespaceTag)); }, regionTag => { Assert.Equal(collapseRegionsWhenCollapsingToDefinitions, regionTag.IsImplementation); Assert.Equal(14, GetCollapsedHintLineCount(regionTag)); Assert.Equal(PredefinedStructureTagTypes.Nonstructural, regionTag.Type); Assert.Equal("#region MyRegion", GetHeaderText(regionTag)); }, classTag => { Assert.False(classTag.IsImplementation); Assert.Equal(12, GetCollapsedHintLineCount(classTag)); Assert.Equal(showBlockStructureGuidesForDeclarationLevelConstructs ? PredefinedStructureTagTypes.Type : PredefinedStructureTagTypes.Nonstructural, classTag.Type); Assert.Equal("public class MyClass", GetHeaderText(classTag)); }, methodTag => { Assert.True(methodTag.IsImplementation); Assert.Equal(9, GetCollapsedHintLineCount(methodTag)); Assert.Equal(showBlockStructureGuidesForDeclarationLevelConstructs ? PredefinedStructureTagTypes.Member : PredefinedStructureTagTypes.Nonstructural, methodTag.Type); Assert.Equal("static void Main(string[] args)", GetHeaderText(methodTag)); }, ifTag => { Assert.False(ifTag.IsImplementation); Assert.Equal(4, GetCollapsedHintLineCount(ifTag)); Assert.Equal(showBlockStructureGuidesForCodeLevelConstructs ? PredefinedStructureTagTypes.Conditional : PredefinedStructureTagTypes.Nonstructural, ifTag.Type); Assert.Equal("if (false)", GetHeaderText(ifTag)); }); } [WpfTheory, Trait(Traits.Feature, Traits.Features.Outlining)] [CombinatorialData] public async Task VisualBasicOutliningTagger( bool collapseRegionsWhenCollapsingToDefinitions, bool showBlockStructureGuidesForDeclarationLevelConstructs, bool showBlockStructureGuidesForCodeLevelConstructs) { var code = @"Imports System Namespace MyNamespace #Region ""MyRegion"" Module M Sub Main(args As String()) If False Then Return End If Dim x As Integer = 5 End Sub End Module #End Region End Namespace"; using var workspace = TestWorkspace.CreateVisualBasic(code, composition: EditorTestCompositions.EditorFeaturesWpf); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(BlockStructureOptions.CollapseRegionsWhenCollapsingToDefinitions, LanguageNames.VisualBasic, collapseRegionsWhenCollapsingToDefinitions) .WithChangedOption(BlockStructureOptions.ShowBlockStructureGuidesForDeclarationLevelConstructs, LanguageNames.VisualBasic, showBlockStructureGuidesForDeclarationLevelConstructs) .WithChangedOption(BlockStructureOptions.ShowBlockStructureGuidesForCodeLevelConstructs, LanguageNames.VisualBasic, showBlockStructureGuidesForCodeLevelConstructs))); var tags = await GetTagsFromWorkspaceAsync(workspace); Assert.Collection(tags, namespaceTag => { Assert.False(namespaceTag.IsImplementation); Assert.Equal(13, GetCollapsedHintLineCount(namespaceTag)); Assert.Equal(showBlockStructureGuidesForDeclarationLevelConstructs ? PredefinedStructureTagTypes.Namespace : PredefinedStructureTagTypes.Nonstructural, namespaceTag.Type); Assert.Equal("Namespace MyNamespace", GetHeaderText(namespaceTag)); }, regionTag => { Assert.Equal(collapseRegionsWhenCollapsingToDefinitions, regionTag.IsImplementation); Assert.Equal(11, GetCollapsedHintLineCount(regionTag)); Assert.Equal(PredefinedStructureTagTypes.Nonstructural, regionTag.Type); Assert.Equal(@"#Region ""MyRegion""", GetHeaderText(regionTag)); }, moduleTag => { Assert.False(moduleTag.IsImplementation); Assert.Equal(9, GetCollapsedHintLineCount(moduleTag)); Assert.Equal(showBlockStructureGuidesForDeclarationLevelConstructs ? PredefinedStructureTagTypes.Type : PredefinedStructureTagTypes.Nonstructural, moduleTag.Type); Assert.Equal("Module M", GetHeaderText(moduleTag)); }, methodTag => { Assert.True(methodTag.IsImplementation); Assert.Equal(7, GetCollapsedHintLineCount(methodTag)); Assert.Equal(showBlockStructureGuidesForDeclarationLevelConstructs ? PredefinedStructureTagTypes.Member : PredefinedStructureTagTypes.Nonstructural, methodTag.Type); Assert.Equal("Sub Main(args As String())", GetHeaderText(methodTag)); }, ifTag => { Assert.False(ifTag.IsImplementation); Assert.Equal(3, GetCollapsedHintLineCount(ifTag)); Assert.Equal(showBlockStructureGuidesForCodeLevelConstructs ? PredefinedStructureTagTypes.Conditional : PredefinedStructureTagTypes.Nonstructural, ifTag.Type); Assert.Equal("If False Then", GetHeaderText(ifTag)); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task OutliningTaggerTooltipText() { var code = @"Module Module1 Sub Main(args As String()) End Sub End Module"; using var workspace = TestWorkspace.CreateVisualBasic(code, composition: EditorTestCompositions.EditorFeaturesWpf); var tags = await GetTagsFromWorkspaceAsync(workspace); var hints = tags.Select(x => x.GetCollapsedHintForm()).Cast<ViewHostingControl>().ToArray(); Assert.Equal("Sub Main(args As String())\r\nEnd Sub", hints[1].GetText_TestOnly()); // method hints.Do(v => v.TextView_TestOnly.Close()); } private static async Task<List<IStructureTag>> GetTagsFromWorkspaceAsync(TestWorkspace workspace) { var hostdoc = workspace.Documents.First(); var view = hostdoc.GetTextView(); var provider = workspace.ExportProvider.GetExportedValue<AbstractStructureTaggerProvider>(); var document = workspace.CurrentSolution.GetDocument(hostdoc.Id); var context = new TaggerContext<IStructureTag>(document, view.TextSnapshot); await provider.GetTestAccessor().ProduceTagsAsync(context); return context.tagSpans.Select(x => x.Tag).OrderBy(t => t.OutliningSpan.Value.Start).ToList(); } private static string GetHeaderText(IStructureTag namespaceTag) { return namespaceTag.Snapshot.GetText(namespaceTag.HeaderSpan.Value); } private static int GetCollapsedHintLineCount(IStructureTag tag) { var control = Assert.IsType<ViewHostingControl>(tag.GetCollapsedHintForm()); var view = control.TextView_TestOnly; try { return view.TextSnapshot.LineCount; } finally { view.Close(); } } } }
// Licensed to the .NET Foundation under one or more 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.Editor.Implementation.Structure; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Text.Adornments; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Structure { [UseExportProvider] public class StructureTaggerTests { [WpfTheory, Trait(Traits.Feature, Traits.Features.Outlining)] [CombinatorialData] public async Task CSharpOutliningTagger( bool collapseRegionsWhenCollapsingToDefinitions, bool showBlockStructureGuidesForDeclarationLevelConstructs, bool showBlockStructureGuidesForCodeLevelConstructs) { var code = @"using System; namespace MyNamespace { #region MyRegion public class MyClass { static void Main(string[] args) { if (false) { return; } int x = 5; } } #endregion }"; using var workspace = TestWorkspace.CreateCSharp(code, composition: EditorTestCompositions.EditorFeaturesWpf); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(BlockStructureOptions.CollapseRegionsWhenCollapsingToDefinitions, LanguageNames.CSharp, collapseRegionsWhenCollapsingToDefinitions) .WithChangedOption(BlockStructureOptions.ShowBlockStructureGuidesForDeclarationLevelConstructs, LanguageNames.CSharp, showBlockStructureGuidesForDeclarationLevelConstructs) .WithChangedOption(BlockStructureOptions.ShowBlockStructureGuidesForCodeLevelConstructs, LanguageNames.CSharp, showBlockStructureGuidesForCodeLevelConstructs))); var tags = await GetTagsFromWorkspaceAsync(workspace); Assert.Collection(tags, namespaceTag => { Assert.False(namespaceTag.IsImplementation); Assert.Equal(17, GetCollapsedHintLineCount(namespaceTag)); Assert.Equal(showBlockStructureGuidesForDeclarationLevelConstructs ? PredefinedStructureTagTypes.Namespace : PredefinedStructureTagTypes.Nonstructural, namespaceTag.Type); Assert.Equal("namespace MyNamespace", GetHeaderText(namespaceTag)); }, regionTag => { Assert.Equal(collapseRegionsWhenCollapsingToDefinitions, regionTag.IsImplementation); Assert.Equal(14, GetCollapsedHintLineCount(regionTag)); Assert.Equal(PredefinedStructureTagTypes.Nonstructural, regionTag.Type); Assert.Equal("#region MyRegion", GetHeaderText(regionTag)); }, classTag => { Assert.False(classTag.IsImplementation); Assert.Equal(12, GetCollapsedHintLineCount(classTag)); Assert.Equal(showBlockStructureGuidesForDeclarationLevelConstructs ? PredefinedStructureTagTypes.Type : PredefinedStructureTagTypes.Nonstructural, classTag.Type); Assert.Equal("public class MyClass", GetHeaderText(classTag)); }, methodTag => { Assert.True(methodTag.IsImplementation); Assert.Equal(9, GetCollapsedHintLineCount(methodTag)); Assert.Equal(showBlockStructureGuidesForDeclarationLevelConstructs ? PredefinedStructureTagTypes.Member : PredefinedStructureTagTypes.Nonstructural, methodTag.Type); Assert.Equal("static void Main(string[] args)", GetHeaderText(methodTag)); }, ifTag => { Assert.False(ifTag.IsImplementation); Assert.Equal(4, GetCollapsedHintLineCount(ifTag)); Assert.Equal(showBlockStructureGuidesForCodeLevelConstructs ? PredefinedStructureTagTypes.Conditional : PredefinedStructureTagTypes.Nonstructural, ifTag.Type); Assert.Equal("if (false)", GetHeaderText(ifTag)); }); } [WpfTheory, Trait(Traits.Feature, Traits.Features.Outlining)] [CombinatorialData] public async Task VisualBasicOutliningTagger( bool collapseRegionsWhenCollapsingToDefinitions, bool showBlockStructureGuidesForDeclarationLevelConstructs, bool showBlockStructureGuidesForCodeLevelConstructs) { var code = @"Imports System Namespace MyNamespace #Region ""MyRegion"" Module M Sub Main(args As String()) If False Then Return End If Dim x As Integer = 5 End Sub End Module #End Region End Namespace"; using var workspace = TestWorkspace.CreateVisualBasic(code, composition: EditorTestCompositions.EditorFeaturesWpf); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(BlockStructureOptions.CollapseRegionsWhenCollapsingToDefinitions, LanguageNames.VisualBasic, collapseRegionsWhenCollapsingToDefinitions) .WithChangedOption(BlockStructureOptions.ShowBlockStructureGuidesForDeclarationLevelConstructs, LanguageNames.VisualBasic, showBlockStructureGuidesForDeclarationLevelConstructs) .WithChangedOption(BlockStructureOptions.ShowBlockStructureGuidesForCodeLevelConstructs, LanguageNames.VisualBasic, showBlockStructureGuidesForCodeLevelConstructs))); var tags = await GetTagsFromWorkspaceAsync(workspace); Assert.Collection(tags, namespaceTag => { Assert.False(namespaceTag.IsImplementation); Assert.Equal(13, GetCollapsedHintLineCount(namespaceTag)); Assert.Equal(showBlockStructureGuidesForDeclarationLevelConstructs ? PredefinedStructureTagTypes.Namespace : PredefinedStructureTagTypes.Nonstructural, namespaceTag.Type); Assert.Equal("Namespace MyNamespace", GetHeaderText(namespaceTag)); }, regionTag => { Assert.Equal(collapseRegionsWhenCollapsingToDefinitions, regionTag.IsImplementation); Assert.Equal(11, GetCollapsedHintLineCount(regionTag)); Assert.Equal(PredefinedStructureTagTypes.Nonstructural, regionTag.Type); Assert.Equal(@"#Region ""MyRegion""", GetHeaderText(regionTag)); }, moduleTag => { Assert.False(moduleTag.IsImplementation); Assert.Equal(9, GetCollapsedHintLineCount(moduleTag)); Assert.Equal(showBlockStructureGuidesForDeclarationLevelConstructs ? PredefinedStructureTagTypes.Type : PredefinedStructureTagTypes.Nonstructural, moduleTag.Type); Assert.Equal("Module M", GetHeaderText(moduleTag)); }, methodTag => { Assert.True(methodTag.IsImplementation); Assert.Equal(7, GetCollapsedHintLineCount(methodTag)); Assert.Equal(showBlockStructureGuidesForDeclarationLevelConstructs ? PredefinedStructureTagTypes.Member : PredefinedStructureTagTypes.Nonstructural, methodTag.Type); Assert.Equal("Sub Main(args As String())", GetHeaderText(methodTag)); }, ifTag => { Assert.False(ifTag.IsImplementation); Assert.Equal(3, GetCollapsedHintLineCount(ifTag)); Assert.Equal(showBlockStructureGuidesForCodeLevelConstructs ? PredefinedStructureTagTypes.Conditional : PredefinedStructureTagTypes.Nonstructural, ifTag.Type); Assert.Equal("If False Then", GetHeaderText(ifTag)); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task OutliningTaggerTooltipText() { var code = @"Module Module1 Sub Main(args As String()) End Sub End Module"; using var workspace = TestWorkspace.CreateVisualBasic(code, composition: EditorTestCompositions.EditorFeaturesWpf); var tags = await GetTagsFromWorkspaceAsync(workspace); var hints = tags.Select(x => x.GetCollapsedHintForm()).Cast<ViewHostingControl>().ToArray(); Assert.Equal("Sub Main(args As String())\r\nEnd Sub", hints[1].GetText_TestOnly()); // method hints.Do(v => v.TextView_TestOnly.Close()); } private static async Task<List<IStructureTag>> GetTagsFromWorkspaceAsync(TestWorkspace workspace) { var hostdoc = workspace.Documents.First(); var view = hostdoc.GetTextView(); var provider = workspace.ExportProvider.GetExportedValue<AbstractStructureTaggerProvider>(); var document = workspace.CurrentSolution.GetDocument(hostdoc.Id); var context = new TaggerContext<IStructureTag>(document, view.TextSnapshot); await provider.GetTestAccessor().ProduceTagsAsync(context); return context.tagSpans.Select(x => x.Tag).OrderBy(t => t.OutliningSpan.Value.Start).ToList(); } private static string GetHeaderText(IStructureTag namespaceTag) { return namespaceTag.Snapshot.GetText(namespaceTag.HeaderSpan.Value); } private static int GetCollapsedHintLineCount(IStructureTag tag) { var control = Assert.IsType<ViewHostingControl>(tag.GetCollapsedHintForm()); var view = control.TextView_TestOnly; try { return view.TextSnapshot.LineCount; } finally { view.Close(); } } } }
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/Compilers/Test/Resources/Core/SymbolsTests/Methods/ByRefReturn.il
// ilasm /DLL ByRefReturn.il // Microsoft (R) .NET Framework IL Disassembler. Version 4.0.30319.1 // Metadata version: v4.0.30319 .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly ByRefReturn { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilationRelaxationsAttribute::.ctor(int32) = ( 01 00 08 00 00 00 00 00 ) .custom instance void [mscorlib]System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::.ctor() = ( 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..WrapNonEx 63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) // ceptionThrows. .hash algorithm 0x00008004 .ver 0:0:0:0 } .module ByRefReturn.dll // MVID: {02416594-C334-48EC-8716-DBB37259A68B} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x019F0000 // =============== CLASS MEMBERS DECLARATION =================== .class public auto ansi beforefieldinit ByRefReturn extends [mscorlib]System.Object { .field private static int32 f .method public hidebysig instance int32& M() cil managed { // Code size 11 (0xb) .maxstack 1 .locals init (int32 V_0) IL_0000: nop IL_0001: ldsflda int32 ByRefReturn::f IL_000a: ret } // end of method ByRefReturn::M .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method ByRefReturn::.ctor } // end of class ByRefReturn // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** // WARNING: Created Win32 resource file ByRefReturn.res
// ilasm /DLL ByRefReturn.il // Microsoft (R) .NET Framework IL Disassembler. Version 4.0.30319.1 // Metadata version: v4.0.30319 .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly ByRefReturn { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilationRelaxationsAttribute::.ctor(int32) = ( 01 00 08 00 00 00 00 00 ) .custom instance void [mscorlib]System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::.ctor() = ( 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..WrapNonEx 63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) // ceptionThrows. .hash algorithm 0x00008004 .ver 0:0:0:0 } .module ByRefReturn.dll // MVID: {02416594-C334-48EC-8716-DBB37259A68B} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x019F0000 // =============== CLASS MEMBERS DECLARATION =================== .class public auto ansi beforefieldinit ByRefReturn extends [mscorlib]System.Object { .field private static int32 f .method public hidebysig instance int32& M() cil managed { // Code size 11 (0xb) .maxstack 1 .locals init (int32 V_0) IL_0000: nop IL_0001: ldsflda int32 ByRefReturn::f IL_000a: ret } // end of method ByRefReturn::M .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method ByRefReturn::.ctor } // end of class ByRefReturn // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** // WARNING: Created Win32 resource file ByRefReturn.res
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/Compilers/CSharp/Test/Semantic/Semantics/MultiDimensionalArrayTests.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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public partial class MultiDimensionalArrayTests : SemanticModelTestBase { [Fact] public void TestMultiDimensionalArray() { // Verify that operations on multidimensional arrays work and cause side effects only once. string source = @" using System; class P { static int M(ref int x) { int y = x; x = 456; return y; } static int counter; static int[,] A(int[,] a) { Console.Write('A'); Console.Write(counter); ++counter; return a; } static int B(int b) { Console.Write('B'); Console.Write(counter); ++counter; return b; } static int C(int c) { Console.Write('C'); Console.Write(counter); ++counter; return c; } static void Main() { int x = 4; int y = 5; int[,] a = new int[x,y]; V((A(a)[B(3),C(4)] = 123) == 123); V(M(ref A(a)[B(1),C(2)]) == 0); V(A(a)[B(1),C(2)] == 456); V(A(a)[B(3),C(4)] == 123); V(A(a)[B(0),C(0)] == 0); V(A(a)[B(0),C(0)]++ == 0); V(A(a)[B(0),C(0)] == 1); V(++A(a)[B(0),C(0)] == 2); V(A(a)[B(0),C(0)] == 2); V((A(a)[B(1),C(1)] += 3) == 3); V((A(a)[B(1),C(1)] -= 2) == 1); } static void V(bool b) { Console.WriteLine(b ? 't' : 'f'); } }"; string expected = @"A0B1C2t A3B4C5t A6B7C8t A9B10C11t A12B13C14t A15B16C17t A18B19C20t A21B22C23t A24B25C26t A27B28C29t A30B31C32t"; var verifier = CompileAndVerify(source: source, expectedOutput: expected); } [Fact] public void TestMultiDimensionalArrayInitializers() { // Verify that operations on multidimensional arrays work and cause side effects only once. string source = @" using System; class P { static void Main() { byte[,,] b = new byte[,,]{ { { 1, 2, 3 }, { 4, 5, 6 } }, { { 7, 8, 9 }, { 10, 11, 12 } } }; int x = 999; int y = 888; int[,,] i = new int[,,]{ { { 1, 2, 3 }, { 4, 5, y } }, { { x, 8, 9 }, { 10, 11, 12 } } }; double[,,] d = new double[,,]{ { { y, y, y }, { x, x, x } }, { { x, y, x }, { 10, 11, 12 } } }; for (int j = 0 ; j < 2; ++j) for (int k = 0; k < 2; ++k) for (int l = 0; l < 3; ++l) Console.Write(b[j,k,l]); Console.WriteLine(); for (int j = 0 ; j < 2; ++j) for (int k = 0; k < 2; ++k) for (int l = 0; l < 3; ++l) Console.Write(i[j,k,l]); Console.WriteLine(); for (int j = 0 ; j < 2; ++j) for (int k = 0; k < 2; ++k) for (int l = 0; l < 3; ++l) Console.Write(d[j,k,l]); } }"; string expected = @"123456789101112 1234588899989101112 888888888999999999999888999101112"; var verifier = CompileAndVerify(source: source, expectedOutput: expected); } [Fact] public void TestMultiDimensionalArrayForEach() { string source = @" public class C { public static void Main() { int y = 50; foreach (var x in new int[2, 3] {{10, 20, 30}, {40, y, 60}}) { System.Console.Write(x); } } }"; string expected = @"102030405060"; var verifier = CompileAndVerify(source: source, expectedOutput: expected); } [WorkItem(544081, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544081")] [Fact()] public void MultiDimArrayGenericTypeWiderThanArrayType() { string source = @" class Program { public static void Ref<T>(T[,] array) { array[0, 0].GetType(); } static void Main(string[] args) { Ref<object>(new string[,] { { System.String.Empty } }); } }"; string expected = @""; var verifier = CompileAndVerify(source: source, expectedOutput: expected); } [WorkItem(544364, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544364")] [Fact] public void MissingNestedArrayInitializerWithNullConst() { var text = @"class Program { static void Main(string[] args) { int?[ , ] ar1 = { null }; } }"; CreateCompilation(text).VerifyDiagnostics( // (5,27): error CS0846: A nested array initializer is expected // int?[ , ] ar1 = { null }; Diagnostic(ErrorCode.ERR_ArrayInitializerExpected, "null") ); } private static readonly string s_arraysOfRank1IlSource = @" .class public auto ansi beforefieldinit Test extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Test1::.ctor .method public hidebysig newslot virtual instance float64[0...] Test1() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test1"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) ldc.i4.0 ldc.i4.1 newobj instance void float64[...]::.ctor(int32, int32) dup ldc.i4.0 ldc.r8 -100 call instance void float64[...]::Set(int32, float64) IL_000a: ret } // end of method Test::Test1 .method public hidebysig newslot virtual instance float64 Test2(float64[0...] x) cil managed { // Code size 11 (0xb) .maxstack 2 IL_0000: ldstr ""Test2"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) ldarg.1 ldc.i4.0 call instance float64 float64[...]::Get(int32) IL_000a: ret } // end of method Test::Test2 .method public hidebysig newslot virtual instance void Test3(float64[0...] x) cil managed { .param [1] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) .maxstack 2 IL_000a: ret } // end of method Test::Test3 .method public hidebysig static void M1<T>(!!T[0...] a) cil managed { // Code size 18 (0x12) .maxstack 8 IL_0000: nop IL_0001: ldtoken !!T IL_0006: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) IL_000b: call void [mscorlib]System.Console::WriteLine(object) IL_0010: nop IL_0011: ret } // end of method M1 .method public hidebysig static void M2<T>(!!T[] a, !!T[0...] b) cil managed { // Code size 18 (0x12) .maxstack 8 IL_0000: nop IL_0001: ldtoken !!T IL_0006: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) IL_000b: call void [mscorlib]System.Console::WriteLine(object) IL_0010: nop IL_0011: ret } // end of method M2 } // end of class Test "; [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void ArraysOfRank1_GetElement() { var source = @"class C { static void Main() { var t = new Test(); System.Console.WriteLine(t.Test1()[0]); } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: @"Test1 -100"); verifier.VerifyIL("C.Main", @" { // Code size 22 (0x16) .maxstack 2 IL_0000: newobj ""Test..ctor()"" IL_0005: callvirt ""double[*] Test.Test1()"" IL_000a: ldc.i4.0 IL_000b: call ""double[*].Get"" IL_0010: call ""void System.Console.WriteLine(double)"" IL_0015: ret } "); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void ArraysOfRank1_SetElement() { var source = @"class C { static void Main() { var t = new Test(); var a = t.Test1(); a[0] = 123; System.Console.WriteLine(t.Test2(a)); } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: @"Test1 Test2 123"); verifier.VerifyIL("C.Main", @" { // Code size 40 (0x28) .maxstack 4 .locals init (double[*] V_0) //a IL_0000: newobj ""Test..ctor()"" IL_0005: dup IL_0006: callvirt ""double[*] Test.Test1()"" IL_000b: stloc.0 IL_000c: ldloc.0 IL_000d: ldc.i4.0 IL_000e: ldc.r8 123 IL_0017: call ""double[*].Set"" IL_001c: ldloc.0 IL_001d: callvirt ""double Test.Test2(double[*])"" IL_0022: call ""void System.Console.WriteLine(double)"" IL_0027: ret } "); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void ArraysOfRank1_ElementAddress() { var source = @"class C { static void Main() { var t = new Test(); var a = t.Test1(); TestRef(ref a[0]); System.Console.WriteLine(t.Test2(a)); } static void TestRef(ref double val) { val = 123; } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: @"Test1 Test2 123"); verifier.VerifyIL("C.Main", @" { // Code size 36 (0x24) .maxstack 3 .locals init (double[*] V_0) //a IL_0000: newobj ""Test..ctor()"" IL_0005: dup IL_0006: callvirt ""double[*] Test.Test1()"" IL_000b: stloc.0 IL_000c: ldloc.0 IL_000d: ldc.i4.0 IL_000e: call ""double[*].Address"" IL_0013: call ""void C.TestRef(ref double)"" IL_0018: ldloc.0 IL_0019: callvirt ""double Test.Test2(double[*])"" IL_001e: call ""void System.Console.WriteLine(double)"" IL_0023: ret } "); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [Fact] public void ArraysOfRank1_Overriding01() { var source = @"class C : Test { public override double[] Test1() { return null; } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (3,30): error CS0508: 'C.Test1()': return type must be 'double[*]' to match overridden member 'Test.Test1()' // public override double[] Test1() Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "Test1").WithArguments("C.Test1()", "Test.Test1()", "double[*]").WithLocation(3, 30) ); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [Fact] public void ArraysOfRank1_Overriding02() { var source = @"class C : Test { public override double Test2(double[] x) { return x[0]; } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (3,28): error CS0115: 'C.Test2(double[])': no suitable method found to override // public override double Test2(double[] x) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Test2").WithArguments("C.Test2(double[])").WithLocation(3, 28) ); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [Fact] public void ArraysOfRank1_Conversions() { var source = @"class C { static void Main() { var t = new Test(); double[] a1 = t.Test1(); double[] a2 = (double[])t.Test1(); System.Collections.Generic.IList<double> a3 = t.Test1(); double [] a4 = null; t.Test2(a4); var a5 = (System.Collections.Generic.IList<double>)t.Test1(); System.Collections.Generic.IList<double> ilist = new double [] {}; var mdarray = t.Test1(); mdarray = ilist; mdarray = t.Test1(); mdarray = new [] { 3.0d }; } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (6,23): error CS0029: Cannot implicitly convert type 'double[*]' to 'double[]' // double[] a1 = t.Test1(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "t.Test1()").WithArguments("double[*]", "double[]").WithLocation(6, 23), // (7,23): error CS0030: Cannot convert type 'double[*]' to 'double[]' // double[] a2 = (double[])t.Test1(); Diagnostic(ErrorCode.ERR_NoExplicitConv, "(double[])t.Test1()").WithArguments("double[*]", "double[]").WithLocation(7, 23), // (8,55): error CS0029: Cannot implicitly convert type 'double[*]' to 'System.Collections.Generic.IList<double>' // System.Collections.Generic.IList<double> a3 = t.Test1(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "t.Test1()").WithArguments("double[*]", "System.Collections.Generic.IList<double>").WithLocation(8, 55), // (10,17): error CS1503: Argument 1: cannot convert from 'double[]' to 'double[*]' // t.Test2(a4); Diagnostic(ErrorCode.ERR_BadArgType, "a4").WithArguments("1", "double[]", "double[*]").WithLocation(10, 17), // (11,18): error CS0030: Cannot convert type 'double[*]' to 'System.Collections.Generic.IList<double>' // var a5 = (System.Collections.Generic.IList<double>)t.Test1(); Diagnostic(ErrorCode.ERR_NoExplicitConv, "(System.Collections.Generic.IList<double>)t.Test1()").WithArguments("double[*]", "System.Collections.Generic.IList<double>").WithLocation(11, 18), // (14,19): error CS0029: Cannot implicitly convert type 'System.Collections.Generic.IList<double>' to 'double[*]' // mdarray = ilist; Diagnostic(ErrorCode.ERR_NoImplicitConv, "ilist").WithArguments("System.Collections.Generic.IList<double>", "double[*]").WithLocation(14, 19), // (16,19): error CS0029: Cannot implicitly convert type 'double[]' to 'double[*]' // mdarray = new [] { 3.0d }; Diagnostic(ErrorCode.ERR_NoImplicitConv, "new [] { 3.0d }").WithArguments("double[]", "double[*]").WithLocation(16, 19) ); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [Fact] public void ArraysOfRank1_TypeArgumentInference01() { var source = @"class C { static void Main() { var t = new Test(); var md = t.Test1(); var sz = new double [] {}; M1(sz); M1(md); M2(sz, sz); M2(md, md); M2(sz, md); M2(md, sz); M3(sz); M3(md); Test.M1(sz); Test.M1(md); Test.M2(sz, sz); Test.M2(md, md); Test.M2(sz, md); Test.M2(md, sz); } static void M1<T>(T [] a){} static void M2<T>(T a, T b){} static void M3<T>(System.Collections.Generic.IList<T> a){} }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseExe); var m2 = compilation.GetTypeByMetadataName("Test").GetMember<MethodSymbol>("M2"); var szArray = (ArrayTypeSymbol)m2.Parameters.First().Type; Assert.Equal("T[]", szArray.ToTestDisplayString()); Assert.True(szArray.IsSZArray); Assert.Equal(1, szArray.Rank); Assert.True(szArray.Sizes.IsEmpty); Assert.True(szArray.LowerBounds.IsDefault); var mdArray = (ArrayTypeSymbol)m2.Parameters.Last().Type; Assert.Equal("T[*]", mdArray.ToTestDisplayString()); Assert.False(mdArray.IsSZArray); Assert.Equal(1, mdArray.Rank); Assert.True(mdArray.Sizes.IsEmpty); Assert.True(mdArray.LowerBounds.IsDefault); compilation.VerifyDiagnostics( // (10,9): error CS0411: The type arguments for method 'C.M1<T>(T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M1(md); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("C.M1<T>(T[])").WithLocation(10, 9), // (13,9): error CS0411: The type arguments for method 'C.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M2(sz, md); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("C.M2<T>(T, T)").WithLocation(13, 9), // (14,9): error CS0411: The type arguments for method 'C.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M2(md, sz); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("C.M2<T>(T, T)").WithLocation(14, 9), // (16,9): error CS0411: The type arguments for method 'C.M3<T>(IList<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M3(md); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M3").WithArguments("C.M3<T>(System.Collections.Generic.IList<T>)").WithLocation(16, 9), // (18,14): error CS0411: The type arguments for method 'Test.M1<T>(T[*])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Test.M1(sz); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Test.M1<T>(T[*])").WithLocation(18, 14), // (20,21): error CS1503: Argument 2: cannot convert from 'double[]' to 'double[*]' // Test.M2(sz, sz); Diagnostic(ErrorCode.ERR_BadArgType, "sz").WithArguments("2", "double[]", "double[*]").WithLocation(20, 21), // (21,17): error CS1503: Argument 1: cannot convert from 'double[*]' to 'double[]' // Test.M2(md, md); Diagnostic(ErrorCode.ERR_BadArgType, "md").WithArguments("1", "double[*]", "double[]").WithLocation(21, 17), // (23,14): error CS0411: The type arguments for method 'Test.M2<T>(T[], T[*])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Test.M2(md, sz); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("Test.M2<T>(T[], T[*])").WithLocation(23, 14) ); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void ArraysOfRank1_TypeArgumentInference02() { var source = @"class C { static void Main() { var t = new Test(); var md = t.Test1(); var sz = new double [] {}; M2(md, md); Test.M1(md); Test.M2(sz, md); } static void M2<T>(T a, T b) { System.Console.WriteLine(typeof(T)); } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseExe); CompileAndVerify(compilation, expectedOutput: @"Test1 System.Double[*] System.Double System.Double "); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void ArraysOfRank1_ForEach() { var source = @"class C { static void Main() { var t = new Test(); foreach (var d in t.Test1()) { System.Console.WriteLine(d); } } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: @"Test1 -100"); verifier.VerifyIL("C.Main", @" { // Code size 50 (0x32) .maxstack 2 .locals init (double[*] V_0, int V_1, int V_2) IL_0000: newobj ""Test..ctor()"" IL_0005: callvirt ""double[*] Test.Test1()"" IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: ldc.i4.0 IL_000d: callvirt ""int System.Array.GetUpperBound(int)"" IL_0012: stloc.1 IL_0013: ldloc.0 IL_0014: ldc.i4.0 IL_0015: callvirt ""int System.Array.GetLowerBound(int)"" IL_001a: stloc.2 IL_001b: br.s IL_002d IL_001d: ldloc.0 IL_001e: ldloc.2 IL_001f: call ""double[*].Get"" IL_0024: call ""void System.Console.WriteLine(double)"" IL_0029: ldloc.2 IL_002a: ldc.i4.1 IL_002b: add IL_002c: stloc.2 IL_002d: ldloc.2 IL_002e: ldloc.1 IL_002f: ble.s IL_001d IL_0031: ret } "); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void ArraysOfRank1_Length() { var source = @"class C { static void Main() { var t = new Test(); System.Console.WriteLine(t.Test1().Length); } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: @"Test1 1"); verifier.VerifyIL("C.Main", @" { // Code size 21 (0x15) .maxstack 1 IL_0000: newobj ""Test..ctor()"" IL_0005: callvirt ""double[*] Test.Test1()"" IL_000a: callvirt ""int System.Array.Length.get"" IL_000f: call ""void System.Console.WriteLine(int)"" IL_0014: ret } "); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void ArraysOfRank1_LongLength() { var source = @"class C { static void Main() { var t = new Test(); System.Console.WriteLine(t.Test1().LongLength); } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: @"Test1 1"); verifier.VerifyIL("C.Main", @" { // Code size 21 (0x15) .maxstack 1 IL_0000: newobj ""Test..ctor()"" IL_0005: callvirt ""double[*] Test.Test1()"" IL_000a: callvirt ""long System.Array.LongLength.get"" IL_000f: call ""void System.Console.WriteLine(long)"" IL_0014: ret } "); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [Fact] public void ArraysOfRank1_ParamArray() { var source = @"class C { static void Main() { var t = new Test(); double d = 1.2; t.Test3(d); t.Test3(new double [] {d}); } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (7,17): error CS1503: Argument 1: cannot convert from 'double' to 'params double[*]' // t.Test3(d); Diagnostic(ErrorCode.ERR_BadArgType, "d").WithArguments("1", "double", "params double[*]").WithLocation(7, 17), // (8,17): error CS1503: Argument 1: cannot convert from 'double[]' to 'params double[*]' // t.Test3(new double [] {d}); Diagnostic(ErrorCode.ERR_BadArgType, "new double [] {d}").WithArguments("1", "double[]", "params double[*]").WithLocation(8, 17) ); } [WorkItem(4954, "https://github.com/dotnet/roslyn/issues/4954")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void SizesAndLowerBounds_01() { var ilSource = @" .class public auto ansi beforefieldinit Test extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Test1::.ctor .method public hidebysig newslot virtual instance float64[,] Test1() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test1"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[...,] Test2() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test2"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[...,...] Test3() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test3"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[5,] Test4() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test4"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[5,...] Test5() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test5"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[5,5] Test6() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test6"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[5,2...] Test7() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test7"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[5,2...8] Test8() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test8"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[1...5,] Test9() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test9"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[1...5,...] Test10() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test10"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[1...5,5] Test11() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test11"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[1...5,2...] Test12() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test12"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[1...5,2...8] Test13() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test13"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[1...,] Test14() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test14"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[1...,...] Test15() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test15"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[1...,2...] Test16() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test16"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[1...5] Test17() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test17"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } } // end of class Test "; var source = @"class C : Test { static void Main() { double[,] a; var t = new Test(); a = t.Test1(); a = t.Test2(); a = t.Test3(); a = t.Test4(); a = t.Test5(); a = t.Test6(); a = t.Test7(); a = t.Test8(); a = t.Test9(); a = t.Test10(); a = t.Test11(); a = t.Test12(); a = t.Test13(); a = t.Test14(); a = t.Test15(); a = t.Test16(); t = new C(); a = t.Test1(); a = t.Test2(); a = t.Test3(); a = t.Test4(); a = t.Test5(); a = t.Test6(); a = t.Test7(); a = t.Test8(); a = t.Test9(); a = t.Test10(); a = t.Test11(); a = t.Test12(); a = t.Test13(); a = t.Test14(); a = t.Test15(); a = t.Test16(); } public override double[,] Test1() { System.Console.WriteLine(""Overridden 1""); return null; } public override double[,] Test2() { System.Console.WriteLine(""Overridden 2""); return null; } public override double[,] Test3() { System.Console.WriteLine(""Overridden 3""); return null; } public override double[,] Test4() { System.Console.WriteLine(""Overridden 4""); return null; } public override double[,] Test5() { System.Console.WriteLine(""Overridden 5""); return null; } public override double[,] Test6() { System.Console.WriteLine(""Overridden 6""); return null; } public override double[,] Test7() { System.Console.WriteLine(""Overridden 7""); return null; } public override double[,] Test8() { System.Console.WriteLine(""Overridden 8""); return null; } public override double[,] Test9() { System.Console.WriteLine(""Overridden 9""); return null; } public override double[,] Test10() { System.Console.WriteLine(""Overridden 10""); return null; } public override double[,] Test11() { System.Console.WriteLine(""Overridden 11""); return null; } public override double[,] Test12() { System.Console.WriteLine(""Overridden 12""); return null; } public override double[,] Test13() { System.Console.WriteLine(""Overridden 13""); return null; } public override double[,] Test14() { System.Console.WriteLine(""Overridden 14""); return null; } public override double[,] Test15() { System.Console.WriteLine(""Overridden 15""); return null; } public override double[,] Test16() { System.Console.WriteLine(""Overridden 16""); return null; } } "; var compilation = CreateCompilationWithILAndMscorlib40(source, ilSource, options: TestOptions.ReleaseExe); var test = compilation.GetTypeByMetadataName("Test"); var array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test1").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.True(array.Sizes.IsEmpty); Assert.True(array.LowerBounds.IsEmpty); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test2").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.True(array.Sizes.IsEmpty); Assert.True(array.LowerBounds.IsEmpty); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test3").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.True(array.Sizes.IsEmpty); Assert.True(array.LowerBounds.IsEmpty); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test4").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5 }, array.Sizes); Assert.Equal(new[] { 0 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test5").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5 }, array.Sizes); Assert.Equal(new[] { 0 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test6").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5, 5 }, array.Sizes); Assert.True(array.LowerBounds.IsDefault); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test7").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5 }, array.Sizes); Assert.Equal(new[] { 0, 2 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test8").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5, 7 }, array.Sizes); Assert.Equal(new[] { 0, 2 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test9").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5 }, array.Sizes); Assert.Equal(new[] { 1 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test10").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5 }, array.Sizes); Assert.Equal(new[] { 1 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test11").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5, 5 }, array.Sizes); Assert.Equal(new[] { 1, 0 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test12").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5 }, array.Sizes); Assert.Equal(new[] { 1, 2 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test13").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5, 7 }, array.Sizes); Assert.Equal(new[] { 1, 2 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test14").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.True(array.Sizes.IsEmpty); Assert.Equal(new[] { 1 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test15").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.True(array.Sizes.IsEmpty); Assert.Equal(new[] { 1 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test16").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.True(array.Sizes.IsEmpty); Assert.Equal(new[] { 1, 2 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test17").ReturnType; Assert.Equal("System.Double[*]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(1, array.Rank); Assert.Equal(new[] { 5 }, array.Sizes); Assert.Equal(new[] { 1 }, array.LowerBounds); var verifier = CompileAndVerify(compilation, expectedOutput: @"Test1 Test2 Test3 Test4 Test5 Test6 Test7 Test8 Test9 Test10 Test11 Test12 Test13 Test14 Test15 Test16 Overridden 1 Overridden 2 Overridden 3 Overridden 4 Overridden 5 Overridden 6 Overridden 7 Overridden 8 Overridden 9 Overridden 10 Overridden 11 Overridden 12 Overridden 13 Overridden 14 Overridden 15 Overridden 16 "); } [WorkItem(4954, "https://github.com/dotnet/roslyn/issues/4954")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void SizesAndLowerBounds_02() { var ilSource = @" .class public auto ansi beforefieldinit Test extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Test1::.ctor .method public hidebysig newslot virtual instance void Test1(float64[,] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test1"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test2(float64[...,] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test2"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test3(float64[...,...] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test3"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test4(float64[5,] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test4"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test5(float64[5,...] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test5"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test6(float64[5,5] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test6"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test7(float64[5,2...] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test7"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test8(float64[5,2...8] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test8"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test9(float64[1...5,] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test9"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test10(float64[1...5,...] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test10"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test11(float64[1...5,5] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test11"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test12(float64[1...5,2...] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test12"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test13(float64[1...5,2...8] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test13"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test14(float64[1...,] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test14"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test15(float64[1...,...] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test15"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test16(float64[1...,2...] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test16"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } } // end of class Test "; var source = @"class C : Test { static void Main() { double[,] a = new double [,] {}; var t = new Test(); t.Test1(a); t.Test2(a); t.Test3(a); t.Test4(a); t.Test5(a); t.Test6(a); t.Test7(a); t.Test8(a); t.Test9(a); t.Test10(a); t.Test11(a); t.Test12(a); t.Test13(a); t.Test14(a); t.Test15(a); t.Test16(a); t = new C(); t.Test1(a); t.Test2(a); t.Test3(a); t.Test4(a); t.Test5(a); t.Test6(a); t.Test7(a); t.Test8(a); t.Test9(a); t.Test10(a); t.Test11(a); t.Test12(a); t.Test13(a); t.Test14(a); t.Test15(a); t.Test16(a); } public override void Test1(double[,] x) { System.Console.WriteLine(""Overridden 1""); } public override void Test2(double[,] x) { System.Console.WriteLine(""Overridden 2""); } public override void Test3(double[,] x) { System.Console.WriteLine(""Overridden 3""); } public override void Test4(double[,] x) { System.Console.WriteLine(""Overridden 4""); } public override void Test5(double[,] x) { System.Console.WriteLine(""Overridden 5""); } public override void Test6(double[,] x) { System.Console.WriteLine(""Overridden 6""); } public override void Test7(double[,] x) { System.Console.WriteLine(""Overridden 7""); } public override void Test8(double[,] x) { System.Console.WriteLine(""Overridden 8""); } public override void Test9(double[,] x) { System.Console.WriteLine(""Overridden 9""); } public override void Test10(double[,] x) { System.Console.WriteLine(""Overridden 10""); } public override void Test11(double[,] x) { System.Console.WriteLine(""Overridden 11""); } public override void Test12(double[,] x) { System.Console.WriteLine(""Overridden 12""); } public override void Test13(double[,] x) { System.Console.WriteLine(""Overridden 13""); } public override void Test14(double[,] x) { System.Console.WriteLine(""Overridden 14""); } public override void Test15(double[,] x) { System.Console.WriteLine(""Overridden 15""); } public override void Test16(double[,] x) { System.Console.WriteLine(""Overridden 16""); } } "; var compilation = CreateCompilationWithILAndMscorlib40(source, ilSource, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: @"Test1 Test2 Test3 Test4 Test5 Test6 Test7 Test8 Test9 Test10 Test11 Test12 Test13 Test14 Test15 Test16 Overridden 1 Overridden 2 Overridden 3 Overridden 4 Overridden 5 Overridden 6 Overridden 7 Overridden 8 Overridden 9 Overridden 10 Overridden 11 Overridden 12 Overridden 13 Overridden 14 Overridden 15 Overridden 16 "); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] [WorkItem(4958, "https://github.com/dotnet/roslyn/issues/4958")] public void ArraysOfRank1_InAttributes() { var ilSource = @" .class public auto ansi beforefieldinit Program extends [mscorlib]System.Object { .method public hidebysig instance void Test1() cil managed { .custom instance void TestAttribute::.ctor(class [mscorlib] System.Type) = {type(class 'System.Int32[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')} // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Program::Test1 .method public hidebysig instance void Test2() cil managed { .custom instance void TestAttribute::.ctor(class [mscorlib] System.Type) = {type(class 'System.Int32[*], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')} // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Program::Test2 .method public hidebysig instance void Test3() cil managed { .custom instance void TestAttribute::.ctor(class [mscorlib] System.Type) = {type(class 'System.Int32[*,*], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')} // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Program::Test3 .method public hidebysig instance void Test4() cil managed { .custom instance void TestAttribute::.ctor(class [mscorlib] System.Type) = {type(class 'System.Int32[,*], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')} // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Program::Test4 } // end of class Program .class public auto ansi beforefieldinit TestAttribute extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(class [mscorlib]System.Type val) cil managed { // Code size 9 (0x9) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: nop IL_0007: nop IL_0008: ret } // end of method TestAttribute::.ctor } // end of class TestAttribute "; var source = @" using System; using System.Linq; class C { static void Main() { System.Console.WriteLine(GetTypeFromAttribute(""Test1"")); System.Console.WriteLine(GetTypeFromAttribute(""Test2"")); try { GetTypeFromAttribute(""Test3""); } catch { System.Console.WriteLine(""Throws""); } try { GetTypeFromAttribute(""Test4""); } catch { System.Console.WriteLine(""Throws""); } } private static Type GetTypeFromAttribute(string target) { return (System.Type)typeof(Program).GetMember(target)[0].GetCustomAttributesData().ElementAt(0).ConstructorArguments[0].Value; } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, ilSource, references: new[] { SystemCoreRef }, options: TestOptions.ReleaseExe); var p = compilation.GetTypeByMetadataName("Program"); var a1 = (IArrayTypeSymbol)p.GetMember<MethodSymbol>("Test1").GetAttributes().Single().ConstructorArguments.Single().Value; Assert.Equal("System.Int32[]", a1.ToTestDisplayString()); Assert.Equal(1, a1.Rank); Assert.True(a1.IsSZArray); var a2 = (IArrayTypeSymbol)p.GetMember<MethodSymbol>("Test2").GetAttributes().Single().ConstructorArguments.Single().Value; Assert.Equal("System.Int32[*]", a2.ToTestDisplayString()); Assert.Equal(1, a2.Rank); Assert.False(a2.IsSZArray); Assert.True(((ITypeSymbol)p.GetMember<MethodSymbol>("Test3").GetAttributes().Single().ConstructorArguments.Single().Value).IsErrorType()); Assert.True(((ITypeSymbol)p.GetMember<MethodSymbol>("Test4").GetAttributes().Single().ConstructorArguments.Single().Value).IsErrorType()); CompileAndVerify(compilation, expectedOutput: @"System.Int32[] System.Int32[*] Throws Throws"); } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public partial class MultiDimensionalArrayTests : SemanticModelTestBase { [Fact] public void TestMultiDimensionalArray() { // Verify that operations on multidimensional arrays work and cause side effects only once. string source = @" using System; class P { static int M(ref int x) { int y = x; x = 456; return y; } static int counter; static int[,] A(int[,] a) { Console.Write('A'); Console.Write(counter); ++counter; return a; } static int B(int b) { Console.Write('B'); Console.Write(counter); ++counter; return b; } static int C(int c) { Console.Write('C'); Console.Write(counter); ++counter; return c; } static void Main() { int x = 4; int y = 5; int[,] a = new int[x,y]; V((A(a)[B(3),C(4)] = 123) == 123); V(M(ref A(a)[B(1),C(2)]) == 0); V(A(a)[B(1),C(2)] == 456); V(A(a)[B(3),C(4)] == 123); V(A(a)[B(0),C(0)] == 0); V(A(a)[B(0),C(0)]++ == 0); V(A(a)[B(0),C(0)] == 1); V(++A(a)[B(0),C(0)] == 2); V(A(a)[B(0),C(0)] == 2); V((A(a)[B(1),C(1)] += 3) == 3); V((A(a)[B(1),C(1)] -= 2) == 1); } static void V(bool b) { Console.WriteLine(b ? 't' : 'f'); } }"; string expected = @"A0B1C2t A3B4C5t A6B7C8t A9B10C11t A12B13C14t A15B16C17t A18B19C20t A21B22C23t A24B25C26t A27B28C29t A30B31C32t"; var verifier = CompileAndVerify(source: source, expectedOutput: expected); } [Fact] public void TestMultiDimensionalArrayInitializers() { // Verify that operations on multidimensional arrays work and cause side effects only once. string source = @" using System; class P { static void Main() { byte[,,] b = new byte[,,]{ { { 1, 2, 3 }, { 4, 5, 6 } }, { { 7, 8, 9 }, { 10, 11, 12 } } }; int x = 999; int y = 888; int[,,] i = new int[,,]{ { { 1, 2, 3 }, { 4, 5, y } }, { { x, 8, 9 }, { 10, 11, 12 } } }; double[,,] d = new double[,,]{ { { y, y, y }, { x, x, x } }, { { x, y, x }, { 10, 11, 12 } } }; for (int j = 0 ; j < 2; ++j) for (int k = 0; k < 2; ++k) for (int l = 0; l < 3; ++l) Console.Write(b[j,k,l]); Console.WriteLine(); for (int j = 0 ; j < 2; ++j) for (int k = 0; k < 2; ++k) for (int l = 0; l < 3; ++l) Console.Write(i[j,k,l]); Console.WriteLine(); for (int j = 0 ; j < 2; ++j) for (int k = 0; k < 2; ++k) for (int l = 0; l < 3; ++l) Console.Write(d[j,k,l]); } }"; string expected = @"123456789101112 1234588899989101112 888888888999999999999888999101112"; var verifier = CompileAndVerify(source: source, expectedOutput: expected); } [Fact] public void TestMultiDimensionalArrayForEach() { string source = @" public class C { public static void Main() { int y = 50; foreach (var x in new int[2, 3] {{10, 20, 30}, {40, y, 60}}) { System.Console.Write(x); } } }"; string expected = @"102030405060"; var verifier = CompileAndVerify(source: source, expectedOutput: expected); } [WorkItem(544081, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544081")] [Fact()] public void MultiDimArrayGenericTypeWiderThanArrayType() { string source = @" class Program { public static void Ref<T>(T[,] array) { array[0, 0].GetType(); } static void Main(string[] args) { Ref<object>(new string[,] { { System.String.Empty } }); } }"; string expected = @""; var verifier = CompileAndVerify(source: source, expectedOutput: expected); } [WorkItem(544364, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544364")] [Fact] public void MissingNestedArrayInitializerWithNullConst() { var text = @"class Program { static void Main(string[] args) { int?[ , ] ar1 = { null }; } }"; CreateCompilation(text).VerifyDiagnostics( // (5,27): error CS0846: A nested array initializer is expected // int?[ , ] ar1 = { null }; Diagnostic(ErrorCode.ERR_ArrayInitializerExpected, "null") ); } private static readonly string s_arraysOfRank1IlSource = @" .class public auto ansi beforefieldinit Test extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Test1::.ctor .method public hidebysig newslot virtual instance float64[0...] Test1() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test1"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) ldc.i4.0 ldc.i4.1 newobj instance void float64[...]::.ctor(int32, int32) dup ldc.i4.0 ldc.r8 -100 call instance void float64[...]::Set(int32, float64) IL_000a: ret } // end of method Test::Test1 .method public hidebysig newslot virtual instance float64 Test2(float64[0...] x) cil managed { // Code size 11 (0xb) .maxstack 2 IL_0000: ldstr ""Test2"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) ldarg.1 ldc.i4.0 call instance float64 float64[...]::Get(int32) IL_000a: ret } // end of method Test::Test2 .method public hidebysig newslot virtual instance void Test3(float64[0...] x) cil managed { .param [1] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) .maxstack 2 IL_000a: ret } // end of method Test::Test3 .method public hidebysig static void M1<T>(!!T[0...] a) cil managed { // Code size 18 (0x12) .maxstack 8 IL_0000: nop IL_0001: ldtoken !!T IL_0006: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) IL_000b: call void [mscorlib]System.Console::WriteLine(object) IL_0010: nop IL_0011: ret } // end of method M1 .method public hidebysig static void M2<T>(!!T[] a, !!T[0...] b) cil managed { // Code size 18 (0x12) .maxstack 8 IL_0000: nop IL_0001: ldtoken !!T IL_0006: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) IL_000b: call void [mscorlib]System.Console::WriteLine(object) IL_0010: nop IL_0011: ret } // end of method M2 } // end of class Test "; [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void ArraysOfRank1_GetElement() { var source = @"class C { static void Main() { var t = new Test(); System.Console.WriteLine(t.Test1()[0]); } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: @"Test1 -100"); verifier.VerifyIL("C.Main", @" { // Code size 22 (0x16) .maxstack 2 IL_0000: newobj ""Test..ctor()"" IL_0005: callvirt ""double[*] Test.Test1()"" IL_000a: ldc.i4.0 IL_000b: call ""double[*].Get"" IL_0010: call ""void System.Console.WriteLine(double)"" IL_0015: ret } "); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void ArraysOfRank1_SetElement() { var source = @"class C { static void Main() { var t = new Test(); var a = t.Test1(); a[0] = 123; System.Console.WriteLine(t.Test2(a)); } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: @"Test1 Test2 123"); verifier.VerifyIL("C.Main", @" { // Code size 40 (0x28) .maxstack 4 .locals init (double[*] V_0) //a IL_0000: newobj ""Test..ctor()"" IL_0005: dup IL_0006: callvirt ""double[*] Test.Test1()"" IL_000b: stloc.0 IL_000c: ldloc.0 IL_000d: ldc.i4.0 IL_000e: ldc.r8 123 IL_0017: call ""double[*].Set"" IL_001c: ldloc.0 IL_001d: callvirt ""double Test.Test2(double[*])"" IL_0022: call ""void System.Console.WriteLine(double)"" IL_0027: ret } "); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void ArraysOfRank1_ElementAddress() { var source = @"class C { static void Main() { var t = new Test(); var a = t.Test1(); TestRef(ref a[0]); System.Console.WriteLine(t.Test2(a)); } static void TestRef(ref double val) { val = 123; } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: @"Test1 Test2 123"); verifier.VerifyIL("C.Main", @" { // Code size 36 (0x24) .maxstack 3 .locals init (double[*] V_0) //a IL_0000: newobj ""Test..ctor()"" IL_0005: dup IL_0006: callvirt ""double[*] Test.Test1()"" IL_000b: stloc.0 IL_000c: ldloc.0 IL_000d: ldc.i4.0 IL_000e: call ""double[*].Address"" IL_0013: call ""void C.TestRef(ref double)"" IL_0018: ldloc.0 IL_0019: callvirt ""double Test.Test2(double[*])"" IL_001e: call ""void System.Console.WriteLine(double)"" IL_0023: ret } "); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [Fact] public void ArraysOfRank1_Overriding01() { var source = @"class C : Test { public override double[] Test1() { return null; } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (3,30): error CS0508: 'C.Test1()': return type must be 'double[*]' to match overridden member 'Test.Test1()' // public override double[] Test1() Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "Test1").WithArguments("C.Test1()", "Test.Test1()", "double[*]").WithLocation(3, 30) ); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [Fact] public void ArraysOfRank1_Overriding02() { var source = @"class C : Test { public override double Test2(double[] x) { return x[0]; } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (3,28): error CS0115: 'C.Test2(double[])': no suitable method found to override // public override double Test2(double[] x) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Test2").WithArguments("C.Test2(double[])").WithLocation(3, 28) ); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [Fact] public void ArraysOfRank1_Conversions() { var source = @"class C { static void Main() { var t = new Test(); double[] a1 = t.Test1(); double[] a2 = (double[])t.Test1(); System.Collections.Generic.IList<double> a3 = t.Test1(); double [] a4 = null; t.Test2(a4); var a5 = (System.Collections.Generic.IList<double>)t.Test1(); System.Collections.Generic.IList<double> ilist = new double [] {}; var mdarray = t.Test1(); mdarray = ilist; mdarray = t.Test1(); mdarray = new [] { 3.0d }; } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (6,23): error CS0029: Cannot implicitly convert type 'double[*]' to 'double[]' // double[] a1 = t.Test1(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "t.Test1()").WithArguments("double[*]", "double[]").WithLocation(6, 23), // (7,23): error CS0030: Cannot convert type 'double[*]' to 'double[]' // double[] a2 = (double[])t.Test1(); Diagnostic(ErrorCode.ERR_NoExplicitConv, "(double[])t.Test1()").WithArguments("double[*]", "double[]").WithLocation(7, 23), // (8,55): error CS0029: Cannot implicitly convert type 'double[*]' to 'System.Collections.Generic.IList<double>' // System.Collections.Generic.IList<double> a3 = t.Test1(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "t.Test1()").WithArguments("double[*]", "System.Collections.Generic.IList<double>").WithLocation(8, 55), // (10,17): error CS1503: Argument 1: cannot convert from 'double[]' to 'double[*]' // t.Test2(a4); Diagnostic(ErrorCode.ERR_BadArgType, "a4").WithArguments("1", "double[]", "double[*]").WithLocation(10, 17), // (11,18): error CS0030: Cannot convert type 'double[*]' to 'System.Collections.Generic.IList<double>' // var a5 = (System.Collections.Generic.IList<double>)t.Test1(); Diagnostic(ErrorCode.ERR_NoExplicitConv, "(System.Collections.Generic.IList<double>)t.Test1()").WithArguments("double[*]", "System.Collections.Generic.IList<double>").WithLocation(11, 18), // (14,19): error CS0029: Cannot implicitly convert type 'System.Collections.Generic.IList<double>' to 'double[*]' // mdarray = ilist; Diagnostic(ErrorCode.ERR_NoImplicitConv, "ilist").WithArguments("System.Collections.Generic.IList<double>", "double[*]").WithLocation(14, 19), // (16,19): error CS0029: Cannot implicitly convert type 'double[]' to 'double[*]' // mdarray = new [] { 3.0d }; Diagnostic(ErrorCode.ERR_NoImplicitConv, "new [] { 3.0d }").WithArguments("double[]", "double[*]").WithLocation(16, 19) ); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [Fact] public void ArraysOfRank1_TypeArgumentInference01() { var source = @"class C { static void Main() { var t = new Test(); var md = t.Test1(); var sz = new double [] {}; M1(sz); M1(md); M2(sz, sz); M2(md, md); M2(sz, md); M2(md, sz); M3(sz); M3(md); Test.M1(sz); Test.M1(md); Test.M2(sz, sz); Test.M2(md, md); Test.M2(sz, md); Test.M2(md, sz); } static void M1<T>(T [] a){} static void M2<T>(T a, T b){} static void M3<T>(System.Collections.Generic.IList<T> a){} }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseExe); var m2 = compilation.GetTypeByMetadataName("Test").GetMember<MethodSymbol>("M2"); var szArray = (ArrayTypeSymbol)m2.Parameters.First().Type; Assert.Equal("T[]", szArray.ToTestDisplayString()); Assert.True(szArray.IsSZArray); Assert.Equal(1, szArray.Rank); Assert.True(szArray.Sizes.IsEmpty); Assert.True(szArray.LowerBounds.IsDefault); var mdArray = (ArrayTypeSymbol)m2.Parameters.Last().Type; Assert.Equal("T[*]", mdArray.ToTestDisplayString()); Assert.False(mdArray.IsSZArray); Assert.Equal(1, mdArray.Rank); Assert.True(mdArray.Sizes.IsEmpty); Assert.True(mdArray.LowerBounds.IsDefault); compilation.VerifyDiagnostics( // (10,9): error CS0411: The type arguments for method 'C.M1<T>(T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M1(md); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("C.M1<T>(T[])").WithLocation(10, 9), // (13,9): error CS0411: The type arguments for method 'C.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M2(sz, md); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("C.M2<T>(T, T)").WithLocation(13, 9), // (14,9): error CS0411: The type arguments for method 'C.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M2(md, sz); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("C.M2<T>(T, T)").WithLocation(14, 9), // (16,9): error CS0411: The type arguments for method 'C.M3<T>(IList<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M3(md); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M3").WithArguments("C.M3<T>(System.Collections.Generic.IList<T>)").WithLocation(16, 9), // (18,14): error CS0411: The type arguments for method 'Test.M1<T>(T[*])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Test.M1(sz); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Test.M1<T>(T[*])").WithLocation(18, 14), // (20,21): error CS1503: Argument 2: cannot convert from 'double[]' to 'double[*]' // Test.M2(sz, sz); Diagnostic(ErrorCode.ERR_BadArgType, "sz").WithArguments("2", "double[]", "double[*]").WithLocation(20, 21), // (21,17): error CS1503: Argument 1: cannot convert from 'double[*]' to 'double[]' // Test.M2(md, md); Diagnostic(ErrorCode.ERR_BadArgType, "md").WithArguments("1", "double[*]", "double[]").WithLocation(21, 17), // (23,14): error CS0411: The type arguments for method 'Test.M2<T>(T[], T[*])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Test.M2(md, sz); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("Test.M2<T>(T[], T[*])").WithLocation(23, 14) ); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void ArraysOfRank1_TypeArgumentInference02() { var source = @"class C { static void Main() { var t = new Test(); var md = t.Test1(); var sz = new double [] {}; M2(md, md); Test.M1(md); Test.M2(sz, md); } static void M2<T>(T a, T b) { System.Console.WriteLine(typeof(T)); } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseExe); CompileAndVerify(compilation, expectedOutput: @"Test1 System.Double[*] System.Double System.Double "); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void ArraysOfRank1_ForEach() { var source = @"class C { static void Main() { var t = new Test(); foreach (var d in t.Test1()) { System.Console.WriteLine(d); } } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: @"Test1 -100"); verifier.VerifyIL("C.Main", @" { // Code size 50 (0x32) .maxstack 2 .locals init (double[*] V_0, int V_1, int V_2) IL_0000: newobj ""Test..ctor()"" IL_0005: callvirt ""double[*] Test.Test1()"" IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: ldc.i4.0 IL_000d: callvirt ""int System.Array.GetUpperBound(int)"" IL_0012: stloc.1 IL_0013: ldloc.0 IL_0014: ldc.i4.0 IL_0015: callvirt ""int System.Array.GetLowerBound(int)"" IL_001a: stloc.2 IL_001b: br.s IL_002d IL_001d: ldloc.0 IL_001e: ldloc.2 IL_001f: call ""double[*].Get"" IL_0024: call ""void System.Console.WriteLine(double)"" IL_0029: ldloc.2 IL_002a: ldc.i4.1 IL_002b: add IL_002c: stloc.2 IL_002d: ldloc.2 IL_002e: ldloc.1 IL_002f: ble.s IL_001d IL_0031: ret } "); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void ArraysOfRank1_Length() { var source = @"class C { static void Main() { var t = new Test(); System.Console.WriteLine(t.Test1().Length); } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: @"Test1 1"); verifier.VerifyIL("C.Main", @" { // Code size 21 (0x15) .maxstack 1 IL_0000: newobj ""Test..ctor()"" IL_0005: callvirt ""double[*] Test.Test1()"" IL_000a: callvirt ""int System.Array.Length.get"" IL_000f: call ""void System.Console.WriteLine(int)"" IL_0014: ret } "); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void ArraysOfRank1_LongLength() { var source = @"class C { static void Main() { var t = new Test(); System.Console.WriteLine(t.Test1().LongLength); } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: @"Test1 1"); verifier.VerifyIL("C.Main", @" { // Code size 21 (0x15) .maxstack 1 IL_0000: newobj ""Test..ctor()"" IL_0005: callvirt ""double[*] Test.Test1()"" IL_000a: callvirt ""long System.Array.LongLength.get"" IL_000f: call ""void System.Console.WriteLine(long)"" IL_0014: ret } "); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [Fact] public void ArraysOfRank1_ParamArray() { var source = @"class C { static void Main() { var t = new Test(); double d = 1.2; t.Test3(d); t.Test3(new double [] {d}); } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (7,17): error CS1503: Argument 1: cannot convert from 'double' to 'params double[*]' // t.Test3(d); Diagnostic(ErrorCode.ERR_BadArgType, "d").WithArguments("1", "double", "params double[*]").WithLocation(7, 17), // (8,17): error CS1503: Argument 1: cannot convert from 'double[]' to 'params double[*]' // t.Test3(new double [] {d}); Diagnostic(ErrorCode.ERR_BadArgType, "new double [] {d}").WithArguments("1", "double[]", "params double[*]").WithLocation(8, 17) ); } [WorkItem(4954, "https://github.com/dotnet/roslyn/issues/4954")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void SizesAndLowerBounds_01() { var ilSource = @" .class public auto ansi beforefieldinit Test extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Test1::.ctor .method public hidebysig newslot virtual instance float64[,] Test1() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test1"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[...,] Test2() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test2"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[...,...] Test3() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test3"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[5,] Test4() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test4"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[5,...] Test5() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test5"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[5,5] Test6() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test6"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[5,2...] Test7() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test7"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[5,2...8] Test8() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test8"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[1...5,] Test9() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test9"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[1...5,...] Test10() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test10"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[1...5,5] Test11() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test11"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[1...5,2...] Test12() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test12"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[1...5,2...8] Test13() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test13"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[1...,] Test14() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test14"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[1...,...] Test15() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test15"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[1...,2...] Test16() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test16"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[1...5] Test17() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test17"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } } // end of class Test "; var source = @"class C : Test { static void Main() { double[,] a; var t = new Test(); a = t.Test1(); a = t.Test2(); a = t.Test3(); a = t.Test4(); a = t.Test5(); a = t.Test6(); a = t.Test7(); a = t.Test8(); a = t.Test9(); a = t.Test10(); a = t.Test11(); a = t.Test12(); a = t.Test13(); a = t.Test14(); a = t.Test15(); a = t.Test16(); t = new C(); a = t.Test1(); a = t.Test2(); a = t.Test3(); a = t.Test4(); a = t.Test5(); a = t.Test6(); a = t.Test7(); a = t.Test8(); a = t.Test9(); a = t.Test10(); a = t.Test11(); a = t.Test12(); a = t.Test13(); a = t.Test14(); a = t.Test15(); a = t.Test16(); } public override double[,] Test1() { System.Console.WriteLine(""Overridden 1""); return null; } public override double[,] Test2() { System.Console.WriteLine(""Overridden 2""); return null; } public override double[,] Test3() { System.Console.WriteLine(""Overridden 3""); return null; } public override double[,] Test4() { System.Console.WriteLine(""Overridden 4""); return null; } public override double[,] Test5() { System.Console.WriteLine(""Overridden 5""); return null; } public override double[,] Test6() { System.Console.WriteLine(""Overridden 6""); return null; } public override double[,] Test7() { System.Console.WriteLine(""Overridden 7""); return null; } public override double[,] Test8() { System.Console.WriteLine(""Overridden 8""); return null; } public override double[,] Test9() { System.Console.WriteLine(""Overridden 9""); return null; } public override double[,] Test10() { System.Console.WriteLine(""Overridden 10""); return null; } public override double[,] Test11() { System.Console.WriteLine(""Overridden 11""); return null; } public override double[,] Test12() { System.Console.WriteLine(""Overridden 12""); return null; } public override double[,] Test13() { System.Console.WriteLine(""Overridden 13""); return null; } public override double[,] Test14() { System.Console.WriteLine(""Overridden 14""); return null; } public override double[,] Test15() { System.Console.WriteLine(""Overridden 15""); return null; } public override double[,] Test16() { System.Console.WriteLine(""Overridden 16""); return null; } } "; var compilation = CreateCompilationWithILAndMscorlib40(source, ilSource, options: TestOptions.ReleaseExe); var test = compilation.GetTypeByMetadataName("Test"); var array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test1").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.True(array.Sizes.IsEmpty); Assert.True(array.LowerBounds.IsEmpty); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test2").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.True(array.Sizes.IsEmpty); Assert.True(array.LowerBounds.IsEmpty); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test3").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.True(array.Sizes.IsEmpty); Assert.True(array.LowerBounds.IsEmpty); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test4").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5 }, array.Sizes); Assert.Equal(new[] { 0 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test5").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5 }, array.Sizes); Assert.Equal(new[] { 0 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test6").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5, 5 }, array.Sizes); Assert.True(array.LowerBounds.IsDefault); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test7").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5 }, array.Sizes); Assert.Equal(new[] { 0, 2 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test8").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5, 7 }, array.Sizes); Assert.Equal(new[] { 0, 2 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test9").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5 }, array.Sizes); Assert.Equal(new[] { 1 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test10").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5 }, array.Sizes); Assert.Equal(new[] { 1 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test11").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5, 5 }, array.Sizes); Assert.Equal(new[] { 1, 0 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test12").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5 }, array.Sizes); Assert.Equal(new[] { 1, 2 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test13").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5, 7 }, array.Sizes); Assert.Equal(new[] { 1, 2 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test14").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.True(array.Sizes.IsEmpty); Assert.Equal(new[] { 1 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test15").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.True(array.Sizes.IsEmpty); Assert.Equal(new[] { 1 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test16").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.True(array.Sizes.IsEmpty); Assert.Equal(new[] { 1, 2 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test17").ReturnType; Assert.Equal("System.Double[*]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(1, array.Rank); Assert.Equal(new[] { 5 }, array.Sizes); Assert.Equal(new[] { 1 }, array.LowerBounds); var verifier = CompileAndVerify(compilation, expectedOutput: @"Test1 Test2 Test3 Test4 Test5 Test6 Test7 Test8 Test9 Test10 Test11 Test12 Test13 Test14 Test15 Test16 Overridden 1 Overridden 2 Overridden 3 Overridden 4 Overridden 5 Overridden 6 Overridden 7 Overridden 8 Overridden 9 Overridden 10 Overridden 11 Overridden 12 Overridden 13 Overridden 14 Overridden 15 Overridden 16 "); } [WorkItem(4954, "https://github.com/dotnet/roslyn/issues/4954")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void SizesAndLowerBounds_02() { var ilSource = @" .class public auto ansi beforefieldinit Test extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Test1::.ctor .method public hidebysig newslot virtual instance void Test1(float64[,] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test1"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test2(float64[...,] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test2"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test3(float64[...,...] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test3"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test4(float64[5,] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test4"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test5(float64[5,...] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test5"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test6(float64[5,5] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test6"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test7(float64[5,2...] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test7"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test8(float64[5,2...8] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test8"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test9(float64[1...5,] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test9"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test10(float64[1...5,...] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test10"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test11(float64[1...5,5] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test11"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test12(float64[1...5,2...] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test12"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test13(float64[1...5,2...8] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test13"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test14(float64[1...,] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test14"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test15(float64[1...,...] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test15"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test16(float64[1...,2...] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test16"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } } // end of class Test "; var source = @"class C : Test { static void Main() { double[,] a = new double [,] {}; var t = new Test(); t.Test1(a); t.Test2(a); t.Test3(a); t.Test4(a); t.Test5(a); t.Test6(a); t.Test7(a); t.Test8(a); t.Test9(a); t.Test10(a); t.Test11(a); t.Test12(a); t.Test13(a); t.Test14(a); t.Test15(a); t.Test16(a); t = new C(); t.Test1(a); t.Test2(a); t.Test3(a); t.Test4(a); t.Test5(a); t.Test6(a); t.Test7(a); t.Test8(a); t.Test9(a); t.Test10(a); t.Test11(a); t.Test12(a); t.Test13(a); t.Test14(a); t.Test15(a); t.Test16(a); } public override void Test1(double[,] x) { System.Console.WriteLine(""Overridden 1""); } public override void Test2(double[,] x) { System.Console.WriteLine(""Overridden 2""); } public override void Test3(double[,] x) { System.Console.WriteLine(""Overridden 3""); } public override void Test4(double[,] x) { System.Console.WriteLine(""Overridden 4""); } public override void Test5(double[,] x) { System.Console.WriteLine(""Overridden 5""); } public override void Test6(double[,] x) { System.Console.WriteLine(""Overridden 6""); } public override void Test7(double[,] x) { System.Console.WriteLine(""Overridden 7""); } public override void Test8(double[,] x) { System.Console.WriteLine(""Overridden 8""); } public override void Test9(double[,] x) { System.Console.WriteLine(""Overridden 9""); } public override void Test10(double[,] x) { System.Console.WriteLine(""Overridden 10""); } public override void Test11(double[,] x) { System.Console.WriteLine(""Overridden 11""); } public override void Test12(double[,] x) { System.Console.WriteLine(""Overridden 12""); } public override void Test13(double[,] x) { System.Console.WriteLine(""Overridden 13""); } public override void Test14(double[,] x) { System.Console.WriteLine(""Overridden 14""); } public override void Test15(double[,] x) { System.Console.WriteLine(""Overridden 15""); } public override void Test16(double[,] x) { System.Console.WriteLine(""Overridden 16""); } } "; var compilation = CreateCompilationWithILAndMscorlib40(source, ilSource, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: @"Test1 Test2 Test3 Test4 Test5 Test6 Test7 Test8 Test9 Test10 Test11 Test12 Test13 Test14 Test15 Test16 Overridden 1 Overridden 2 Overridden 3 Overridden 4 Overridden 5 Overridden 6 Overridden 7 Overridden 8 Overridden 9 Overridden 10 Overridden 11 Overridden 12 Overridden 13 Overridden 14 Overridden 15 Overridden 16 "); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] [WorkItem(4958, "https://github.com/dotnet/roslyn/issues/4958")] public void ArraysOfRank1_InAttributes() { var ilSource = @" .class public auto ansi beforefieldinit Program extends [mscorlib]System.Object { .method public hidebysig instance void Test1() cil managed { .custom instance void TestAttribute::.ctor(class [mscorlib] System.Type) = {type(class 'System.Int32[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')} // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Program::Test1 .method public hidebysig instance void Test2() cil managed { .custom instance void TestAttribute::.ctor(class [mscorlib] System.Type) = {type(class 'System.Int32[*], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')} // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Program::Test2 .method public hidebysig instance void Test3() cil managed { .custom instance void TestAttribute::.ctor(class [mscorlib] System.Type) = {type(class 'System.Int32[*,*], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')} // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Program::Test3 .method public hidebysig instance void Test4() cil managed { .custom instance void TestAttribute::.ctor(class [mscorlib] System.Type) = {type(class 'System.Int32[,*], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')} // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Program::Test4 } // end of class Program .class public auto ansi beforefieldinit TestAttribute extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(class [mscorlib]System.Type val) cil managed { // Code size 9 (0x9) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: nop IL_0007: nop IL_0008: ret } // end of method TestAttribute::.ctor } // end of class TestAttribute "; var source = @" using System; using System.Linq; class C { static void Main() { System.Console.WriteLine(GetTypeFromAttribute(""Test1"")); System.Console.WriteLine(GetTypeFromAttribute(""Test2"")); try { GetTypeFromAttribute(""Test3""); } catch { System.Console.WriteLine(""Throws""); } try { GetTypeFromAttribute(""Test4""); } catch { System.Console.WriteLine(""Throws""); } } private static Type GetTypeFromAttribute(string target) { return (System.Type)typeof(Program).GetMember(target)[0].GetCustomAttributesData().ElementAt(0).ConstructorArguments[0].Value; } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, ilSource, references: new[] { SystemCoreRef }, options: TestOptions.ReleaseExe); var p = compilation.GetTypeByMetadataName("Program"); var a1 = (IArrayTypeSymbol)p.GetMember<MethodSymbol>("Test1").GetAttributes().Single().ConstructorArguments.Single().Value; Assert.Equal("System.Int32[]", a1.ToTestDisplayString()); Assert.Equal(1, a1.Rank); Assert.True(a1.IsSZArray); var a2 = (IArrayTypeSymbol)p.GetMember<MethodSymbol>("Test2").GetAttributes().Single().ConstructorArguments.Single().Value; Assert.Equal("System.Int32[*]", a2.ToTestDisplayString()); Assert.Equal(1, a2.Rank); Assert.False(a2.IsSZArray); Assert.True(((ITypeSymbol)p.GetMember<MethodSymbol>("Test3").GetAttributes().Single().ConstructorArguments.Single().Value).IsErrorType()); Assert.True(((ITypeSymbol)p.GetMember<MethodSymbol>("Test4").GetAttributes().Single().ConstructorArguments.Single().Value).IsErrorType()); CompileAndVerify(compilation, expectedOutput: @"System.Int32[] System.Int32[*] Throws Throws"); } } }
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/Workspaces/VisualBasic/Portable/Simplification/VisualBasicSimplificationService.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.Composition Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Internal.Log Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification <ExportLanguageService(GetType(ISimplificationService), LanguageNames.VisualBasic), [Shared]> Partial Friend Class VisualBasicSimplificationService Inherits AbstractSimplificationService(Of ExpressionSyntax, ExecutableStatementSyntax, CrefReferenceSyntax) Private Shared ReadOnly s_reducers As ImmutableArray(Of AbstractReducer) = ImmutableArray.Create(Of AbstractReducer)( New VisualBasicExtensionMethodReducer(), New VisualBasicCastReducer(), New VisualBasicNameReducer(), New VisualBasicParenthesesReducer(), New VisualBasicCallReducer(), New VisualBasicEscapingReducer(), ' order before VisualBasicMiscellaneousReducer, see RenameNewOverload test New VisualBasicMiscellaneousReducer(), New VisualBasicCastReducer(), New VisualBasicVariableDeclaratorReducer(), New VisualBasicInferredMemberNameReducer()) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() MyBase.New(s_reducers) End Sub Public Overrides Function Expand(node As SyntaxNode, semanticModel As SemanticModel, aliasReplacementAnnotation As SyntaxAnnotation, expandInsideNode As Func(Of SyntaxNode, Boolean), expandParameter As Boolean, cancellationToken As CancellationToken) As SyntaxNode Using Logger.LogBlock(FunctionId.Simplifier_ExpandNode, cancellationToken) If TypeOf node Is ExpressionSyntax OrElse TypeOf node Is StatementSyntax OrElse TypeOf node Is AttributeSyntax OrElse TypeOf node Is SimpleArgumentSyntax OrElse TypeOf node Is CrefReferenceSyntax OrElse TypeOf node Is TypeConstraintSyntax Then Dim rewriter = New Expander(semanticModel, expandInsideNode, cancellationToken, expandParameter, aliasReplacementAnnotation) Return rewriter.Visit(node) Else Throw New ArgumentException( VBWorkspaceResources.Only_attributes_expressions_or_statements_can_be_made_explicit, paramName:=NameOf(node)) End If End Using End Function Public Overrides Function Expand(token As SyntaxToken, semanticModel As SemanticModel, expandInsideNode As Func(Of SyntaxNode, Boolean), cancellationToken As CancellationToken) As SyntaxToken Using Logger.LogBlock(FunctionId.Simplifier_ExpandToken, cancellationToken) Dim rewriter = New Expander(semanticModel, expandInsideNode, cancellationToken) Return TryEscapeIdentifierToken(rewriter.VisitToken(token)) End Using End Function Protected Overrides Function GetSpeculativeSemanticModel(ByRef nodeToSpeculate As SyntaxNode, originalSemanticModel As SemanticModel, originalNode As SyntaxNode) As SemanticModel Contract.ThrowIfNull(nodeToSpeculate) Contract.ThrowIfNull(originalNode) Dim speculativeModel As SemanticModel Dim methodBlockBase = TryCast(nodeToSpeculate, MethodBlockBaseSyntax) ' Speculation over Field Declarations is not supported If originalNode.Kind() = SyntaxKind.VariableDeclarator AndAlso originalNode.Parent.Kind() = SyntaxKind.FieldDeclaration Then Return originalSemanticModel End If If methodBlockBase IsNot Nothing Then ' Certain reducers for VB (escaping, parentheses) require to operate on the entire method body, rather than individual statements. ' Hence, we need to reduce the entire method body as a single unit. ' However, there is no SyntaxNode for the method body or statement list, hence NodesAndTokensToReduceComputer added the MethodBlockBaseSyntax to the list of nodes to be reduced. ' Here we make sure that we create a speculative semantic model for the method body for the given MethodBlockBaseSyntax. Dim originalMethod = DirectCast(originalNode, MethodBlockBaseSyntax) Contract.ThrowIfFalse(originalMethod.Statements.Any(), "How did empty method body get reduced?") Dim position As Integer If originalSemanticModel.IsSpeculativeSemanticModel Then ' Chaining speculative model Not supported, speculate off the original model. Debug.Assert(originalSemanticModel.ParentModel IsNot Nothing) Debug.Assert(Not originalSemanticModel.ParentModel.IsSpeculativeSemanticModel) position = originalSemanticModel.OriginalPositionForSpeculation originalSemanticModel = originalSemanticModel.ParentModel Else position = originalMethod.Statements.First.SpanStart End If speculativeModel = Nothing originalSemanticModel.TryGetSpeculativeSemanticModelForMethodBody(position, methodBlockBase, speculativeModel) Return speculativeModel End If Contract.ThrowIfFalse(SpeculationAnalyzer.CanSpeculateOnNode(nodeToSpeculate)) Dim isAsNewClause = nodeToSpeculate.Kind = SyntaxKind.AsNewClause If isAsNewClause Then ' Currently, there is no support for speculating on an AsNewClauseSyntax node. ' So we synthesize an EqualsValueSyntax with the inner NewExpression and speculate on this EqualsValueSyntax node. Dim asNewClauseNode = DirectCast(nodeToSpeculate, AsNewClauseSyntax) nodeToSpeculate = SyntaxFactory.EqualsValue(asNewClauseNode.NewExpression) nodeToSpeculate = asNewClauseNode.CopyAnnotationsTo(nodeToSpeculate) End If speculativeModel = SpeculationAnalyzer.CreateSpeculativeSemanticModelForNode(originalNode, nodeToSpeculate, originalSemanticModel) If isAsNewClause Then nodeToSpeculate = speculativeModel.SyntaxTree.GetRoot() End If Return speculativeModel End Function Protected Overrides Function TransformReducedNode(reducedNode As SyntaxNode, originalNode As SyntaxNode) As SyntaxNode ' Please see comments within the above GetSpeculativeSemanticModel method for details. If originalNode.Kind = SyntaxKind.AsNewClause AndAlso reducedNode.Kind = SyntaxKind.EqualsValue Then Return originalNode.ReplaceNode(DirectCast(originalNode, AsNewClauseSyntax).NewExpression, DirectCast(reducedNode, EqualsValueSyntax).Value) End If Dim originalMethod = TryCast(originalNode, MethodBlockBaseSyntax) If originalMethod IsNot Nothing Then Dim reducedMethod = DirectCast(reducedNode, MethodBlockBaseSyntax) reducedMethod = reducedMethod.ReplaceNode(reducedMethod.BlockStatement, originalMethod.BlockStatement) Return reducedMethod.ReplaceNode(reducedMethod.EndBlockStatement, originalMethod.EndBlockStatement) End If Return reducedNode End Function Protected Overrides Function GetNodesAndTokensToReduce(root As SyntaxNode, isNodeOrTokenOutsideSimplifySpans As Func(Of SyntaxNodeOrToken, Boolean)) As ImmutableArray(Of NodeOrTokenToReduce) Return NodesAndTokensToReduceComputer.Compute(root, isNodeOrTokenOutsideSimplifySpans) End Function Protected Overrides Function CanNodeBeSimplifiedWithoutSpeculation(node As SyntaxNode) As Boolean Return node IsNot Nothing AndAlso node.Parent IsNot Nothing AndAlso TypeOf node Is VariableDeclaratorSyntax AndAlso TypeOf node.Parent Is FieldDeclarationSyntax End Function Private Const s_BC50000_UnusedImportsClause As String = "BC50000" Private Const s_BC50001_UnusedImportsStatement As String = "BC50001" Protected Overrides Sub GetUnusedNamespaceImports(model As SemanticModel, namespaceImports As HashSet(Of SyntaxNode), cancellationToken As CancellationToken) Dim root = model.SyntaxTree.GetRoot(cancellationToken) Dim diagnostics = model.GetDiagnostics(cancellationToken:=cancellationToken) For Each diagnostic In diagnostics If diagnostic.Id = s_BC50000_UnusedImportsClause OrElse diagnostic.Id = s_BC50001_UnusedImportsStatement Then Dim node = root.FindNode(diagnostic.Location.SourceSpan) Dim statement = TryCast(node, ImportsStatementSyntax) Dim clause = TryCast(node, ImportsStatementSyntax) If statement IsNot Nothing Or clause IsNot Nothing Then namespaceImports.Add(node) End If End If Next 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.Composition Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Internal.Log Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification <ExportLanguageService(GetType(ISimplificationService), LanguageNames.VisualBasic), [Shared]> Partial Friend Class VisualBasicSimplificationService Inherits AbstractSimplificationService(Of ExpressionSyntax, ExecutableStatementSyntax, CrefReferenceSyntax) Private Shared ReadOnly s_reducers As ImmutableArray(Of AbstractReducer) = ImmutableArray.Create(Of AbstractReducer)( New VisualBasicExtensionMethodReducer(), New VisualBasicCastReducer(), New VisualBasicNameReducer(), New VisualBasicParenthesesReducer(), New VisualBasicCallReducer(), New VisualBasicEscapingReducer(), ' order before VisualBasicMiscellaneousReducer, see RenameNewOverload test New VisualBasicMiscellaneousReducer(), New VisualBasicCastReducer(), New VisualBasicVariableDeclaratorReducer(), New VisualBasicInferredMemberNameReducer()) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() MyBase.New(s_reducers) End Sub Public Overrides Function Expand(node As SyntaxNode, semanticModel As SemanticModel, aliasReplacementAnnotation As SyntaxAnnotation, expandInsideNode As Func(Of SyntaxNode, Boolean), expandParameter As Boolean, cancellationToken As CancellationToken) As SyntaxNode Using Logger.LogBlock(FunctionId.Simplifier_ExpandNode, cancellationToken) If TypeOf node Is ExpressionSyntax OrElse TypeOf node Is StatementSyntax OrElse TypeOf node Is AttributeSyntax OrElse TypeOf node Is SimpleArgumentSyntax OrElse TypeOf node Is CrefReferenceSyntax OrElse TypeOf node Is TypeConstraintSyntax Then Dim rewriter = New Expander(semanticModel, expandInsideNode, cancellationToken, expandParameter, aliasReplacementAnnotation) Return rewriter.Visit(node) Else Throw New ArgumentException( VBWorkspaceResources.Only_attributes_expressions_or_statements_can_be_made_explicit, paramName:=NameOf(node)) End If End Using End Function Public Overrides Function Expand(token As SyntaxToken, semanticModel As SemanticModel, expandInsideNode As Func(Of SyntaxNode, Boolean), cancellationToken As CancellationToken) As SyntaxToken Using Logger.LogBlock(FunctionId.Simplifier_ExpandToken, cancellationToken) Dim rewriter = New Expander(semanticModel, expandInsideNode, cancellationToken) Return TryEscapeIdentifierToken(rewriter.VisitToken(token)) End Using End Function Protected Overrides Function GetSpeculativeSemanticModel(ByRef nodeToSpeculate As SyntaxNode, originalSemanticModel As SemanticModel, originalNode As SyntaxNode) As SemanticModel Contract.ThrowIfNull(nodeToSpeculate) Contract.ThrowIfNull(originalNode) Dim speculativeModel As SemanticModel Dim methodBlockBase = TryCast(nodeToSpeculate, MethodBlockBaseSyntax) ' Speculation over Field Declarations is not supported If originalNode.Kind() = SyntaxKind.VariableDeclarator AndAlso originalNode.Parent.Kind() = SyntaxKind.FieldDeclaration Then Return originalSemanticModel End If If methodBlockBase IsNot Nothing Then ' Certain reducers for VB (escaping, parentheses) require to operate on the entire method body, rather than individual statements. ' Hence, we need to reduce the entire method body as a single unit. ' However, there is no SyntaxNode for the method body or statement list, hence NodesAndTokensToReduceComputer added the MethodBlockBaseSyntax to the list of nodes to be reduced. ' Here we make sure that we create a speculative semantic model for the method body for the given MethodBlockBaseSyntax. Dim originalMethod = DirectCast(originalNode, MethodBlockBaseSyntax) Contract.ThrowIfFalse(originalMethod.Statements.Any(), "How did empty method body get reduced?") Dim position As Integer If originalSemanticModel.IsSpeculativeSemanticModel Then ' Chaining speculative model Not supported, speculate off the original model. Debug.Assert(originalSemanticModel.ParentModel IsNot Nothing) Debug.Assert(Not originalSemanticModel.ParentModel.IsSpeculativeSemanticModel) position = originalSemanticModel.OriginalPositionForSpeculation originalSemanticModel = originalSemanticModel.ParentModel Else position = originalMethod.Statements.First.SpanStart End If speculativeModel = Nothing originalSemanticModel.TryGetSpeculativeSemanticModelForMethodBody(position, methodBlockBase, speculativeModel) Return speculativeModel End If Contract.ThrowIfFalse(SpeculationAnalyzer.CanSpeculateOnNode(nodeToSpeculate)) Dim isAsNewClause = nodeToSpeculate.Kind = SyntaxKind.AsNewClause If isAsNewClause Then ' Currently, there is no support for speculating on an AsNewClauseSyntax node. ' So we synthesize an EqualsValueSyntax with the inner NewExpression and speculate on this EqualsValueSyntax node. Dim asNewClauseNode = DirectCast(nodeToSpeculate, AsNewClauseSyntax) nodeToSpeculate = SyntaxFactory.EqualsValue(asNewClauseNode.NewExpression) nodeToSpeculate = asNewClauseNode.CopyAnnotationsTo(nodeToSpeculate) End If speculativeModel = SpeculationAnalyzer.CreateSpeculativeSemanticModelForNode(originalNode, nodeToSpeculate, originalSemanticModel) If isAsNewClause Then nodeToSpeculate = speculativeModel.SyntaxTree.GetRoot() End If Return speculativeModel End Function Protected Overrides Function TransformReducedNode(reducedNode As SyntaxNode, originalNode As SyntaxNode) As SyntaxNode ' Please see comments within the above GetSpeculativeSemanticModel method for details. If originalNode.Kind = SyntaxKind.AsNewClause AndAlso reducedNode.Kind = SyntaxKind.EqualsValue Then Return originalNode.ReplaceNode(DirectCast(originalNode, AsNewClauseSyntax).NewExpression, DirectCast(reducedNode, EqualsValueSyntax).Value) End If Dim originalMethod = TryCast(originalNode, MethodBlockBaseSyntax) If originalMethod IsNot Nothing Then Dim reducedMethod = DirectCast(reducedNode, MethodBlockBaseSyntax) reducedMethod = reducedMethod.ReplaceNode(reducedMethod.BlockStatement, originalMethod.BlockStatement) Return reducedMethod.ReplaceNode(reducedMethod.EndBlockStatement, originalMethod.EndBlockStatement) End If Return reducedNode End Function Protected Overrides Function GetNodesAndTokensToReduce(root As SyntaxNode, isNodeOrTokenOutsideSimplifySpans As Func(Of SyntaxNodeOrToken, Boolean)) As ImmutableArray(Of NodeOrTokenToReduce) Return NodesAndTokensToReduceComputer.Compute(root, isNodeOrTokenOutsideSimplifySpans) End Function Protected Overrides Function CanNodeBeSimplifiedWithoutSpeculation(node As SyntaxNode) As Boolean Return node IsNot Nothing AndAlso node.Parent IsNot Nothing AndAlso TypeOf node Is VariableDeclaratorSyntax AndAlso TypeOf node.Parent Is FieldDeclarationSyntax End Function Private Const s_BC50000_UnusedImportsClause As String = "BC50000" Private Const s_BC50001_UnusedImportsStatement As String = "BC50001" Protected Overrides Sub GetUnusedNamespaceImports(model As SemanticModel, namespaceImports As HashSet(Of SyntaxNode), cancellationToken As CancellationToken) Dim root = model.SyntaxTree.GetRoot(cancellationToken) Dim diagnostics = model.GetDiagnostics(cancellationToken:=cancellationToken) For Each diagnostic In diagnostics If diagnostic.Id = s_BC50000_UnusedImportsClause OrElse diagnostic.Id = s_BC50001_UnusedImportsStatement Then Dim node = root.FindNode(diagnostic.Location.SourceSpan) Dim statement = TryCast(node, ImportsStatementSyntax) Dim clause = TryCast(node, ImportsStatementSyntax) If statement IsNot Nothing Or clause IsNot Nothing Then namespaceImports.Add(node) End If End If Next End Sub End Class End Namespace
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/Compilers/Core/Portable/InternalUtilities/EmptyComparer.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.Runtime.CompilerServices; namespace Roslyn.Utilities { /// <summary> /// Very cheap trivial comparer that never matches the keys, /// should only be used in empty dictionaries. /// </summary> internal sealed class EmptyComparer : IEqualityComparer<object> { public static readonly EmptyComparer Instance = new EmptyComparer(); private EmptyComparer() { } bool IEqualityComparer<object>.Equals(object? a, object? b) { Debug.Assert(false, "Are we using empty comparer with nonempty dictionary?"); return false; } int IEqualityComparer<object>.GetHashCode(object s) { // dictionary will call this often return 0; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; namespace Roslyn.Utilities { /// <summary> /// Very cheap trivial comparer that never matches the keys, /// should only be used in empty dictionaries. /// </summary> internal sealed class EmptyComparer : IEqualityComparer<object> { public static readonly EmptyComparer Instance = new EmptyComparer(); private EmptyComparer() { } bool IEqualityComparer<object>.Equals(object? a, object? b) { Debug.Assert(false, "Are we using empty comparer with nonempty dictionary?"); return false; } int IEqualityComparer<object>.GetHashCode(object s) { // dictionary will call this often return 0; } } }
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/EditorFeatures/VisualBasic/LineCommit/CommitBufferManager.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 System.Threading.Tasks Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.VisualStudio.Text Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit ''' <summary> ''' This class watches for buffer-based events, tracks the dirty regions, and invokes the formatter as appropriate ''' </summary> Partial Friend Class CommitBufferManager Inherits ForegroundThreadAffinitizedObject Private ReadOnly _buffer As ITextBuffer Private ReadOnly _commitFormatter As ICommitFormatter Private ReadOnly _inlineRenameService As IInlineRenameService Private _referencingViews As Integer ''' <summary> ''' An object to use as a sync lock for <see cref="_referencingViews"/>. ''' </summary> Private ReadOnly _referencingViewsLock As Object = New Object() ''' <summary> ''' The tracking span which is the currently "dirty" region in the buffer. May be null if there is no dirty region. ''' </summary> Private _dirtyState As DirtyState Private _documentBeforePreviousEdit As Document ''' <summary> ''' The number of times BeginSuppressingCommits() has been called. ''' </summary> Private _suppressions As Integer Public Sub New( buffer As ITextBuffer, commitFormatter As ICommitFormatter, inlineRenameService As IInlineRenameService, threadingContext As IThreadingContext) MyBase.New(threadingContext, assertIsForeground:=False) Contract.ThrowIfNull(buffer) Contract.ThrowIfNull(commitFormatter) Contract.ThrowIfNull(inlineRenameService) _buffer = buffer _commitFormatter = commitFormatter _inlineRenameService = inlineRenameService End Sub Public Sub AddReferencingView() ThisCanBeCalledOnAnyThread() SyncLock _referencingViewsLock _referencingViews += 1 If _referencingViews = 1 Then AddHandler _buffer.Changing, AddressOf OnTextBufferChanging AddHandler _buffer.Changed, AddressOf OnTextBufferChanged End If End SyncLock End Sub Public Sub RemoveReferencingView() ThisCanBeCalledOnAnyThread() SyncLock _referencingViewsLock ' If someone enables line commit with a file already open, we might end up decrementing ' the ref count too many times, so only do work if we are still above 0. If _referencingViews > 0 Then _referencingViews -= 1 If _referencingViews = 0 Then RemoveHandler _buffer.Changed, AddressOf OnTextBufferChanged RemoveHandler _buffer.Changing, AddressOf OnTextBufferChanging End If End If End SyncLock End Sub Public ReadOnly Property HasDirtyRegion As Boolean Get Return _dirtyState IsNot Nothing End Get End Property ''' <summary> ''' Commits any dirty region, if one exists. ''' ''' To improve perf, passing false to isExplicitFormat will avoid semantic checks when expanding ''' the formatting span to an entire block ''' </summary> Public Sub CommitDirty(isExplicitFormat As Boolean, cancellationToken As CancellationToken) If _inlineRenameService.ActiveSession IsNot Nothing Then _dirtyState = Nothing Return End If If _dirtyState Is Nothing Then Return End If ' Is something else in the commit process suppressing the commit? If _suppressions > 0 Then Return End If Try ' Start to suppress commits to ensure we don't have any sort of re-entrancy in this process. ' We've seen bugs (17015) where waits triggered by some computation might re-enter. Using BeginSuppressingCommits() ' It's possible that an edit may already be in progress. In this scenario, there's ' really nothing we can do, so we'll just skip the format If _buffer.EditInProgress Then Return End If Dim dirtyRegion = _dirtyState.DirtyRegion.GetSpan(_buffer.CurrentSnapshot) Dim info As FormattingInfo If Not TryComputeExpandedSpanToFormat(dirtyRegion, info, cancellationToken) Then Return End If Dim useSemantics = info.UseSemantics If useSemantics AndAlso Not isExplicitFormat Then ' Avoid using semantics for formatting extremely large dirty spans without an explicit request ' from the user. The "large span threshold" is 7000 lines. The 7000 line threshold is an ' estimated value accounting for a lower-bound of the algorithmic complexity of text ' differencing in designer cases along with measurements of a pathological example demonstrated ' at 14000 lines. We expect Windows Forms designer formatting operations to run in under ~15 ' seconds on average current hardware when nearing the threshold. Dim startLineNumber = 0 Dim startCharIndex = 0 Dim endLineNumber = 0 Dim endCharIndex = 0 info.SpanToFormat.GetLinesAndCharacters(startLineNumber, startCharIndex, endLineNumber, endCharIndex) If endLineNumber - startLineNumber > 7000 Then useSemantics = False End If End If Dim tree = _dirtyState.BaseDocument.GetSyntaxTreeSynchronously(cancellationToken) _commitFormatter.CommitRegion(info.SpanToFormat, isExplicitFormat, useSemantics, dirtyRegion, _dirtyState.BaseSnapshot, tree, cancellationToken) End Using Finally ' We may have tracked a dirty region while committing or it may have been aborted. ' In any case, we want to guarantee we have no dirty region once we're done _dirtyState = Nothing End Try End Sub Private Structure FormattingInfo Public UseSemantics As Boolean Public SpanToFormat As SnapshotSpan End Structure Public Sub ExpandDirtyRegion(snapshotSpan As SnapshotSpan) If _dirtyState Is Nothing Then Dim document = snapshotSpan.Snapshot.GetOpenDocumentInCurrentContextWithChanges() If document IsNot Nothing Then _dirtyState = New DirtyState(snapshotSpan, snapshotSpan.Snapshot, document) End If Else _dirtyState = _dirtyState.WithExpandedDirtySpan(snapshotSpan) End If End Sub Private Shared Function TryComputeExpandedSpanToFormat(dirtySpan As SnapshotSpan, ByRef formattingInfo As FormattingInfo, cancellationToken As CancellationToken) As Boolean Dim document = dirtySpan.Snapshot.GetOpenDocumentInCurrentContextWithChanges() If document Is Nothing Then Return False End If formattingInfo.UseSemantics = True Dim tree = document.GetSyntaxTreeSynchronously(cancellationToken) ' No matter what, we will always include the dirty span Dim finalSpanStart = dirtySpan.Start.Position Dim finalSpanEnd = dirtySpan.End.Position ' Find the containing statements Dim startingStatementInfo = ContainingStatementInfo.GetInfo(dirtySpan.Start, tree, cancellationToken) If startingStatementInfo IsNot Nothing Then finalSpanStart = Math.Min(finalSpanStart, startingStatementInfo.TextSpan.Start) If startingStatementInfo.MatchingBlockConstruct IsNot Nothing Then ' If we're expanding backwards because of editing an end construct, we don't wan to run ' expensive semantic formatting checks. We really just want to fix up indentation. formattingInfo.UseSemantics = finalSpanStart <= startingStatementInfo.MatchingBlockConstruct.SpanStart finalSpanStart = Math.Min(finalSpanStart, startingStatementInfo.MatchingBlockConstruct.SpanStart) End If End If Dim endingStatementInfo = If(ContainingStatementInfo.GetInfo(dirtySpan.End, tree, cancellationToken), startingStatementInfo) If endingStatementInfo IsNot Nothing Then finalSpanEnd = Math.Max(finalSpanEnd, endingStatementInfo.TextSpan.End) If endingStatementInfo.MatchingBlockConstruct IsNot Nothing Then finalSpanEnd = Math.Max(finalSpanEnd, endingStatementInfo.MatchingBlockConstruct.Span.End) End If End If Dim startingLine = dirtySpan.Snapshot.GetLineFromPosition(finalSpanStart) If startingLine.LineNumber = 0 Then finalSpanStart = 0 Else ' We want to include the line break into the line before finalSpanStart = dirtySpan.Snapshot.GetLineFromLineNumber(startingLine.LineNumber - 1).End End If formattingInfo.SpanToFormat = New SnapshotSpan(dirtySpan.Snapshot, Span.FromBounds(finalSpanStart, finalSpanEnd)) Return True End Function Public Shared Function IsMovementBetweenStatements(oldPoint As SnapshotPoint, newPoint As SnapshotPoint, cancellationToken As CancellationToken) As Boolean ' If they are the same line, then definitely no If oldPoint.GetContainingLine().LineNumber = newPoint.GetContainingLine().LineNumber Then Return False End If Dim document = newPoint.Snapshot.GetOpenDocumentInCurrentContextWithChanges() If document Is Nothing Then Return False End If Dim tree = document.GetSyntaxTreeSynchronously(cancellationToken) Dim oldStatement = ContainingStatementInfo.GetInfo(oldPoint, tree, cancellationToken) Dim newStatement = ContainingStatementInfo.GetInfo(newPoint, tree, cancellationToken) If oldStatement Is Nothing AndAlso newStatement Is Nothing Then Return True End If If (oldStatement Is Nothing) <> (newStatement Is Nothing) Then Return True End If Return oldStatement.TextSpan <> newStatement.TextSpan End Function Private Sub OnTextBufferChanging(sender As Object, e As TextContentChangingEventArgs) If _dirtyState Is Nothing Then ' Grab the current document for the text buffer before it changes so we can get any ' cached versions Dim documentBeforePreviousEdit = e.Before.GetOpenDocumentInCurrentContextWithChanges() If documentBeforePreviousEdit IsNot Nothing Then _documentBeforePreviousEdit = documentBeforePreviousEdit ' Kick off a task to eagerly force compute InternalsVisibleTo semantics for all the references. ' This provides a noticeable perf improvement when code cleanup is subsequently invoked on this document. Task.Run(Async Function() Await ForceComputeInternalsVisibleToAsync(documentBeforePreviousEdit, CancellationToken.None).ConfigureAwait(False) End Function) End If End If End Sub Private Sub OnTextBufferChanged(sender As Object, e As TextContentChangedEventArgs) ' Before we do anything else, ensure the field is nulled back out Dim documentBeforePreviousEdit = _documentBeforePreviousEdit _documentBeforePreviousEdit = Nothing If e.Changes.Count = 0 Then Return End If ' If this is a reiterated version, then it's part of undo/redo and we should ignore it If e.AfterVersion.ReiteratedVersionNumber <> e.AfterVersion.VersionNumber Then Return End If ' Add this region into our dirty region Dim encompassingNewSpan = New SnapshotSpan(e.After, Span.FromBounds(e.Changes.First().NewPosition, e.Changes.Last().NewEnd)) If _dirtyState Is Nothing Then ' Some times, we won't get a documentBeforePreviousEdit. This happens because sometimes OnTextBufferChanging ' isn't called before OnTextBufferChanged in undo scenarios. In those cases, since we can't set up valid state, ' just throw it out If documentBeforePreviousEdit IsNot Nothing Then _dirtyState = New DirtyState(encompassingNewSpan, e.Before, documentBeforePreviousEdit) End If Else _dirtyState = _dirtyState.WithExpandedDirtySpan(encompassingNewSpan) End If End Sub Private Shared Async Function ForceComputeInternalsVisibleToAsync(document As Document, cancellationToken As CancellationToken) As Task Dim project = document.Project Dim compilation = Await project.GetCompilationAsync(cancellationToken).ConfigureAwait(False) For Each reference In project.ProjectReferences Dim refProject = project.Solution.GetProject(reference.ProjectId) If refProject IsNot Nothing Then Dim refCompilation = Await refProject.GetCompilationAsync(cancellationToken).ConfigureAwait(False) refCompilation.Assembly().GivesAccessTo(compilation.Assembly) End If Next For Each reference In project.MetadataReferences Dim refAssemblyOrModule = compilation.GetAssemblyOrModuleSymbol(reference) If refAssemblyOrModule.MatchesKind(SymbolKind.Assembly) Then Dim refAssembly = DirectCast(refAssemblyOrModule, IAssemblySymbol) refAssembly.GivesAccessTo(compilation.Assembly) End If Next End Function ''' <summary> ''' Suppresses future commits, causing all calls to CommitDirty() to be a simple no-op, even ''' if there is a dirty span. ''' </summary> ''' <returns>An IDisposable that should be disposed when the caller wants to resume ''' submissions.</returns> Friend Function BeginSuppressingCommits() As IDisposable _suppressions += 1 Return New SuppressionHandle(Me) End Function Private Class SuppressionHandle Implements IDisposable Private _manager As CommitBufferManager Public Sub New(manager As CommitBufferManager) Contract.ThrowIfNull(manager) _manager = manager End Sub Public Sub Dispose() Implements IDisposable.Dispose _manager._suppressions -= 1 _manager = Nothing 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.Threading Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.VisualStudio.Text Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit ''' <summary> ''' This class watches for buffer-based events, tracks the dirty regions, and invokes the formatter as appropriate ''' </summary> Partial Friend Class CommitBufferManager Inherits ForegroundThreadAffinitizedObject Private ReadOnly _buffer As ITextBuffer Private ReadOnly _commitFormatter As ICommitFormatter Private ReadOnly _inlineRenameService As IInlineRenameService Private _referencingViews As Integer ''' <summary> ''' An object to use as a sync lock for <see cref="_referencingViews"/>. ''' </summary> Private ReadOnly _referencingViewsLock As Object = New Object() ''' <summary> ''' The tracking span which is the currently "dirty" region in the buffer. May be null if there is no dirty region. ''' </summary> Private _dirtyState As DirtyState Private _documentBeforePreviousEdit As Document ''' <summary> ''' The number of times BeginSuppressingCommits() has been called. ''' </summary> Private _suppressions As Integer Public Sub New( buffer As ITextBuffer, commitFormatter As ICommitFormatter, inlineRenameService As IInlineRenameService, threadingContext As IThreadingContext) MyBase.New(threadingContext, assertIsForeground:=False) Contract.ThrowIfNull(buffer) Contract.ThrowIfNull(commitFormatter) Contract.ThrowIfNull(inlineRenameService) _buffer = buffer _commitFormatter = commitFormatter _inlineRenameService = inlineRenameService End Sub Public Sub AddReferencingView() ThisCanBeCalledOnAnyThread() SyncLock _referencingViewsLock _referencingViews += 1 If _referencingViews = 1 Then AddHandler _buffer.Changing, AddressOf OnTextBufferChanging AddHandler _buffer.Changed, AddressOf OnTextBufferChanged End If End SyncLock End Sub Public Sub RemoveReferencingView() ThisCanBeCalledOnAnyThread() SyncLock _referencingViewsLock ' If someone enables line commit with a file already open, we might end up decrementing ' the ref count too many times, so only do work if we are still above 0. If _referencingViews > 0 Then _referencingViews -= 1 If _referencingViews = 0 Then RemoveHandler _buffer.Changed, AddressOf OnTextBufferChanged RemoveHandler _buffer.Changing, AddressOf OnTextBufferChanging End If End If End SyncLock End Sub Public ReadOnly Property HasDirtyRegion As Boolean Get Return _dirtyState IsNot Nothing End Get End Property ''' <summary> ''' Commits any dirty region, if one exists. ''' ''' To improve perf, passing false to isExplicitFormat will avoid semantic checks when expanding ''' the formatting span to an entire block ''' </summary> Public Sub CommitDirty(isExplicitFormat As Boolean, cancellationToken As CancellationToken) If _inlineRenameService.ActiveSession IsNot Nothing Then _dirtyState = Nothing Return End If If _dirtyState Is Nothing Then Return End If ' Is something else in the commit process suppressing the commit? If _suppressions > 0 Then Return End If Try ' Start to suppress commits to ensure we don't have any sort of re-entrancy in this process. ' We've seen bugs (17015) where waits triggered by some computation might re-enter. Using BeginSuppressingCommits() ' It's possible that an edit may already be in progress. In this scenario, there's ' really nothing we can do, so we'll just skip the format If _buffer.EditInProgress Then Return End If Dim dirtyRegion = _dirtyState.DirtyRegion.GetSpan(_buffer.CurrentSnapshot) Dim info As FormattingInfo If Not TryComputeExpandedSpanToFormat(dirtyRegion, info, cancellationToken) Then Return End If Dim useSemantics = info.UseSemantics If useSemantics AndAlso Not isExplicitFormat Then ' Avoid using semantics for formatting extremely large dirty spans without an explicit request ' from the user. The "large span threshold" is 7000 lines. The 7000 line threshold is an ' estimated value accounting for a lower-bound of the algorithmic complexity of text ' differencing in designer cases along with measurements of a pathological example demonstrated ' at 14000 lines. We expect Windows Forms designer formatting operations to run in under ~15 ' seconds on average current hardware when nearing the threshold. Dim startLineNumber = 0 Dim startCharIndex = 0 Dim endLineNumber = 0 Dim endCharIndex = 0 info.SpanToFormat.GetLinesAndCharacters(startLineNumber, startCharIndex, endLineNumber, endCharIndex) If endLineNumber - startLineNumber > 7000 Then useSemantics = False End If End If Dim tree = _dirtyState.BaseDocument.GetSyntaxTreeSynchronously(cancellationToken) _commitFormatter.CommitRegion(info.SpanToFormat, isExplicitFormat, useSemantics, dirtyRegion, _dirtyState.BaseSnapshot, tree, cancellationToken) End Using Finally ' We may have tracked a dirty region while committing or it may have been aborted. ' In any case, we want to guarantee we have no dirty region once we're done _dirtyState = Nothing End Try End Sub Private Structure FormattingInfo Public UseSemantics As Boolean Public SpanToFormat As SnapshotSpan End Structure Public Sub ExpandDirtyRegion(snapshotSpan As SnapshotSpan) If _dirtyState Is Nothing Then Dim document = snapshotSpan.Snapshot.GetOpenDocumentInCurrentContextWithChanges() If document IsNot Nothing Then _dirtyState = New DirtyState(snapshotSpan, snapshotSpan.Snapshot, document) End If Else _dirtyState = _dirtyState.WithExpandedDirtySpan(snapshotSpan) End If End Sub Private Shared Function TryComputeExpandedSpanToFormat(dirtySpan As SnapshotSpan, ByRef formattingInfo As FormattingInfo, cancellationToken As CancellationToken) As Boolean Dim document = dirtySpan.Snapshot.GetOpenDocumentInCurrentContextWithChanges() If document Is Nothing Then Return False End If formattingInfo.UseSemantics = True Dim tree = document.GetSyntaxTreeSynchronously(cancellationToken) ' No matter what, we will always include the dirty span Dim finalSpanStart = dirtySpan.Start.Position Dim finalSpanEnd = dirtySpan.End.Position ' Find the containing statements Dim startingStatementInfo = ContainingStatementInfo.GetInfo(dirtySpan.Start, tree, cancellationToken) If startingStatementInfo IsNot Nothing Then finalSpanStart = Math.Min(finalSpanStart, startingStatementInfo.TextSpan.Start) If startingStatementInfo.MatchingBlockConstruct IsNot Nothing Then ' If we're expanding backwards because of editing an end construct, we don't wan to run ' expensive semantic formatting checks. We really just want to fix up indentation. formattingInfo.UseSemantics = finalSpanStart <= startingStatementInfo.MatchingBlockConstruct.SpanStart finalSpanStart = Math.Min(finalSpanStart, startingStatementInfo.MatchingBlockConstruct.SpanStart) End If End If Dim endingStatementInfo = If(ContainingStatementInfo.GetInfo(dirtySpan.End, tree, cancellationToken), startingStatementInfo) If endingStatementInfo IsNot Nothing Then finalSpanEnd = Math.Max(finalSpanEnd, endingStatementInfo.TextSpan.End) If endingStatementInfo.MatchingBlockConstruct IsNot Nothing Then finalSpanEnd = Math.Max(finalSpanEnd, endingStatementInfo.MatchingBlockConstruct.Span.End) End If End If Dim startingLine = dirtySpan.Snapshot.GetLineFromPosition(finalSpanStart) If startingLine.LineNumber = 0 Then finalSpanStart = 0 Else ' We want to include the line break into the line before finalSpanStart = dirtySpan.Snapshot.GetLineFromLineNumber(startingLine.LineNumber - 1).End End If formattingInfo.SpanToFormat = New SnapshotSpan(dirtySpan.Snapshot, Span.FromBounds(finalSpanStart, finalSpanEnd)) Return True End Function Public Shared Function IsMovementBetweenStatements(oldPoint As SnapshotPoint, newPoint As SnapshotPoint, cancellationToken As CancellationToken) As Boolean ' If they are the same line, then definitely no If oldPoint.GetContainingLine().LineNumber = newPoint.GetContainingLine().LineNumber Then Return False End If Dim document = newPoint.Snapshot.GetOpenDocumentInCurrentContextWithChanges() If document Is Nothing Then Return False End If Dim tree = document.GetSyntaxTreeSynchronously(cancellationToken) Dim oldStatement = ContainingStatementInfo.GetInfo(oldPoint, tree, cancellationToken) Dim newStatement = ContainingStatementInfo.GetInfo(newPoint, tree, cancellationToken) If oldStatement Is Nothing AndAlso newStatement Is Nothing Then Return True End If If (oldStatement Is Nothing) <> (newStatement Is Nothing) Then Return True End If Return oldStatement.TextSpan <> newStatement.TextSpan End Function Private Sub OnTextBufferChanging(sender As Object, e As TextContentChangingEventArgs) If _dirtyState Is Nothing Then ' Grab the current document for the text buffer before it changes so we can get any ' cached versions Dim documentBeforePreviousEdit = e.Before.GetOpenDocumentInCurrentContextWithChanges() If documentBeforePreviousEdit IsNot Nothing Then _documentBeforePreviousEdit = documentBeforePreviousEdit ' Kick off a task to eagerly force compute InternalsVisibleTo semantics for all the references. ' This provides a noticeable perf improvement when code cleanup is subsequently invoked on this document. Task.Run(Async Function() Await ForceComputeInternalsVisibleToAsync(documentBeforePreviousEdit, CancellationToken.None).ConfigureAwait(False) End Function) End If End If End Sub Private Sub OnTextBufferChanged(sender As Object, e As TextContentChangedEventArgs) ' Before we do anything else, ensure the field is nulled back out Dim documentBeforePreviousEdit = _documentBeforePreviousEdit _documentBeforePreviousEdit = Nothing If e.Changes.Count = 0 Then Return End If ' If this is a reiterated version, then it's part of undo/redo and we should ignore it If e.AfterVersion.ReiteratedVersionNumber <> e.AfterVersion.VersionNumber Then Return End If ' Add this region into our dirty region Dim encompassingNewSpan = New SnapshotSpan(e.After, Span.FromBounds(e.Changes.First().NewPosition, e.Changes.Last().NewEnd)) If _dirtyState Is Nothing Then ' Some times, we won't get a documentBeforePreviousEdit. This happens because sometimes OnTextBufferChanging ' isn't called before OnTextBufferChanged in undo scenarios. In those cases, since we can't set up valid state, ' just throw it out If documentBeforePreviousEdit IsNot Nothing Then _dirtyState = New DirtyState(encompassingNewSpan, e.Before, documentBeforePreviousEdit) End If Else _dirtyState = _dirtyState.WithExpandedDirtySpan(encompassingNewSpan) End If End Sub Private Shared Async Function ForceComputeInternalsVisibleToAsync(document As Document, cancellationToken As CancellationToken) As Task Dim project = document.Project Dim compilation = Await project.GetCompilationAsync(cancellationToken).ConfigureAwait(False) For Each reference In project.ProjectReferences Dim refProject = project.Solution.GetProject(reference.ProjectId) If refProject IsNot Nothing Then Dim refCompilation = Await refProject.GetCompilationAsync(cancellationToken).ConfigureAwait(False) refCompilation.Assembly().GivesAccessTo(compilation.Assembly) End If Next For Each reference In project.MetadataReferences Dim refAssemblyOrModule = compilation.GetAssemblyOrModuleSymbol(reference) If refAssemblyOrModule.MatchesKind(SymbolKind.Assembly) Then Dim refAssembly = DirectCast(refAssemblyOrModule, IAssemblySymbol) refAssembly.GivesAccessTo(compilation.Assembly) End If Next End Function ''' <summary> ''' Suppresses future commits, causing all calls to CommitDirty() to be a simple no-op, even ''' if there is a dirty span. ''' </summary> ''' <returns>An IDisposable that should be disposed when the caller wants to resume ''' submissions.</returns> Friend Function BeginSuppressingCommits() As IDisposable _suppressions += 1 Return New SuppressionHandle(Me) End Function Private Class SuppressionHandle Implements IDisposable Private _manager As CommitBufferManager Public Sub New(manager As CommitBufferManager) Contract.ThrowIfNull(manager) _manager = manager End Sub Public Sub Dispose() Implements IDisposable.Dispose _manager._suppressions -= 1 _manager = Nothing End Sub End Class End Class End Namespace
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/Compilers/Test/Resources/Core/SymbolsTests/Methods/VBMethods.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. ' vbc /t:library VBMethods.vb Public Class C1 Public Sub M1(x As Integer) End Sub Public Sub M2(<System.Runtime.InteropServices.Optional()> ByVal x As Integer) End Sub Public Sub M3(Optional x As Integer = 11) End Sub Public Sub M4(<System.Runtime.InteropServices.Optional(), System.Runtime.InteropServices.DefaultParameterValue(12)> ByVal x As Integer) End Sub Public Sub M5(ByVal x As Integer) End Sub Public Sub M6(ByVal x As Integer) End Sub Public Sub M7(Of T)(ByVal x As Integer) End Sub Public Sub M8(Of T)(ByVal x As Integer) End Sub Public Sub M9(ByVal x As Integer) End Sub Public Sub M9(Of T)(ByVal x As Integer) End Sub Public Sub M10(Of T1)(ByVal x As T1) End Sub Public Function M11(Of T2, T3 As C1)(ByVal x As T2) As T3 Return Nothing End Function Public Sub M12(ByVal x As Integer) End Sub Public Declare Auto Function LoadLibrary Lib "Kernel32.dll" (ByVal lpFileName As String) As IntPtr End Class Public Structure EmptyStructure End Structure Public Class C2(Of T4) Public Sub M1(Of T5)(ByVal x As T5, ByVal y As T4) End Sub End Class Public MustInherit Class Modifiers1 Public MustOverride Sub M1() Public Overridable Sub M2() End Sub Public Overloads Sub M3() End Sub Public Sub M4() End Sub Public Shadows Sub M5() End Sub Public MustOverride Overloads Sub M6() Public Overridable Overloads Sub M7() End Sub Public MustOverride Shadows Sub M8() Public Overridable Shadows Sub M9() End Sub End Class Public MustInherit Class Modifiers2 Inherits Modifiers1 Public MustOverride Overrides Sub M1() Public NotOverridable Overrides Sub M2() End Sub Public MustOverride Overloads Overrides Sub M6() Public NotOverridable Overloads Overrides Sub M7() End Sub ' 'Overrides' and 'Shadows' cannot be combined 'Public MustOverride Overrides Shadows Sub M8() ' 'Overrides' and 'Shadows' cannot be combined 'Public NotOverridable Overrides Shadows Sub M9() 'End Sub End Class Public MustInherit Class Modifiers3 Inherits Modifiers1 Public Overrides Sub M1() End Sub Public Overloads Overrides Sub M6() End Sub 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. ' vbc /t:library VBMethods.vb Public Class C1 Public Sub M1(x As Integer) End Sub Public Sub M2(<System.Runtime.InteropServices.Optional()> ByVal x As Integer) End Sub Public Sub M3(Optional x As Integer = 11) End Sub Public Sub M4(<System.Runtime.InteropServices.Optional(), System.Runtime.InteropServices.DefaultParameterValue(12)> ByVal x As Integer) End Sub Public Sub M5(ByVal x As Integer) End Sub Public Sub M6(ByVal x As Integer) End Sub Public Sub M7(Of T)(ByVal x As Integer) End Sub Public Sub M8(Of T)(ByVal x As Integer) End Sub Public Sub M9(ByVal x As Integer) End Sub Public Sub M9(Of T)(ByVal x As Integer) End Sub Public Sub M10(Of T1)(ByVal x As T1) End Sub Public Function M11(Of T2, T3 As C1)(ByVal x As T2) As T3 Return Nothing End Function Public Sub M12(ByVal x As Integer) End Sub Public Declare Auto Function LoadLibrary Lib "Kernel32.dll" (ByVal lpFileName As String) As IntPtr End Class Public Structure EmptyStructure End Structure Public Class C2(Of T4) Public Sub M1(Of T5)(ByVal x As T5, ByVal y As T4) End Sub End Class Public MustInherit Class Modifiers1 Public MustOverride Sub M1() Public Overridable Sub M2() End Sub Public Overloads Sub M3() End Sub Public Sub M4() End Sub Public Shadows Sub M5() End Sub Public MustOverride Overloads Sub M6() Public Overridable Overloads Sub M7() End Sub Public MustOverride Shadows Sub M8() Public Overridable Shadows Sub M9() End Sub End Class Public MustInherit Class Modifiers2 Inherits Modifiers1 Public MustOverride Overrides Sub M1() Public NotOverridable Overrides Sub M2() End Sub Public MustOverride Overloads Overrides Sub M6() Public NotOverridable Overloads Overrides Sub M7() End Sub ' 'Overrides' and 'Shadows' cannot be combined 'Public MustOverride Overrides Shadows Sub M8() ' 'Overrides' and 'Shadows' cannot be combined 'Public NotOverridable Overrides Shadows Sub M9() 'End Sub End Class Public MustInherit Class Modifiers3 Inherits Modifiers1 Public Overrides Sub M1() End Sub Public Overloads Overrides Sub M6() End Sub End Class
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/EditorFeatures/Core/Implementation/InlineRename/Taggers/RenameTaggerProvider.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.Text; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { [Export(typeof(ITaggerProvider))] [ContentType(ContentTypeNames.RoslynContentType)] [ContentType(ContentTypeNames.XamlContentType)] [TagType(typeof(ITextMarkerTag))] internal class RenameTaggerProvider : ITaggerProvider { private readonly InlineRenameService _renameService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RenameTaggerProvider(InlineRenameService renameService) => _renameService = renameService; public ITagger<T> CreateTagger<T>(ITextBuffer buffer) where T : ITag => new RenameTagger(buffer, _renameService) as ITagger<T>; } }
// Licensed to the .NET Foundation under one or more 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.Text; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { [Export(typeof(ITaggerProvider))] [ContentType(ContentTypeNames.RoslynContentType)] [ContentType(ContentTypeNames.XamlContentType)] [TagType(typeof(ITextMarkerTag))] internal class RenameTaggerProvider : ITaggerProvider { private readonly InlineRenameService _renameService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RenameTaggerProvider(InlineRenameService renameService) => _renameService = renameService; public ITagger<T> CreateTagger<T>(ITextBuffer buffer) where T : ITag => new RenameTagger(buffer, _renameService) as ITagger<T>; } }
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/PreprocessorDirectives/IfDirectiveKeywordRecommender.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 Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.PreprocessorDirectives ''' <summary> ''' Recommends the "#If" preprocessor directive ''' </summary> Friend Class IfDirectiveKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("#If", VBFeaturesResources.Conditionally_compiles_selected_blocks_of_code_depending_on_the_value_of_an_expression)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) Return If(context.IsPreprocessorStartContext AndAlso Not context.SyntaxTree.IsEnumMemberNameContext(context), s_keywords, 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 Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.PreprocessorDirectives ''' <summary> ''' Recommends the "#If" preprocessor directive ''' </summary> Friend Class IfDirectiveKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("#If", VBFeaturesResources.Conditionally_compiles_selected_blocks_of_code_depending_on_the_value_of_an_expression)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) Return If(context.IsPreprocessorStartContext AndAlso Not context.SyntaxTree.IsEnumMemberNameContext(context), s_keywords, ImmutableArray(Of RecommendedKeyword).Empty) End Function End Class End Namespace
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/Workspaces/Core/MSBuild/xlf/WorkspaceMSBuildResources.ru.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="ru" original="../WorkspaceMSBuildResources.resx"> <body> <trans-unit id="Failed_to_load_solution_filter_0"> <source>Failed to load solution filter: '{0}'</source> <target state="translated">Не удалось загрузить фильтр решений: "{0}"</target> <note /> </trans-unit> <trans-unit id="Found_project_reference_without_a_matching_metadata_reference_0"> <source>Found project reference without a matching metadata reference: {0}</source> <target state="translated">Обнаружена ссылка на проект без соответствующей ссылки на метаданные: {0}</target> <note /> </trans-unit> <trans-unit id="Invalid_0_specified_1"> <source>Invalid {0} specified: {1}</source> <target state="translated">Указан недопустимый элемент {0}: {1}</target> <note /> </trans-unit> <trans-unit id="Msbuild_failed_when_processing_the_file_0"> <source>Msbuild failed when processing the file '{0}'</source> <target state="translated">Сбой Msbuild при обработке файла "{0}"</target> <note /> </trans-unit> <trans-unit id="Msbuild_failed_when_processing_the_file_0_with_message_1"> <source>Msbuild failed when processing the file '{0}' with message: {1}</source> <target state="translated">Сбой Msbuild при обработке файла "{0}" с сообщением: {1}</target> <note /> </trans-unit> <trans-unit id="Parameter_cannot_be_null_empty_or_contain_whitespace"> <source>Parameter cannot be null, empty, or contain whitespace.</source> <target state="translated">Параметр не может иметь значение NULL, быть пустым или содержать пробелы.</target> <note /> </trans-unit> <trans-unit id="Path_for_additional_document_0_was_null"> <source>Path for additional document '{0}' was null}</source> <target state="translated">Путь к дополнительному документу "{0}" имел значение NULL}</target> <note /> </trans-unit> <trans-unit id="Path_for_document_0_was_null"> <source>Path for document '{0}' was null</source> <target state="translated">Путь для документа "{0}" имел значение NULL</target> <note /> </trans-unit> <trans-unit id="Project_already_added"> <source>Project already added.</source> <target state="translated">Проект уже добавлен.</target> <note /> </trans-unit> <trans-unit id="Project_does_not_contain_0_target"> <source>Project does not contain '{0}' target.</source> <target state="translated">Проект не содержит целевого объекта "{0}".</target> <note /> </trans-unit> <trans-unit id="Found_project_with_the_same_file_path_and_output_path_as_another_project_0"> <source>Found project with the same file path and output path as another project: {0}</source> <target state="translated">Найден проект, путь к файлу и выходной путь которого совпадают с путями другого проекта: {0}</target> <note /> </trans-unit> <trans-unit id="Duplicate_project_discovered_and_skipped_0"> <source>Duplicate project discovered and skipped: {0}</source> <target state="translated">Обнаружен и пропущен повторяющийся проект: {0}</target> <note /> </trans-unit> <trans-unit id="Project_does_not_have_a_path"> <source>Project does not have a path.</source> <target state="translated">У проекта нет пути.</target> <note /> </trans-unit> <trans-unit id="Project_path_for_0_was_null"> <source>Project path for '{0}' was null</source> <target state="translated">Путь проекта для "{0}" имел значение NULL</target> <note /> </trans-unit> <trans-unit id="Unable_to_add_metadata_reference_0"> <source>Unable to add metadata reference '{0}'</source> <target state="translated">Не удается добавить ссылку на метаданные "{0}"</target> <note /> </trans-unit> <trans-unit id="Unable_to_find_0"> <source>Unable to find '{0}'</source> <target state="translated">Невозможно найти "{0}"</target> <note /> </trans-unit> <trans-unit id="Unable_to_find_a_0_for_1"> <source>Unable to find a '{0}' for '{1}'</source> <target state="translated">Не удается найти "{0}" для "{1}"</target> <note /> </trans-unit> <trans-unit id="Unable_to_remove_metadata_reference_0"> <source>Unable to remove metadata reference '{0}'</source> <target state="translated">Не удается удалить ссылку на метаданные "{0}"</target> <note /> </trans-unit> <trans-unit id="Unresolved_metadata_reference_removed_from_project_0"> <source>Unresolved metadata reference removed from project: {0}</source> <target state="translated">Неразрешенная ссылка на метаданные удалена из проекта: {0}</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="ru" original="../WorkspaceMSBuildResources.resx"> <body> <trans-unit id="Failed_to_load_solution_filter_0"> <source>Failed to load solution filter: '{0}'</source> <target state="translated">Не удалось загрузить фильтр решений: "{0}"</target> <note /> </trans-unit> <trans-unit id="Found_project_reference_without_a_matching_metadata_reference_0"> <source>Found project reference without a matching metadata reference: {0}</source> <target state="translated">Обнаружена ссылка на проект без соответствующей ссылки на метаданные: {0}</target> <note /> </trans-unit> <trans-unit id="Invalid_0_specified_1"> <source>Invalid {0} specified: {1}</source> <target state="translated">Указан недопустимый элемент {0}: {1}</target> <note /> </trans-unit> <trans-unit id="Msbuild_failed_when_processing_the_file_0"> <source>Msbuild failed when processing the file '{0}'</source> <target state="translated">Сбой Msbuild при обработке файла "{0}"</target> <note /> </trans-unit> <trans-unit id="Msbuild_failed_when_processing_the_file_0_with_message_1"> <source>Msbuild failed when processing the file '{0}' with message: {1}</source> <target state="translated">Сбой Msbuild при обработке файла "{0}" с сообщением: {1}</target> <note /> </trans-unit> <trans-unit id="Parameter_cannot_be_null_empty_or_contain_whitespace"> <source>Parameter cannot be null, empty, or contain whitespace.</source> <target state="translated">Параметр не может иметь значение NULL, быть пустым или содержать пробелы.</target> <note /> </trans-unit> <trans-unit id="Path_for_additional_document_0_was_null"> <source>Path for additional document '{0}' was null}</source> <target state="translated">Путь к дополнительному документу "{0}" имел значение NULL}</target> <note /> </trans-unit> <trans-unit id="Path_for_document_0_was_null"> <source>Path for document '{0}' was null</source> <target state="translated">Путь для документа "{0}" имел значение NULL</target> <note /> </trans-unit> <trans-unit id="Project_already_added"> <source>Project already added.</source> <target state="translated">Проект уже добавлен.</target> <note /> </trans-unit> <trans-unit id="Project_does_not_contain_0_target"> <source>Project does not contain '{0}' target.</source> <target state="translated">Проект не содержит целевого объекта "{0}".</target> <note /> </trans-unit> <trans-unit id="Found_project_with_the_same_file_path_and_output_path_as_another_project_0"> <source>Found project with the same file path and output path as another project: {0}</source> <target state="translated">Найден проект, путь к файлу и выходной путь которого совпадают с путями другого проекта: {0}</target> <note /> </trans-unit> <trans-unit id="Duplicate_project_discovered_and_skipped_0"> <source>Duplicate project discovered and skipped: {0}</source> <target state="translated">Обнаружен и пропущен повторяющийся проект: {0}</target> <note /> </trans-unit> <trans-unit id="Project_does_not_have_a_path"> <source>Project does not have a path.</source> <target state="translated">У проекта нет пути.</target> <note /> </trans-unit> <trans-unit id="Project_path_for_0_was_null"> <source>Project path for '{0}' was null</source> <target state="translated">Путь проекта для "{0}" имел значение NULL</target> <note /> </trans-unit> <trans-unit id="Unable_to_add_metadata_reference_0"> <source>Unable to add metadata reference '{0}'</source> <target state="translated">Не удается добавить ссылку на метаданные "{0}"</target> <note /> </trans-unit> <trans-unit id="Unable_to_find_0"> <source>Unable to find '{0}'</source> <target state="translated">Невозможно найти "{0}"</target> <note /> </trans-unit> <trans-unit id="Unable_to_find_a_0_for_1"> <source>Unable to find a '{0}' for '{1}'</source> <target state="translated">Не удается найти "{0}" для "{1}"</target> <note /> </trans-unit> <trans-unit id="Unable_to_remove_metadata_reference_0"> <source>Unable to remove metadata reference '{0}'</source> <target state="translated">Не удается удалить ссылку на метаданные "{0}"</target> <note /> </trans-unit> <trans-unit id="Unresolved_metadata_reference_removed_from_project_0"> <source>Unresolved metadata reference removed from project: {0}</source> <target state="translated">Неразрешенная ссылка на метаданные удалена из проекта: {0}</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/Tools/Source/CompilerGeneratorTools/Source/BoundTreeGenerator/app.config
<?xml version="1.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. --> <configuration> <startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>
<?xml version="1.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. --> <configuration> <startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/Workspaces/Core/Portable/Shared/RuntimeOptions.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.Options; namespace Microsoft.CodeAnalysis.Shared.Options { /// <summary> /// Options that aren't persisted. options here will be reset to default on new process. /// </summary> internal static class RuntimeOptions { public static readonly Option<bool> BackgroundAnalysisSuspendedInfoBarShown = new(nameof(RuntimeOptions), "FullSolutionAnalysisInfoBarShown", defaultValue: 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 Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Shared.Options { /// <summary> /// Options that aren't persisted. options here will be reset to default on new process. /// </summary> internal static class RuntimeOptions { public static readonly Option<bool> BackgroundAnalysisSuspendedInfoBarShown = new(nameof(RuntimeOptions), "FullSolutionAnalysisInfoBarShown", defaultValue: false); } }
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/Workspaces/Core/Desktop/Workspace/Host/Mef/DesktopMefHostServices.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.Reflection; namespace Microsoft.CodeAnalysis.Host.Mef { public static class DesktopMefHostServices { public static MefHostServices DefaultServices => MefHostServices.DefaultHost; public static ImmutableArray<Assembly> DefaultAssemblies => MefHostServices.DefaultAssemblies; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Reflection; namespace Microsoft.CodeAnalysis.Host.Mef { public static class DesktopMefHostServices { public static MefHostServices DefaultServices => MefHostServices.DefaultHost; public static ImmutableArray<Assembly> DefaultAssemblies => MefHostServices.DefaultAssemblies; } }
-1
dotnet/roslyn
56,132
Remove the HasCompilation flag.
Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
CyrusNajmabadi
"2021-09-02T19:52:40Z"
"2021-09-07T19:29:03Z"
5851730e82f7805df3559444fd0f605243bd1adf
7955a0a36c470caad04c7c765d0df666bad4860e
Remove the HasCompilation flag.. Seems to be an odd flag that just allows us to dump prior compilation trackers we might have created *but* which didn't have at least some compilatino in them. And all we're saving then is the allocation of a tiny object corresponding to that project. This seems like extra unnecessary complexity (in a very complex area) for no benefit.
./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter.PatternLocalRewriter.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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { /// <summary> /// A common base class for lowering constructs that use pattern-matching. /// </summary> private abstract class PatternLocalRewriter { protected readonly LocalRewriter _localRewriter; protected readonly SyntheticBoundNodeFactory _factory; protected readonly DagTempAllocator _tempAllocator; public PatternLocalRewriter(SyntaxNode node, LocalRewriter localRewriter, bool generateInstrumentation) { _localRewriter = localRewriter; _factory = localRewriter._factory; GenerateInstrumentation = generateInstrumentation; _tempAllocator = new DagTempAllocator(_factory, node, generateInstrumentation); } /// <summary> /// True if we should produce instrumentation and sequence points, which we do for a switch statement and a switch expression. /// This affects /// - whether or not we invoke the instrumentation APIs /// - production of sequence points /// - synthesized local variable kind /// The temp variables must be long lived in a switch statement since their lifetime spans across sequence points. /// </summary> protected bool GenerateInstrumentation { get; } public void Free() { _tempAllocator.Free(); } public sealed class DagTempAllocator { private readonly SyntheticBoundNodeFactory _factory; private readonly PooledDictionary<BoundDagTemp, BoundExpression> _map = PooledDictionary<BoundDagTemp, BoundExpression>.GetInstance(); private readonly ArrayBuilder<LocalSymbol> _temps = ArrayBuilder<LocalSymbol>.GetInstance(); private readonly SyntaxNode _node; private readonly bool _generateSequencePoints; public DagTempAllocator(SyntheticBoundNodeFactory factory, SyntaxNode node, bool generateSequencePoints) { _factory = factory; _node = node; _generateSequencePoints = generateSequencePoints; } public void Free() { _temps.Free(); _map.Free(); } #if DEBUG public string Dump() { var poolElement = PooledStringBuilder.GetInstance(); var builder = poolElement.Builder; foreach (var kv in _map) { builder.Append("Key: "); builder.AppendLine(kv.Key.Dump()); builder.Append("Value: "); builder.AppendLine(kv.Value.Dump()); } var result = builder.ToString(); poolElement.Free(); return result; } #endif public BoundExpression GetTemp(BoundDagTemp dagTemp) { if (!_map.TryGetValue(dagTemp, out BoundExpression result)) { var kind = _generateSequencePoints ? SynthesizedLocalKind.SwitchCasePatternMatching : SynthesizedLocalKind.LoweringTemp; LocalSymbol temp = _factory.SynthesizedLocal(dagTemp.Type, syntax: _node, kind: kind); result = _factory.Local(temp); _map.Add(dagTemp, result); _temps.Add(temp); } return result; } /// <summary> /// Try setting a user-declared variable (given by its accessing expression) to be /// used for a pattern-matching temporary variable. Returns true when not already /// assigned. The return value of this method is typically ignored by the caller as /// once we have made an assignment we can keep it (we keep the first assignment we /// find), but we return a success bool to emphasize that the assignment is not unconditional. /// </summary> public bool TrySetTemp(BoundDagTemp dagTemp, BoundExpression translation) { if (!_map.ContainsKey(dagTemp)) { _map.Add(dagTemp, translation); return true; } return false; } public ImmutableArray<LocalSymbol> AllTemps() { return _temps.ToImmutableArray(); } } /// <summary> /// Return the side-effect expression corresponding to an evaluation. /// </summary> protected BoundExpression LowerEvaluation(BoundDagEvaluation evaluation) { BoundExpression input = _tempAllocator.GetTemp(evaluation.Input); switch (evaluation) { case BoundDagFieldEvaluation f: { FieldSymbol field = f.Field; var outputTemp = new BoundDagTemp(f.Syntax, field.Type, f); BoundExpression output = _tempAllocator.GetTemp(outputTemp); BoundExpression access = _localRewriter.MakeFieldAccess(f.Syntax, input, field, null, LookupResultKind.Viable, field.Type); access.WasCompilerGenerated = true; return _factory.AssignmentExpression(output, access); } case BoundDagPropertyEvaluation p: { PropertySymbol property = p.Property; var outputTemp = new BoundDagTemp(p.Syntax, property.Type, p); BoundExpression output = _tempAllocator.GetTemp(outputTemp); return _factory.AssignmentExpression(output, _factory.Property(input, property)); } case BoundDagDeconstructEvaluation d: { MethodSymbol method = d.DeconstructMethod; var refKindBuilder = ArrayBuilder<RefKind>.GetInstance(); var argBuilder = ArrayBuilder<BoundExpression>.GetInstance(); BoundExpression receiver; void addArg(RefKind refKind, BoundExpression expression) { refKindBuilder.Add(refKind); argBuilder.Add(expression); } Debug.Assert(method.Name == WellKnownMemberNames.DeconstructMethodName); int extensionExtra; if (method.IsStatic) { Debug.Assert(method.IsExtensionMethod); receiver = _factory.Type(method.ContainingType); addArg(method.ParameterRefKinds[0], input); extensionExtra = 1; } else { receiver = input; extensionExtra = 0; } for (int i = extensionExtra; i < method.ParameterCount; i++) { ParameterSymbol parameter = method.Parameters[i]; Debug.Assert(parameter.RefKind == RefKind.Out); var outputTemp = new BoundDagTemp(d.Syntax, parameter.Type, d, i - extensionExtra); addArg(RefKind.Out, _tempAllocator.GetTemp(outputTemp)); } return _factory.Call(receiver, method, refKindBuilder.ToImmutableAndFree(), argBuilder.ToImmutableAndFree()); } case BoundDagTypeEvaluation t: { TypeSymbol inputType = input.Type; Debug.Assert(inputType is { }); if (inputType.IsDynamic()) { // Avoid using dynamic conversions for pattern-matching. inputType = _factory.SpecialType(SpecialType.System_Object); input = _factory.Convert(inputType, input); } TypeSymbol type = t.Type; var outputTemp = new BoundDagTemp(t.Syntax, type, t); BoundExpression output = _tempAllocator.GetTemp(outputTemp); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = _localRewriter.GetNewCompoundUseSiteInfo(); Conversion conversion = _factory.Compilation.Conversions.ClassifyBuiltInConversion(inputType, output.Type, ref useSiteInfo); _localRewriter._diagnostics.Add(t.Syntax, useSiteInfo); BoundExpression evaluated; if (conversion.Exists) { if (conversion.Kind == ConversionKind.ExplicitNullable && inputType.GetNullableUnderlyingType().Equals(output.Type, TypeCompareKind.AllIgnoreOptions) && _localRewriter.TryGetNullableMethod(t.Syntax, inputType, SpecialMember.System_Nullable_T_GetValueOrDefault, out MethodSymbol getValueOrDefault)) { // As a special case, since the null test has already been done we can use Nullable<T>.GetValueOrDefault evaluated = _factory.Call(input, getValueOrDefault); } else { evaluated = _factory.Convert(type, input, conversion); } } else { evaluated = _factory.As(input, type); } return _factory.AssignmentExpression(output, evaluated); } case BoundDagIndexEvaluation e: { // This is an evaluation of an indexed property with a constant int value. // The input type must be ITuple, and the property must be a property of ITuple. Debug.Assert(e.Property.GetMethod.ParameterCount == 1); Debug.Assert(e.Property.GetMethod.Parameters[0].Type.SpecialType == SpecialType.System_Int32); TypeSymbol type = e.Property.GetMethod.ReturnType; var outputTemp = new BoundDagTemp(e.Syntax, type, e); BoundExpression output = _tempAllocator.GetTemp(outputTemp); return _factory.AssignmentExpression(output, _factory.Call(input, e.Property.GetMethod, _factory.Literal(e.Index))); } default: throw ExceptionUtilities.UnexpectedValue(evaluation); } } /// <summary> /// Return the boolean expression to be evaluated for the given test. Returns `null` if the test is trivially true. /// </summary> protected BoundExpression LowerTest(BoundDagTest test) { _factory.Syntax = test.Syntax; BoundExpression input = _tempAllocator.GetTemp(test.Input); Debug.Assert(input.Type is { }); switch (test) { case BoundDagNonNullTest d: return MakeNullCheck(d.Syntax, input, input.Type.IsNullableType() ? BinaryOperatorKind.NullableNullNotEqual : BinaryOperatorKind.NotEqual); case BoundDagTypeTest d: // Note that this tests for non-null as a side-effect. We depend on that to sometimes avoid the null check. return _factory.Is(input, d.Type); case BoundDagExplicitNullTest d: return MakeNullCheck(d.Syntax, input, input.Type.IsNullableType() ? BinaryOperatorKind.NullableNullEqual : BinaryOperatorKind.Equal); case BoundDagValueTest d: Debug.Assert(!input.Type.IsNullableType()); return MakeValueTest(d.Syntax, input, d.Value); case BoundDagRelationalTest d: Debug.Assert(!input.Type.IsNullableType()); Debug.Assert(input.Type.IsValueType); return MakeRelationalTest(d.Syntax, input, d.OperatorKind, d.Value); default: throw ExceptionUtilities.UnexpectedValue(test); } } private BoundExpression MakeNullCheck(SyntaxNode syntax, BoundExpression rewrittenExpr, BinaryOperatorKind operatorKind) { if (rewrittenExpr.Type.IsPointerOrFunctionPointer()) { TypeSymbol objectType = _factory.SpecialType(SpecialType.System_Object); var operandType = new PointerTypeSymbol(TypeWithAnnotations.Create(_factory.SpecialType(SpecialType.System_Void))); return _localRewriter.MakeBinaryOperator( syntax, operatorKind, _factory.Convert(operandType, rewrittenExpr), _factory.Convert(operandType, new BoundLiteral(syntax, ConstantValue.Null, objectType)), _factory.SpecialType(SpecialType.System_Boolean), method: null, constrainedToTypeOpt: null); } return _localRewriter.MakeNullCheck(syntax, rewrittenExpr, operatorKind); } protected BoundExpression MakeValueTest(SyntaxNode syntax, BoundExpression input, ConstantValue value) { TypeSymbol comparisonType = input.Type.EnumUnderlyingTypeOrSelf(); var operatorType = Binder.RelationalOperatorType(comparisonType); Debug.Assert(operatorType != BinaryOperatorKind.Error); var operatorKind = BinaryOperatorKind.Equal | operatorType; return MakeRelationalTest(syntax, input, operatorKind, value); } protected BoundExpression MakeRelationalTest(SyntaxNode syntax, BoundExpression input, BinaryOperatorKind operatorKind, ConstantValue value) { if (input.Type.SpecialType == SpecialType.System_Double && double.IsNaN(value.DoubleValue) || input.Type.SpecialType == SpecialType.System_Single && float.IsNaN(value.SingleValue)) { Debug.Assert(operatorKind.Operator() == BinaryOperatorKind.Equal); return _factory.MakeIsNotANumberTest(input); } BoundExpression literal = _localRewriter.MakeLiteral(syntax, value, input.Type); TypeSymbol comparisonType = input.Type.EnumUnderlyingTypeOrSelf(); if (operatorKind.OperandTypes() == BinaryOperatorKind.Int && comparisonType.SpecialType != SpecialType.System_Int32) { // Promote operands to int before comparison for byte, sbyte, short, ushort Debug.Assert(comparisonType.SpecialType switch { SpecialType.System_Byte => true, SpecialType.System_SByte => true, SpecialType.System_Int16 => true, SpecialType.System_UInt16 => true, _ => false }); comparisonType = _factory.SpecialType(SpecialType.System_Int32); input = _factory.Convert(comparisonType, input); literal = _factory.Convert(comparisonType, literal); } return this._localRewriter.MakeBinaryOperator(_factory.Syntax, operatorKind, input, literal, _factory.SpecialType(SpecialType.System_Boolean), method: null, constrainedToTypeOpt: null); } /// <summary> /// Lower a test followed by an evaluation into a side-effect followed by a test. This permits us to optimize /// a type test followed by a cast into an `as` expression followed by a null check. Returns true if the optimization /// applies and the results are placed into <paramref name="sideEffect"/> and <paramref name="test"/>. The caller /// should place the side-effect before the test in the generated code. /// </summary> /// <param name="evaluation"></param> /// <param name="test"></param> /// <param name="sideEffect"></param> /// <param name="testExpression"></param> /// <returns>true if the optimization is applied</returns> protected bool TryLowerTypeTestAndCast( BoundDagTest test, BoundDagEvaluation evaluation, [NotNullWhen(true)] out BoundExpression sideEffect, [NotNullWhen(true)] out BoundExpression testExpression) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = _localRewriter.GetNewCompoundUseSiteInfo(); // case 1: type test followed by cast to that type if (test is BoundDagTypeTest typeDecision && evaluation is BoundDagTypeEvaluation typeEvaluation1 && typeDecision.Type.IsReferenceType && typeEvaluation1.Type.Equals(typeDecision.Type, TypeCompareKind.AllIgnoreOptions) && typeEvaluation1.Input == typeDecision.Input) { BoundExpression input = _tempAllocator.GetTemp(test.Input); BoundExpression output = _tempAllocator.GetTemp(new BoundDagTemp(evaluation.Syntax, typeEvaluation1.Type, evaluation)); Debug.Assert(output.Type is { }); sideEffect = _factory.AssignmentExpression(output, _factory.As(input, typeEvaluation1.Type)); testExpression = _factory.ObjectNotEqual(output, _factory.Null(output.Type)); return true; } // case 2: null check followed by cast to a base type if (test is BoundDagNonNullTest nonNullTest && evaluation is BoundDagTypeEvaluation typeEvaluation2 && _factory.Compilation.Conversions.ClassifyBuiltInConversion(test.Input.Type, typeEvaluation2.Type, ref useSiteInfo) is Conversion conv && (conv.IsIdentity || conv.Kind == ConversionKind.ImplicitReference || conv.IsBoxing) && typeEvaluation2.Input == nonNullTest.Input) { BoundExpression input = _tempAllocator.GetTemp(test.Input); var baseType = typeEvaluation2.Type; BoundExpression output = _tempAllocator.GetTemp(new BoundDagTemp(evaluation.Syntax, baseType, evaluation)); sideEffect = _factory.AssignmentExpression(output, _factory.Convert(baseType, input)); testExpression = _factory.ObjectNotEqual(output, _factory.Null(baseType)); _localRewriter._diagnostics.Add(test.Syntax, useSiteInfo); return true; } sideEffect = testExpression = null; return false; } /// <summary> /// Produce assignment of the input expression. This method is also responsible for assigning /// variables for some pattern-matching temps that can be shared with user variables. /// </summary> protected BoundDecisionDag ShareTempsAndEvaluateInput( BoundExpression loweredInput, BoundDecisionDag decisionDag, Action<BoundExpression> addCode, out BoundExpression savedInputExpression) { Debug.Assert(loweredInput.Type is { }); // We share input variables if there is no when clause (because a when clause might mutate them). bool anyWhenClause = decisionDag.TopologicallySortedNodes .Any(node => node is BoundWhenDecisionDagNode { WhenExpression: { ConstantValue: null } }); var inputDagTemp = BoundDagTemp.ForOriginalInput(loweredInput); if ((loweredInput.Kind == BoundKind.Local || loweredInput.Kind == BoundKind.Parameter) && loweredInput.GetRefKind() == RefKind.None && !anyWhenClause) { // If we're switching on a local variable and there is no when clause, // we assume the value of the local variable does not change during the execution of the // decision automaton and we just reuse the local variable when we need the input expression. // It is possible for this assumption to be violated by a side-effecting Deconstruct that // modifies the local variable which has been captured in a lambda. Since the language assumes // that functions called by pattern-matching are idempotent and not side-effecting, we feel // justified in taking this assumption in the compiler too. bool tempAssigned = _tempAllocator.TrySetTemp(inputDagTemp, loweredInput); Debug.Assert(tempAssigned); } foreach (BoundDecisionDagNode node in decisionDag.TopologicallySortedNodes) { if (node is BoundWhenDecisionDagNode w) { // We share a slot for a user-declared pattern-matching variable with a pattern temp if there // is no user-written when-clause that could modify the variable before the matching // automaton is done with it (checked by the caller). foreach (BoundPatternBinding binding in w.Bindings) { if (binding.VariableAccess is BoundLocal l) { Debug.Assert(l.LocalSymbol.DeclarationKind == LocalDeclarationKind.PatternVariable); _ = _tempAllocator.TrySetTemp(binding.TempContainingValue, binding.VariableAccess); } } } } if (loweredInput.Type.IsTupleType && !loweredInput.Type.OriginalDefinition.Equals(_factory.Compilation.GetWellKnownType(WellKnownType.System_ValueTuple_TRest)) && loweredInput.Syntax.Kind() == SyntaxKind.TupleExpression && loweredInput is BoundObjectCreationExpression expr && !decisionDag.TopologicallySortedNodes.Any(n => usesOriginalInput(n))) { // If the switch governing expression is a tuple literal whose whole value is not used anywhere, // (though perhaps its component parts are used), then we can save the component parts // and assign them into temps (or perhaps user variables) to avoid the creation of // the tuple altogether. decisionDag = RewriteTupleInput(decisionDag, expr, addCode, !anyWhenClause, out savedInputExpression); } else { // Otherwise we emit an assignment of the input expression to a temporary variable. BoundExpression inputTemp = _tempAllocator.GetTemp(inputDagTemp); savedInputExpression = inputTemp; if (inputTemp != loweredInput) { addCode(_factory.AssignmentExpression(inputTemp, loweredInput)); } } Debug.Assert(savedInputExpression != null); return decisionDag; static bool usesOriginalInput(BoundDecisionDagNode node) { switch (node) { case BoundWhenDecisionDagNode n: return n.Bindings.Any(b => b.TempContainingValue.IsOriginalInput); case BoundTestDecisionDagNode t: return t.Test.Input.IsOriginalInput; case BoundEvaluationDecisionDagNode e: switch (e.Evaluation) { case BoundDagFieldEvaluation f: return f.Input.IsOriginalInput && !f.Field.IsTupleElement(); default: return e.Evaluation.Input.IsOriginalInput; } default: return false; } } } /// <summary> /// We have a decision dag whose input is a tuple literal, and the decision dag does not need the tuple itself. /// We rewrite the decision dag into one which doesn't touch the tuple, but instead works directly with the /// values that have been stored in temps. This permits the caller to avoid creation of the tuple object /// itself. We also emit assignments of the tuple values into their corresponding temps. /// </summary> /// <param name="savedInputExpression">An expression that produces the value of the original input if needed /// by the caller.</param> /// <returns>A new decision dag that does not reference the input directly</returns> private BoundDecisionDag RewriteTupleInput( BoundDecisionDag decisionDag, BoundObjectCreationExpression loweredInput, Action<BoundExpression> addCode, bool canShareInputs, out BoundExpression savedInputExpression) { int count = loweredInput.Arguments.Length; // first evaluate the inputs (in order) into temps var originalInput = BoundDagTemp.ForOriginalInput(loweredInput.Syntax, loweredInput.Type); var newArguments = ArrayBuilder<BoundExpression>.GetInstance(loweredInput.Arguments.Length); for (int i = 0; i < count; i++) { var field = loweredInput.Type.TupleElements[i].CorrespondingTupleField; Debug.Assert(field != null); var expr = loweredInput.Arguments[i]; var fieldFetchEvaluation = new BoundDagFieldEvaluation(expr.Syntax, field, originalInput); var temp = new BoundDagTemp(expr.Syntax, expr.Type, fieldFetchEvaluation); storeToTemp(temp, expr); newArguments.Add(_tempAllocator.GetTemp(temp)); } var rewrittenDag = decisionDag.Rewrite(makeReplacement); savedInputExpression = loweredInput.Update( loweredInput.Constructor, arguments: newArguments.ToImmutableAndFree(), loweredInput.ArgumentNamesOpt, loweredInput.ArgumentRefKindsOpt, loweredInput.Expanded, loweredInput.ArgsToParamsOpt, loweredInput.DefaultArguments, loweredInput.ConstantValueOpt, loweredInput.InitializerExpressionOpt, loweredInput.Type); return rewrittenDag; void storeToTemp(BoundDagTemp temp, BoundExpression expr) { if (canShareInputs && (expr.Kind == BoundKind.Parameter || expr.Kind == BoundKind.Local) && _tempAllocator.TrySetTemp(temp, expr)) { // we've arranged to use the input value from the variable it is already stored in } else { var tempToHoldInput = _tempAllocator.GetTemp(temp); addCode(_factory.AssignmentExpression(tempToHoldInput, expr)); } } BoundDecisionDagNode makeReplacement(BoundDecisionDagNode node, Func<BoundDecisionDagNode, BoundDecisionDagNode> replacement) { switch (node) { case BoundEvaluationDecisionDagNode evalNode: if (evalNode.Evaluation is BoundDagFieldEvaluation eval && eval.Input.IsOriginalInput && eval.Field is var field && field.CorrespondingTupleField != null && field.TupleElementIndex is int i) { // The elements of an input tuple were evaluated beforehand, so don't need to be evaluated now. return replacement(evalNode.Next); } // Since we are performing an optimization whose precondition is that the original // input is not used except to get its elements, we can assert here that the original // input is not used for anything else. Debug.Assert(!evalNode.Evaluation.Input.IsOriginalInput); break; case BoundTestDecisionDagNode testNode: Debug.Assert(!testNode.Test.Input.IsOriginalInput); break; } return BoundDecisionDag.TrivialReplacement(node, replacement); } } } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { /// <summary> /// A common base class for lowering constructs that use pattern-matching. /// </summary> private abstract class PatternLocalRewriter { protected readonly LocalRewriter _localRewriter; protected readonly SyntheticBoundNodeFactory _factory; protected readonly DagTempAllocator _tempAllocator; public PatternLocalRewriter(SyntaxNode node, LocalRewriter localRewriter, bool generateInstrumentation) { _localRewriter = localRewriter; _factory = localRewriter._factory; GenerateInstrumentation = generateInstrumentation; _tempAllocator = new DagTempAllocator(_factory, node, generateInstrumentation); } /// <summary> /// True if we should produce instrumentation and sequence points, which we do for a switch statement and a switch expression. /// This affects /// - whether or not we invoke the instrumentation APIs /// - production of sequence points /// - synthesized local variable kind /// The temp variables must be long lived in a switch statement since their lifetime spans across sequence points. /// </summary> protected bool GenerateInstrumentation { get; } public void Free() { _tempAllocator.Free(); } public sealed class DagTempAllocator { private readonly SyntheticBoundNodeFactory _factory; private readonly PooledDictionary<BoundDagTemp, BoundExpression> _map = PooledDictionary<BoundDagTemp, BoundExpression>.GetInstance(); private readonly ArrayBuilder<LocalSymbol> _temps = ArrayBuilder<LocalSymbol>.GetInstance(); private readonly SyntaxNode _node; private readonly bool _generateSequencePoints; public DagTempAllocator(SyntheticBoundNodeFactory factory, SyntaxNode node, bool generateSequencePoints) { _factory = factory; _node = node; _generateSequencePoints = generateSequencePoints; } public void Free() { _temps.Free(); _map.Free(); } #if DEBUG public string Dump() { var poolElement = PooledStringBuilder.GetInstance(); var builder = poolElement.Builder; foreach (var kv in _map) { builder.Append("Key: "); builder.AppendLine(kv.Key.Dump()); builder.Append("Value: "); builder.AppendLine(kv.Value.Dump()); } var result = builder.ToString(); poolElement.Free(); return result; } #endif public BoundExpression GetTemp(BoundDagTemp dagTemp) { if (!_map.TryGetValue(dagTemp, out BoundExpression result)) { var kind = _generateSequencePoints ? SynthesizedLocalKind.SwitchCasePatternMatching : SynthesizedLocalKind.LoweringTemp; LocalSymbol temp = _factory.SynthesizedLocal(dagTemp.Type, syntax: _node, kind: kind); result = _factory.Local(temp); _map.Add(dagTemp, result); _temps.Add(temp); } return result; } /// <summary> /// Try setting a user-declared variable (given by its accessing expression) to be /// used for a pattern-matching temporary variable. Returns true when not already /// assigned. The return value of this method is typically ignored by the caller as /// once we have made an assignment we can keep it (we keep the first assignment we /// find), but we return a success bool to emphasize that the assignment is not unconditional. /// </summary> public bool TrySetTemp(BoundDagTemp dagTemp, BoundExpression translation) { if (!_map.ContainsKey(dagTemp)) { _map.Add(dagTemp, translation); return true; } return false; } public ImmutableArray<LocalSymbol> AllTemps() { return _temps.ToImmutableArray(); } } /// <summary> /// Return the side-effect expression corresponding to an evaluation. /// </summary> protected BoundExpression LowerEvaluation(BoundDagEvaluation evaluation) { BoundExpression input = _tempAllocator.GetTemp(evaluation.Input); switch (evaluation) { case BoundDagFieldEvaluation f: { FieldSymbol field = f.Field; var outputTemp = new BoundDagTemp(f.Syntax, field.Type, f); BoundExpression output = _tempAllocator.GetTemp(outputTemp); BoundExpression access = _localRewriter.MakeFieldAccess(f.Syntax, input, field, null, LookupResultKind.Viable, field.Type); access.WasCompilerGenerated = true; return _factory.AssignmentExpression(output, access); } case BoundDagPropertyEvaluation p: { PropertySymbol property = p.Property; var outputTemp = new BoundDagTemp(p.Syntax, property.Type, p); BoundExpression output = _tempAllocator.GetTemp(outputTemp); return _factory.AssignmentExpression(output, _factory.Property(input, property)); } case BoundDagDeconstructEvaluation d: { MethodSymbol method = d.DeconstructMethod; var refKindBuilder = ArrayBuilder<RefKind>.GetInstance(); var argBuilder = ArrayBuilder<BoundExpression>.GetInstance(); BoundExpression receiver; void addArg(RefKind refKind, BoundExpression expression) { refKindBuilder.Add(refKind); argBuilder.Add(expression); } Debug.Assert(method.Name == WellKnownMemberNames.DeconstructMethodName); int extensionExtra; if (method.IsStatic) { Debug.Assert(method.IsExtensionMethod); receiver = _factory.Type(method.ContainingType); addArg(method.ParameterRefKinds[0], input); extensionExtra = 1; } else { receiver = input; extensionExtra = 0; } for (int i = extensionExtra; i < method.ParameterCount; i++) { ParameterSymbol parameter = method.Parameters[i]; Debug.Assert(parameter.RefKind == RefKind.Out); var outputTemp = new BoundDagTemp(d.Syntax, parameter.Type, d, i - extensionExtra); addArg(RefKind.Out, _tempAllocator.GetTemp(outputTemp)); } return _factory.Call(receiver, method, refKindBuilder.ToImmutableAndFree(), argBuilder.ToImmutableAndFree()); } case BoundDagTypeEvaluation t: { TypeSymbol inputType = input.Type; Debug.Assert(inputType is { }); if (inputType.IsDynamic()) { // Avoid using dynamic conversions for pattern-matching. inputType = _factory.SpecialType(SpecialType.System_Object); input = _factory.Convert(inputType, input); } TypeSymbol type = t.Type; var outputTemp = new BoundDagTemp(t.Syntax, type, t); BoundExpression output = _tempAllocator.GetTemp(outputTemp); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = _localRewriter.GetNewCompoundUseSiteInfo(); Conversion conversion = _factory.Compilation.Conversions.ClassifyBuiltInConversion(inputType, output.Type, ref useSiteInfo); _localRewriter._diagnostics.Add(t.Syntax, useSiteInfo); BoundExpression evaluated; if (conversion.Exists) { if (conversion.Kind == ConversionKind.ExplicitNullable && inputType.GetNullableUnderlyingType().Equals(output.Type, TypeCompareKind.AllIgnoreOptions) && _localRewriter.TryGetNullableMethod(t.Syntax, inputType, SpecialMember.System_Nullable_T_GetValueOrDefault, out MethodSymbol getValueOrDefault)) { // As a special case, since the null test has already been done we can use Nullable<T>.GetValueOrDefault evaluated = _factory.Call(input, getValueOrDefault); } else { evaluated = _factory.Convert(type, input, conversion); } } else { evaluated = _factory.As(input, type); } return _factory.AssignmentExpression(output, evaluated); } case BoundDagIndexEvaluation e: { // This is an evaluation of an indexed property with a constant int value. // The input type must be ITuple, and the property must be a property of ITuple. Debug.Assert(e.Property.GetMethod.ParameterCount == 1); Debug.Assert(e.Property.GetMethod.Parameters[0].Type.SpecialType == SpecialType.System_Int32); TypeSymbol type = e.Property.GetMethod.ReturnType; var outputTemp = new BoundDagTemp(e.Syntax, type, e); BoundExpression output = _tempAllocator.GetTemp(outputTemp); return _factory.AssignmentExpression(output, _factory.Call(input, e.Property.GetMethod, _factory.Literal(e.Index))); } default: throw ExceptionUtilities.UnexpectedValue(evaluation); } } /// <summary> /// Return the boolean expression to be evaluated for the given test. Returns `null` if the test is trivially true. /// </summary> protected BoundExpression LowerTest(BoundDagTest test) { _factory.Syntax = test.Syntax; BoundExpression input = _tempAllocator.GetTemp(test.Input); Debug.Assert(input.Type is { }); switch (test) { case BoundDagNonNullTest d: return MakeNullCheck(d.Syntax, input, input.Type.IsNullableType() ? BinaryOperatorKind.NullableNullNotEqual : BinaryOperatorKind.NotEqual); case BoundDagTypeTest d: // Note that this tests for non-null as a side-effect. We depend on that to sometimes avoid the null check. return _factory.Is(input, d.Type); case BoundDagExplicitNullTest d: return MakeNullCheck(d.Syntax, input, input.Type.IsNullableType() ? BinaryOperatorKind.NullableNullEqual : BinaryOperatorKind.Equal); case BoundDagValueTest d: Debug.Assert(!input.Type.IsNullableType()); return MakeValueTest(d.Syntax, input, d.Value); case BoundDagRelationalTest d: Debug.Assert(!input.Type.IsNullableType()); Debug.Assert(input.Type.IsValueType); return MakeRelationalTest(d.Syntax, input, d.OperatorKind, d.Value); default: throw ExceptionUtilities.UnexpectedValue(test); } } private BoundExpression MakeNullCheck(SyntaxNode syntax, BoundExpression rewrittenExpr, BinaryOperatorKind operatorKind) { if (rewrittenExpr.Type.IsPointerOrFunctionPointer()) { TypeSymbol objectType = _factory.SpecialType(SpecialType.System_Object); var operandType = new PointerTypeSymbol(TypeWithAnnotations.Create(_factory.SpecialType(SpecialType.System_Void))); return _localRewriter.MakeBinaryOperator( syntax, operatorKind, _factory.Convert(operandType, rewrittenExpr), _factory.Convert(operandType, new BoundLiteral(syntax, ConstantValue.Null, objectType)), _factory.SpecialType(SpecialType.System_Boolean), method: null, constrainedToTypeOpt: null); } return _localRewriter.MakeNullCheck(syntax, rewrittenExpr, operatorKind); } protected BoundExpression MakeValueTest(SyntaxNode syntax, BoundExpression input, ConstantValue value) { TypeSymbol comparisonType = input.Type.EnumUnderlyingTypeOrSelf(); var operatorType = Binder.RelationalOperatorType(comparisonType); Debug.Assert(operatorType != BinaryOperatorKind.Error); var operatorKind = BinaryOperatorKind.Equal | operatorType; return MakeRelationalTest(syntax, input, operatorKind, value); } protected BoundExpression MakeRelationalTest(SyntaxNode syntax, BoundExpression input, BinaryOperatorKind operatorKind, ConstantValue value) { if (input.Type.SpecialType == SpecialType.System_Double && double.IsNaN(value.DoubleValue) || input.Type.SpecialType == SpecialType.System_Single && float.IsNaN(value.SingleValue)) { Debug.Assert(operatorKind.Operator() == BinaryOperatorKind.Equal); return _factory.MakeIsNotANumberTest(input); } BoundExpression literal = _localRewriter.MakeLiteral(syntax, value, input.Type); TypeSymbol comparisonType = input.Type.EnumUnderlyingTypeOrSelf(); if (operatorKind.OperandTypes() == BinaryOperatorKind.Int && comparisonType.SpecialType != SpecialType.System_Int32) { // Promote operands to int before comparison for byte, sbyte, short, ushort Debug.Assert(comparisonType.SpecialType switch { SpecialType.System_Byte => true, SpecialType.System_SByte => true, SpecialType.System_Int16 => true, SpecialType.System_UInt16 => true, _ => false }); comparisonType = _factory.SpecialType(SpecialType.System_Int32); input = _factory.Convert(comparisonType, input); literal = _factory.Convert(comparisonType, literal); } return this._localRewriter.MakeBinaryOperator(_factory.Syntax, operatorKind, input, literal, _factory.SpecialType(SpecialType.System_Boolean), method: null, constrainedToTypeOpt: null); } /// <summary> /// Lower a test followed by an evaluation into a side-effect followed by a test. This permits us to optimize /// a type test followed by a cast into an `as` expression followed by a null check. Returns true if the optimization /// applies and the results are placed into <paramref name="sideEffect"/> and <paramref name="test"/>. The caller /// should place the side-effect before the test in the generated code. /// </summary> /// <param name="evaluation"></param> /// <param name="test"></param> /// <param name="sideEffect"></param> /// <param name="testExpression"></param> /// <returns>true if the optimization is applied</returns> protected bool TryLowerTypeTestAndCast( BoundDagTest test, BoundDagEvaluation evaluation, [NotNullWhen(true)] out BoundExpression sideEffect, [NotNullWhen(true)] out BoundExpression testExpression) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = _localRewriter.GetNewCompoundUseSiteInfo(); // case 1: type test followed by cast to that type if (test is BoundDagTypeTest typeDecision && evaluation is BoundDagTypeEvaluation typeEvaluation1 && typeDecision.Type.IsReferenceType && typeEvaluation1.Type.Equals(typeDecision.Type, TypeCompareKind.AllIgnoreOptions) && typeEvaluation1.Input == typeDecision.Input) { BoundExpression input = _tempAllocator.GetTemp(test.Input); BoundExpression output = _tempAllocator.GetTemp(new BoundDagTemp(evaluation.Syntax, typeEvaluation1.Type, evaluation)); Debug.Assert(output.Type is { }); sideEffect = _factory.AssignmentExpression(output, _factory.As(input, typeEvaluation1.Type)); testExpression = _factory.ObjectNotEqual(output, _factory.Null(output.Type)); return true; } // case 2: null check followed by cast to a base type if (test is BoundDagNonNullTest nonNullTest && evaluation is BoundDagTypeEvaluation typeEvaluation2 && _factory.Compilation.Conversions.ClassifyBuiltInConversion(test.Input.Type, typeEvaluation2.Type, ref useSiteInfo) is Conversion conv && (conv.IsIdentity || conv.Kind == ConversionKind.ImplicitReference || conv.IsBoxing) && typeEvaluation2.Input == nonNullTest.Input) { BoundExpression input = _tempAllocator.GetTemp(test.Input); var baseType = typeEvaluation2.Type; BoundExpression output = _tempAllocator.GetTemp(new BoundDagTemp(evaluation.Syntax, baseType, evaluation)); sideEffect = _factory.AssignmentExpression(output, _factory.Convert(baseType, input)); testExpression = _factory.ObjectNotEqual(output, _factory.Null(baseType)); _localRewriter._diagnostics.Add(test.Syntax, useSiteInfo); return true; } sideEffect = testExpression = null; return false; } /// <summary> /// Produce assignment of the input expression. This method is also responsible for assigning /// variables for some pattern-matching temps that can be shared with user variables. /// </summary> protected BoundDecisionDag ShareTempsAndEvaluateInput( BoundExpression loweredInput, BoundDecisionDag decisionDag, Action<BoundExpression> addCode, out BoundExpression savedInputExpression) { Debug.Assert(loweredInput.Type is { }); // We share input variables if there is no when clause (because a when clause might mutate them). bool anyWhenClause = decisionDag.TopologicallySortedNodes .Any(node => node is BoundWhenDecisionDagNode { WhenExpression: { ConstantValue: null } }); var inputDagTemp = BoundDagTemp.ForOriginalInput(loweredInput); if ((loweredInput.Kind == BoundKind.Local || loweredInput.Kind == BoundKind.Parameter) && loweredInput.GetRefKind() == RefKind.None && !anyWhenClause) { // If we're switching on a local variable and there is no when clause, // we assume the value of the local variable does not change during the execution of the // decision automaton and we just reuse the local variable when we need the input expression. // It is possible for this assumption to be violated by a side-effecting Deconstruct that // modifies the local variable which has been captured in a lambda. Since the language assumes // that functions called by pattern-matching are idempotent and not side-effecting, we feel // justified in taking this assumption in the compiler too. bool tempAssigned = _tempAllocator.TrySetTemp(inputDagTemp, loweredInput); Debug.Assert(tempAssigned); } foreach (BoundDecisionDagNode node in decisionDag.TopologicallySortedNodes) { if (node is BoundWhenDecisionDagNode w) { // We share a slot for a user-declared pattern-matching variable with a pattern temp if there // is no user-written when-clause that could modify the variable before the matching // automaton is done with it (checked by the caller). foreach (BoundPatternBinding binding in w.Bindings) { if (binding.VariableAccess is BoundLocal l) { Debug.Assert(l.LocalSymbol.DeclarationKind == LocalDeclarationKind.PatternVariable); _ = _tempAllocator.TrySetTemp(binding.TempContainingValue, binding.VariableAccess); } } } } if (loweredInput.Type.IsTupleType && !loweredInput.Type.OriginalDefinition.Equals(_factory.Compilation.GetWellKnownType(WellKnownType.System_ValueTuple_TRest)) && loweredInput.Syntax.Kind() == SyntaxKind.TupleExpression && loweredInput is BoundObjectCreationExpression expr && !decisionDag.TopologicallySortedNodes.Any(n => usesOriginalInput(n))) { // If the switch governing expression is a tuple literal whose whole value is not used anywhere, // (though perhaps its component parts are used), then we can save the component parts // and assign them into temps (or perhaps user variables) to avoid the creation of // the tuple altogether. decisionDag = RewriteTupleInput(decisionDag, expr, addCode, !anyWhenClause, out savedInputExpression); } else { // Otherwise we emit an assignment of the input expression to a temporary variable. BoundExpression inputTemp = _tempAllocator.GetTemp(inputDagTemp); savedInputExpression = inputTemp; if (inputTemp != loweredInput) { addCode(_factory.AssignmentExpression(inputTemp, loweredInput)); } } Debug.Assert(savedInputExpression != null); return decisionDag; static bool usesOriginalInput(BoundDecisionDagNode node) { switch (node) { case BoundWhenDecisionDagNode n: return n.Bindings.Any(b => b.TempContainingValue.IsOriginalInput); case BoundTestDecisionDagNode t: return t.Test.Input.IsOriginalInput; case BoundEvaluationDecisionDagNode e: switch (e.Evaluation) { case BoundDagFieldEvaluation f: return f.Input.IsOriginalInput && !f.Field.IsTupleElement(); default: return e.Evaluation.Input.IsOriginalInput; } default: return false; } } } /// <summary> /// We have a decision dag whose input is a tuple literal, and the decision dag does not need the tuple itself. /// We rewrite the decision dag into one which doesn't touch the tuple, but instead works directly with the /// values that have been stored in temps. This permits the caller to avoid creation of the tuple object /// itself. We also emit assignments of the tuple values into their corresponding temps. /// </summary> /// <param name="savedInputExpression">An expression that produces the value of the original input if needed /// by the caller.</param> /// <returns>A new decision dag that does not reference the input directly</returns> private BoundDecisionDag RewriteTupleInput( BoundDecisionDag decisionDag, BoundObjectCreationExpression loweredInput, Action<BoundExpression> addCode, bool canShareInputs, out BoundExpression savedInputExpression) { int count = loweredInput.Arguments.Length; // first evaluate the inputs (in order) into temps var originalInput = BoundDagTemp.ForOriginalInput(loweredInput.Syntax, loweredInput.Type); var newArguments = ArrayBuilder<BoundExpression>.GetInstance(loweredInput.Arguments.Length); for (int i = 0; i < count; i++) { var field = loweredInput.Type.TupleElements[i].CorrespondingTupleField; Debug.Assert(field != null); var expr = loweredInput.Arguments[i]; var fieldFetchEvaluation = new BoundDagFieldEvaluation(expr.Syntax, field, originalInput); var temp = new BoundDagTemp(expr.Syntax, expr.Type, fieldFetchEvaluation); storeToTemp(temp, expr); newArguments.Add(_tempAllocator.GetTemp(temp)); } var rewrittenDag = decisionDag.Rewrite(makeReplacement); savedInputExpression = loweredInput.Update( loweredInput.Constructor, arguments: newArguments.ToImmutableAndFree(), loweredInput.ArgumentNamesOpt, loweredInput.ArgumentRefKindsOpt, loweredInput.Expanded, loweredInput.ArgsToParamsOpt, loweredInput.DefaultArguments, loweredInput.ConstantValueOpt, loweredInput.InitializerExpressionOpt, loweredInput.Type); return rewrittenDag; void storeToTemp(BoundDagTemp temp, BoundExpression expr) { if (canShareInputs && (expr.Kind == BoundKind.Parameter || expr.Kind == BoundKind.Local) && _tempAllocator.TrySetTemp(temp, expr)) { // we've arranged to use the input value from the variable it is already stored in } else { var tempToHoldInput = _tempAllocator.GetTemp(temp); addCode(_factory.AssignmentExpression(tempToHoldInput, expr)); } } BoundDecisionDagNode makeReplacement(BoundDecisionDagNode node, Func<BoundDecisionDagNode, BoundDecisionDagNode> replacement) { switch (node) { case BoundEvaluationDecisionDagNode evalNode: if (evalNode.Evaluation is BoundDagFieldEvaluation eval && eval.Input.IsOriginalInput && eval.Field is var field && field.CorrespondingTupleField != null && field.TupleElementIndex is int i) { // The elements of an input tuple were evaluated beforehand, so don't need to be evaluated now. return replacement(evalNode.Next); } // Since we are performing an optimization whose precondition is that the original // input is not used except to get its elements, we can assert here that the original // input is not used for anything else. Debug.Assert(!evalNode.Evaluation.Input.IsOriginalInput); break; case BoundTestDecisionDagNode testNode: Debug.Assert(!testNode.Test.Input.IsOriginalInput); break; } return BoundDecisionDag.TrivialReplacement(node, replacement); } } } } }
-1
dotnet/roslyn
56,095
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-02T00:01:28Z"
"2021-09-02T01:47:21Z"
212ca8da034e484813ea99027c29cc3f6405fe1f
fe389d485fb73f8186b32636bfc747a39a70b028
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Portable/SourceGeneration/CSharpGeneratorDriver.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.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using System.Linq; using System.ComponentModel; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// A <see cref="GeneratorDriver"/> implementation for the CSharp language. /// </summary> public sealed class CSharpGeneratorDriver : GeneratorDriver { /// <summary> /// Creates a new instance of <see cref="CSharpGeneratorDriver"/> /// </summary> /// <param name="parseOptions">The <see cref="CSharpParseOptions"/> that should be used when parsing generated files.</param> /// <param name="generators">The generators that will run as part of this driver.</param> /// <param name="optionsProvider">An <see cref="AnalyzerConfigOptionsProvider"/> that can be used to retrieve analyzer config values by the generators in this driver.</param> /// <param name="additionalTexts">A list of <see cref="AdditionalText"/>s available to generators in this driver.</param> internal CSharpGeneratorDriver(CSharpParseOptions parseOptions, ImmutableArray<ISourceGenerator> generators, AnalyzerConfigOptionsProvider optionsProvider, ImmutableArray<AdditionalText> additionalTexts, GeneratorDriverOptions driverOptions) : base(parseOptions, generators, optionsProvider, additionalTexts, driverOptions) { } private CSharpGeneratorDriver(GeneratorDriverState state) : base(state) { } /// <summary> /// Creates a new instance of <see cref="CSharpGeneratorDriver"/> with the specified <see cref="ISourceGenerator"/>s and default options /// </summary> /// <param name="generators">The generators to create this driver with</param> /// <returns>A new <see cref="CSharpGeneratorDriver"/> instance.</returns> public static CSharpGeneratorDriver Create(params ISourceGenerator[] generators) => Create(generators, additionalTexts: null); /// <summary> /// Creates a new instance of <see cref="CSharpGeneratorDriver"/> with the specified <see cref="IIncrementalGenerator"/>s and default options /// </summary> /// <param name="incrementalGenerators">The incremental generators to create this driver with</param> /// <returns>A new <see cref="CSharpGeneratorDriver"/> instance.</returns> public static CSharpGeneratorDriver Create(params IIncrementalGenerator[] incrementalGenerators) => Create(incrementalGenerators.Select(GeneratorExtensions.AsSourceGenerator), additionalTexts: null); /// <summary> /// Creates a new instance of <see cref="CSharpGeneratorDriver"/> with the specified <see cref="ISourceGenerator"/>s and the provided options or default. /// </summary> /// <param name="generators">The generators to create this driver with</param> /// <param name="additionalTexts">A list of <see cref="AdditionalText"/>s available to generators in this driver, or <c>null</c> if there are none.</param> /// <param name="parseOptions">The <see cref="CSharpParseOptions"/> that should be used when parsing generated files, or <c>null</c> to use <see cref="CSharpParseOptions.Default"/></param> /// <param name="optionsProvider">An <see cref="AnalyzerConfigOptionsProvider"/> that can be used to retrieve analyzer config values by the generators in this driver, or <c>null</c> if there are none.</param> /// <param name="driverOptions">A <see cref="GeneratorDriverOptions"/> that controls the behavior of the created driver.</param> /// <returns>A new <see cref="CSharpGeneratorDriver"/> instance.</returns> public static CSharpGeneratorDriver Create(IEnumerable<ISourceGenerator> generators, IEnumerable<AdditionalText>? additionalTexts = null, CSharpParseOptions? parseOptions = null, AnalyzerConfigOptionsProvider? optionsProvider = null, GeneratorDriverOptions driverOptions = default) => new CSharpGeneratorDriver(parseOptions ?? CSharpParseOptions.Default, generators.ToImmutableArray(), optionsProvider ?? CompilerAnalyzerConfigOptionsProvider.Empty, additionalTexts.AsImmutableOrEmpty(), driverOptions); // 3.11 BACKCOMPAT OVERLOAD -- DO NOT TOUCH [EditorBrowsable(EditorBrowsableState.Never)] public static CSharpGeneratorDriver Create(IEnumerable<ISourceGenerator> generators, IEnumerable<AdditionalText>? additionalTexts, CSharpParseOptions? parseOptions, AnalyzerConfigOptionsProvider? optionsProvider) => Create(generators, additionalTexts, parseOptions, optionsProvider, driverOptions: default); internal override SyntaxTree ParseGeneratedSourceText(GeneratedSourceText input, string fileName, CancellationToken cancellationToken) => CSharpSyntaxTree.ParseTextLazy(input.Text, (CSharpParseOptions)_state.ParseOptions, fileName); internal override GeneratorDriver FromState(GeneratorDriverState state) => new CSharpGeneratorDriver(state); internal override CommonMessageProvider MessageProvider => CSharp.MessageProvider.Instance; internal override string SourceExtension => ".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.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using System.Linq; using System.ComponentModel; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// A <see cref="GeneratorDriver"/> implementation for the CSharp language. /// </summary> public sealed class CSharpGeneratorDriver : GeneratorDriver { /// <summary> /// Creates a new instance of <see cref="CSharpGeneratorDriver"/> /// </summary> /// <param name="parseOptions">The <see cref="CSharpParseOptions"/> that should be used when parsing generated files.</param> /// <param name="generators">The generators that will run as part of this driver.</param> /// <param name="optionsProvider">An <see cref="AnalyzerConfigOptionsProvider"/> that can be used to retrieve analyzer config values by the generators in this driver.</param> /// <param name="additionalTexts">A list of <see cref="AdditionalText"/>s available to generators in this driver.</param> internal CSharpGeneratorDriver(CSharpParseOptions parseOptions, ImmutableArray<ISourceGenerator> generators, AnalyzerConfigOptionsProvider optionsProvider, ImmutableArray<AdditionalText> additionalTexts, GeneratorDriverOptions driverOptions) : base(parseOptions, generators, optionsProvider, additionalTexts, driverOptions) { } private CSharpGeneratorDriver(GeneratorDriverState state) : base(state) { } /// <summary> /// Creates a new instance of <see cref="CSharpGeneratorDriver"/> with the specified <see cref="ISourceGenerator"/>s and default options /// </summary> /// <param name="generators">The generators to create this driver with</param> /// <returns>A new <see cref="CSharpGeneratorDriver"/> instance.</returns> public static CSharpGeneratorDriver Create(params ISourceGenerator[] generators) => Create(generators, additionalTexts: null); /// <summary> /// Creates a new instance of <see cref="CSharpGeneratorDriver"/> with the specified <see cref="IIncrementalGenerator"/>s and default options /// </summary> /// <param name="incrementalGenerators">The incremental generators to create this driver with</param> /// <returns>A new <see cref="CSharpGeneratorDriver"/> instance.</returns> public static CSharpGeneratorDriver Create(params IIncrementalGenerator[] incrementalGenerators) => Create(incrementalGenerators.Select(GeneratorExtensions.AsSourceGenerator), additionalTexts: null); /// <summary> /// Creates a new instance of <see cref="CSharpGeneratorDriver"/> with the specified <see cref="ISourceGenerator"/>s and the provided options or default. /// </summary> /// <param name="generators">The generators to create this driver with</param> /// <param name="additionalTexts">A list of <see cref="AdditionalText"/>s available to generators in this driver, or <c>null</c> if there are none.</param> /// <param name="parseOptions">The <see cref="CSharpParseOptions"/> that should be used when parsing generated files, or <c>null</c> to use <see cref="CSharpParseOptions.Default"/></param> /// <param name="optionsProvider">An <see cref="AnalyzerConfigOptionsProvider"/> that can be used to retrieve analyzer config values by the generators in this driver, or <c>null</c> if there are none.</param> /// <param name="driverOptions">A <see cref="GeneratorDriverOptions"/> that controls the behavior of the created driver.</param> /// <returns>A new <see cref="CSharpGeneratorDriver"/> instance.</returns> public static CSharpGeneratorDriver Create(IEnumerable<ISourceGenerator> generators, IEnumerable<AdditionalText>? additionalTexts = null, CSharpParseOptions? parseOptions = null, AnalyzerConfigOptionsProvider? optionsProvider = null, GeneratorDriverOptions driverOptions = default) => new CSharpGeneratorDriver(parseOptions ?? CSharpParseOptions.Default, generators.ToImmutableArray(), optionsProvider ?? CompilerAnalyzerConfigOptionsProvider.Empty, additionalTexts.AsImmutableOrEmpty(), driverOptions); // 3.11 BACKCOMPAT OVERLOAD -- DO NOT TOUCH [EditorBrowsable(EditorBrowsableState.Never)] public static CSharpGeneratorDriver Create(IEnumerable<ISourceGenerator> generators, IEnumerable<AdditionalText>? additionalTexts, CSharpParseOptions? parseOptions, AnalyzerConfigOptionsProvider? optionsProvider) => Create(generators, additionalTexts, parseOptions, optionsProvider, driverOptions: default); internal override SyntaxTree ParseGeneratedSourceText(GeneratedSourceText input, string fileName, CancellationToken cancellationToken) => CSharpSyntaxTree.ParseTextLazy(input.Text, (CSharpParseOptions)_state.ParseOptions, fileName); internal override GeneratorDriver FromState(GeneratorDriverState state) => new CSharpGeneratorDriver(state); internal override CommonMessageProvider MessageProvider => CSharp.MessageProvider.Instance; internal override string SourceExtension => ".cs"; } }
1
dotnet/roslyn
56,095
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-02T00:01:28Z"
"2021-09-02T01:47:21Z"
212ca8da034e484813ea99027c29cc3f6405fe1f
fe389d485fb73f8186b32636bfc747a39a70b028
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Test/Semantic/SourceGeneration/AdditionalSourcesCollectionTests.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.Text; using System.Threading; using System.Threading.Tasks; using System.Xml; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.SourceGeneration { public class AdditionalSourcesCollectionTests : CSharpTestBase { [Theory] [InlineData("abc")] // abc.cs [InlineData("abc.cs")] //abc.cs [InlineData("abc.vb")] // abc.vb.cs [InlineData("abc.generated.cs")] [InlineData("abc_-_")] [InlineData("abc - generated.cs")] [InlineData("abc\u0064.cs")] //acbd.cs [InlineData("abc(1).cs")] [InlineData("abc[1].cs")] [InlineData("abc{1}.cs")] public void HintName_ValidValues(string hintName) { AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); asc.Add(hintName, SourceText.From("public class D{}", Encoding.UTF8)); Assert.True(asc.Contains(hintName)); var sources = asc.ToImmutableAndFree(); Assert.Single(sources); Assert.True(sources[0].HintName.EndsWith(".cs")); } [Theory] [InlineData("abc")] // abc.vb [InlineData("abc.cs")] //abc.cs.vb [InlineData("abc.vb")] // abc.vb public void HintName_WithExtension(string hintName) { AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".vb"); asc.Add(hintName, SourceText.From("public class D{}", Encoding.UTF8)); Assert.True(asc.Contains(hintName)); var sources = asc.ToImmutableAndFree(); Assert.Single(sources); Assert.True(sources[0].HintName.EndsWith(".vb")); } [Theory] [InlineData("/abc/def.cs")] [InlineData("\\")] [InlineData(":")] [InlineData("*")] [InlineData("?")] [InlineData("\"")] [InlineData("<")] [InlineData(">")] [InlineData("|")] [InlineData("\0")] [InlineData("abc\u00A0.cs")] // unicode non-breaking space public void HintName_InvalidValues(string hintName) { AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); var exception = Assert.Throws<ArgumentException>(nameof(hintName), () => asc.Add(hintName, SourceText.From("public class D{}", Encoding.UTF8))); Assert.Contains(hintName, exception.Message); } [Fact] public void AddedSources_Are_Deterministic() { // a few manual simple ones AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); asc.Add("file3.cs", SourceText.From("", Encoding.UTF8)); asc.Add("file1.cs", SourceText.From("", Encoding.UTF8)); asc.Add("file2.cs", SourceText.From("", Encoding.UTF8)); asc.Add("file5.cs", SourceText.From("", Encoding.UTF8)); asc.Add("file4.cs", SourceText.From("", Encoding.UTF8)); var sources = asc.ToImmutableAndFree(); var hintNames = sources.Select(s => s.HintName).ToArray(); Assert.Equal(new[] { "file3.cs", "file1.cs", "file2.cs", "file5.cs", "file4.cs" }, hintNames); // generate a long random list, remembering the order we added them Random r = new Random(); string[] names = new string[1000]; asc = new AdditionalSourcesCollection(".cs"); for (int i = 0; i < 1000; i++) { names[i] = CSharpTestBase.GetUniqueName() + ".cs"; asc.Add(names[i], SourceText.From("", Encoding.UTF8)); } sources = asc.ToImmutableAndFree(); hintNames = sources.Select(s => s.HintName).ToArray(); Assert.Equal(names, hintNames); } [Theory] [InlineData("file.cs", "file.cs")] [InlineData("file", "file")] [InlineData("file", "file.cs")] [InlineData("file.cs", "file")] [InlineData("file.cs", "file.CS")] [InlineData("file.CS", "file.cs")] [InlineData("file", "file.CS")] [InlineData("file.CS", "file")] [InlineData("File", "file")] [InlineData("file", "File")] public void Hint_Name_Must_Be_Unique(string hintName1, string hintName2) { AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); asc.Add(hintName1, SourceText.From("", Encoding.UTF8)); var exception = Assert.Throws<ArgumentException>("hintName", () => asc.Add(hintName2, SourceText.From("", Encoding.UTF8))); Assert.Contains(hintName2, exception.Message); } [Fact] public void Hint_Name_Must_Be_Unique_When_Combining_Soruces() { AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); asc.Add("hintName1", SourceText.From("", Encoding.UTF8)); asc.Add("hintName2", SourceText.From("", Encoding.UTF8)); AdditionalSourcesCollection asc2 = new AdditionalSourcesCollection(".cs"); asc2.Add("hintName3", SourceText.From("", Encoding.UTF8)); asc2.Add("hintName1", SourceText.From("", Encoding.UTF8)); var exception = Assert.Throws<ArgumentException>("hintName", () => asc.CopyTo(asc2)); Assert.Contains("hintName1", exception.Message); } [Theory] [InlineData("file.cs", "file.cs")] [InlineData("file", "file")] [InlineData("file", "file.cs")] [InlineData("file.cs", "file")] [InlineData("file.CS", "file")] [InlineData("file", "file.CS")] [InlineData("File", "file.cs")] [InlineData("File.cs", "file")] [InlineData("File.cs", "file.CS")] public void Contains(string addHintName, string checkHintName) { AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); asc.Add(addHintName, SourceText.From("", Encoding.UTF8)); Assert.True(asc.Contains(checkHintName)); } [Theory] [InlineData("file.cs", "file.cs")] [InlineData("file", "file")] [InlineData("file", "file.cs")] [InlineData("file.cs", "file")] public void Remove(string addHintName, string removeHintName) { AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); asc.Add(addHintName, SourceText.From("", Encoding.UTF8)); asc.RemoveSource(removeHintName); var sources = asc.ToImmutableAndFree(); Assert.Empty(sources); } [Fact] public void SourceTextRequiresEncoding() { AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); // fine asc.Add("file1.cs", SourceText.From("", Encoding.UTF8)); asc.Add("file2.cs", SourceText.From("", Encoding.UTF32)); asc.Add("file3.cs", SourceText.From("", Encoding.Unicode)); // no encoding Assert.Throws<ArgumentException>(() => asc.Add("file4.cs", SourceText.From(""))); // explicit null encoding Assert.Throws<ArgumentException>(() => asc.Add("file5.cs", SourceText.From("", encoding: null))); var exception = Assert.Throws<ArgumentException>(() => asc.Add("file5.cs", SourceText.From("", encoding: null))); // check the exception contains the expected hintName Assert.Contains("file5.cs", exception.Message); } } }
// Licensed to the .NET Foundation under one or more 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.Text; using System.Threading; using System.Threading.Tasks; using System.Xml; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.SourceGeneration { public class AdditionalSourcesCollectionTests : CSharpTestBase { [Theory] [InlineData("abc")] // abc.cs [InlineData("abc.cs")] //abc.cs [InlineData("abc.vb")] // abc.vb.cs [InlineData("abc.generated.cs")] [InlineData("abc_-_")] [InlineData("abc - generated.cs")] [InlineData("abc\u0064.cs")] //acbd.cs [InlineData("abc(1).cs")] [InlineData("abc[1].cs")] [InlineData("abc{1}.cs")] public void HintName_ValidValues(string hintName) { AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); asc.Add(hintName, SourceText.From("public class D{}", Encoding.UTF8)); Assert.True(asc.Contains(hintName)); var sources = asc.ToImmutableAndFree(); Assert.Single(sources); Assert.True(sources[0].HintName.EndsWith(".cs")); } [Theory] [InlineData("abc")] // abc.vb [InlineData("abc.cs")] //abc.cs.vb [InlineData("abc.vb")] // abc.vb public void HintName_WithExtension(string hintName) { AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".vb"); asc.Add(hintName, SourceText.From("public class D{}", Encoding.UTF8)); Assert.True(asc.Contains(hintName)); var sources = asc.ToImmutableAndFree(); Assert.Single(sources); Assert.True(sources[0].HintName.EndsWith(".vb")); } [Theory] [InlineData("/abc/def.cs")] [InlineData("\\")] [InlineData(":")] [InlineData("*")] [InlineData("?")] [InlineData("\"")] [InlineData("<")] [InlineData(">")] [InlineData("|")] [InlineData("\0")] [InlineData("abc\u00A0.cs")] // unicode non-breaking space public void HintName_InvalidValues(string hintName) { AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); var exception = Assert.Throws<ArgumentException>(nameof(hintName), () => asc.Add(hintName, SourceText.From("public class D{}", Encoding.UTF8))); Assert.Contains(hintName, exception.Message); } [Fact] public void AddedSources_Are_Deterministic() { // a few manual simple ones AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); asc.Add("file3.cs", SourceText.From("", Encoding.UTF8)); asc.Add("file1.cs", SourceText.From("", Encoding.UTF8)); asc.Add("file2.cs", SourceText.From("", Encoding.UTF8)); asc.Add("file5.cs", SourceText.From("", Encoding.UTF8)); asc.Add("file4.cs", SourceText.From("", Encoding.UTF8)); var sources = asc.ToImmutableAndFree(); var hintNames = sources.Select(s => s.HintName).ToArray(); Assert.Equal(new[] { "file3.cs", "file1.cs", "file2.cs", "file5.cs", "file4.cs" }, hintNames); // generate a long random list, remembering the order we added them Random r = new Random(); string[] names = new string[1000]; asc = new AdditionalSourcesCollection(".cs"); for (int i = 0; i < 1000; i++) { names[i] = CSharpTestBase.GetUniqueName() + ".cs"; asc.Add(names[i], SourceText.From("", Encoding.UTF8)); } sources = asc.ToImmutableAndFree(); hintNames = sources.Select(s => s.HintName).ToArray(); Assert.Equal(names, hintNames); } [Theory] [InlineData("file.cs", "file.cs")] [InlineData("file", "file")] [InlineData("file", "file.cs")] [InlineData("file.cs", "file")] [InlineData("file.cs", "file.CS")] [InlineData("file.CS", "file.cs")] [InlineData("file", "file.CS")] [InlineData("file.CS", "file")] [InlineData("File", "file")] [InlineData("file", "File")] public void Hint_Name_Must_Be_Unique(string hintName1, string hintName2) { AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); asc.Add(hintName1, SourceText.From("", Encoding.UTF8)); var exception = Assert.Throws<ArgumentException>("hintName", () => asc.Add(hintName2, SourceText.From("", Encoding.UTF8))); Assert.Contains(hintName2, exception.Message); } [Fact] public void Hint_Name_Must_Be_Unique_When_Combining_Soruces() { AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); asc.Add("hintName1", SourceText.From("", Encoding.UTF8)); asc.Add("hintName2", SourceText.From("", Encoding.UTF8)); AdditionalSourcesCollection asc2 = new AdditionalSourcesCollection(".cs"); asc2.Add("hintName3", SourceText.From("", Encoding.UTF8)); asc2.Add("hintName1", SourceText.From("", Encoding.UTF8)); var exception = Assert.Throws<ArgumentException>("hintName", () => asc.CopyTo(asc2)); Assert.Contains("hintName1", exception.Message); } [Theory] [InlineData("file.cs", "file.cs")] [InlineData("file", "file")] [InlineData("file", "file.cs")] [InlineData("file.cs", "file")] [InlineData("file.CS", "file")] [InlineData("file", "file.CS")] [InlineData("File", "file.cs")] [InlineData("File.cs", "file")] [InlineData("File.cs", "file.CS")] public void Contains(string addHintName, string checkHintName) { AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); asc.Add(addHintName, SourceText.From("", Encoding.UTF8)); Assert.True(asc.Contains(checkHintName)); } [Theory] [InlineData("file.cs", "file.cs")] [InlineData("file", "file")] [InlineData("file", "file.cs")] [InlineData("file.cs", "file")] public void Remove(string addHintName, string removeHintName) { AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); asc.Add(addHintName, SourceText.From("", Encoding.UTF8)); asc.RemoveSource(removeHintName); var sources = asc.ToImmutableAndFree(); Assert.Empty(sources); } [Fact] public void SourceTextRequiresEncoding() { AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs"); // fine asc.Add("file1.cs", SourceText.From("", Encoding.UTF8)); asc.Add("file2.cs", SourceText.From("", Encoding.UTF32)); asc.Add("file3.cs", SourceText.From("", Encoding.Unicode)); // no encoding Assert.Throws<ArgumentException>(() => asc.Add("file4.cs", SourceText.From(""))); // explicit null encoding Assert.Throws<ArgumentException>(() => asc.Add("file5.cs", SourceText.From("", encoding: null))); var exception = Assert.Throws<ArgumentException>(() => asc.Add("file5.cs", SourceText.From("", encoding: null))); // check the exception contains the expected hintName Assert.Contains("file5.cs", exception.Message); } } }
1
dotnet/roslyn
56,095
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-02T00:01:28Z"
"2021-09-02T01:47:21Z"
212ca8da034e484813ea99027c29cc3f6405fe1f
fe389d485fb73f8186b32636bfc747a39a70b028
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Test/Semantic/SourceGeneration/GeneratorDriverTests.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.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.TestGenerators; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.SourceGeneration { public class GeneratorDriverTests : CSharpTestBase { [Fact] public void Running_With_No_Changes_Is_NoOp() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray<ISourceGenerator>.Empty, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics); Assert.Empty(diagnostics); Assert.Single(outputCompilation.SyntaxTrees); Assert.Equal(compilation, outputCompilation); } [Fact] public void Generator_Is_Initialized_Before_Running() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int initCount = 0, executeCount = 0; var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics); Assert.Equal(1, initCount); Assert.Equal(1, executeCount); } [Fact] public void Generator_Is_Not_Initialized_If_Not_Run() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int initCount = 0, executeCount = 0; var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); Assert.Equal(0, initCount); Assert.Equal(0, executeCount); } [Fact] public void Generator_Is_Only_Initialized_Once() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int initCount = 0, executeCount = 0; var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++, source: "public class C { }"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); driver = driver.RunGeneratorsAndUpdateCompilation(outputCompilation, out outputCompilation, out _); driver.RunGeneratorsAndUpdateCompilation(outputCompilation, out outputCompilation, out _); Assert.Equal(1, initCount); Assert.Equal(3, executeCount); } [Fact] public void Single_File_Is_Added() { var source = @" class C { } "; var generatorSource = @" class GeneratedClass { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); SingleFileTestGenerator testGenerator = new SingleFileTestGenerator(generatorSource); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); Assert.NotEqual(compilation, outputCompilation); var generatedClass = outputCompilation.GlobalNamespace.GetTypeMembers("GeneratedClass").Single(); Assert.True(generatedClass.Locations.Single().IsInSource); } [Fact] public void Analyzer_Is_Run() { var source = @" class C { } "; var generatorSource = @" class GeneratedClass { } "; var parseOptions = TestOptions.Regular; var analyzer = new Analyzer_Is_Run_Analyzer(); Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); compilation.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(0, analyzer.GeneratedClassCount); SingleFileTestGenerator testGenerator = new SingleFileTestGenerator(generatorSource); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); outputCompilation.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.GeneratedClassCount); } private class Analyzer_Is_Run_Analyzer : DiagnosticAnalyzer { public int GeneratedClassCount; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(Handle, SymbolKind.NamedType); } private void Handle(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "GeneratedClass": Interlocked.Increment(ref GeneratedClassCount); break; case "C": case "System.Runtime.CompilerServices.IsExternalInit": break; default: Assert.True(false); break; } } } [Fact] public void Single_File_Is_Added_OnlyOnce_For_Multiple_Calls() { var source = @" class C { } "; var generatorSource = @" class GeneratedClass { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); SingleFileTestGenerator testGenerator = new SingleFileTestGenerator(generatorSource); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation1, out _); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation2, out _); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation3, out _); Assert.Equal(2, outputCompilation1.SyntaxTrees.Count()); Assert.Equal(2, outputCompilation2.SyntaxTrees.Count()); Assert.Equal(2, outputCompilation3.SyntaxTrees.Count()); Assert.NotEqual(compilation, outputCompilation1); Assert.NotEqual(compilation, outputCompilation2); Assert.NotEqual(compilation, outputCompilation3); } [Fact] public void User_Source_Can_Depend_On_Generated_Source() { var source = @" #pragma warning disable CS0649 class C { public D d; } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics( // (5,12): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?) // public D d; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(5, 12) ); Assert.Single(compilation.SyntaxTrees); var generator = new SingleFileTestGenerator("public class D { }"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify(); } [Fact] public void Error_During_Initialization_Is_Reported() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("init error"); var generator = new CallbackGenerator((ic) => throw exception, (sgc) => { }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify( // warning CS8784: Generator 'CallbackGenerator' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'init error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "InvalidOperationException", "init error").WithLocation(1, 1) ); } [Fact] public void Error_During_Initialization_Generator_Does_Not_Run() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("init error"); var generator = new CallbackGenerator((ic) => throw exception, (sgc) => { }, source: "class D { }"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); Assert.Single(outputCompilation.SyntaxTrees); } [Fact] public void Error_During_Generation_Is_Reported() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("generate error"); var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify( // warning CS8785: Generator 'CallbackGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'generate error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "InvalidOperationException", "generate error").WithLocation(1, 1) ); } [Fact] public void Error_During_Generation_Does_Not_Affect_Other_Generators() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("generate error"); var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception); var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { }, source: "public class D { }"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); generatorDiagnostics.Verify( // warning CS8785: Generator 'CallbackGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'generate error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "InvalidOperationException", "generate error").WithLocation(1, 1) ); } [Fact] public void Error_During_Generation_With_Dependent_Source() { var source = @" #pragma warning disable CS0649 class C { public D d; } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics( // (5,12): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?) // public D d; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(5, 12) ); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("generate error"); var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception, source: "public class D { }"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics( // (5,12): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?) // public D d; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(5, 12) ); generatorDiagnostics.Verify( // warning CS8785: Generator 'CallbackGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'generate error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "InvalidOperationException", "generate error").WithLocation(1, 1) ); } [Fact] public void Error_During_Generation_Has_Exception_In_Description() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("generate error"); var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); // Since translated description strings can have punctuation that differs based on locale, simply ensure the // exception message is contains in the diagnostic description. Assert.Contains(exception.ToString(), generatorDiagnostics.Single().Descriptor.Description.ToString()); } [Fact] public void Generator_Can_Report_Diagnostics() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); string description = "This is a test diagnostic"; DiagnosticDescriptor generatorDiagnostic = new DiagnosticDescriptor("TG001", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); var diagnostic = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic, Location.None); var generator = new CallbackGenerator((ic) => { }, (sgc) => sgc.ReportDiagnostic(diagnostic)); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify( Diagnostic("TG001").WithLocation(1, 1) ); } [Fact] public void Generator_HintName_MustBe_Unique() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8)); // the assert should swallow the exception, so we'll actually successfully generate Assert.Throws<ArgumentException>("hintName", () => sgc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8))); // also throws for <name> vs <name>.cs Assert.Throws<ArgumentException>("hintName", () => sgc.AddSource("test.cs", SourceText.From("public class D{}", Encoding.UTF8))); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify(); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); } [ConditionalFact(typeof(MonoOrCoreClrOnly), Reason = "Desktop CLR displays argument exceptions differently")] public void Generator_HintName_MustBe_Unique_Across_Outputs() { var source = @" class C { } "; var parseOptions = TestOptions.Regular.WithLanguageVersion(LanguageVersion.Preview); Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => { spc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8)); // throws immediately, because we're within the same output node Assert.Throws<ArgumentException>("hintName", () => spc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8))); // throws for .cs too Assert.Throws<ArgumentException>("hintName", () => spc.AddSource("test.cs", SourceText.From("public class D{}", Encoding.UTF8))); }); ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => { // will not throw at this point, because we have no way of knowing what the other outputs added // we *will* throw later in the driver when we combine them however (this is a change for V2, but not visible from V1) spc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8)); }); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator.AsSourceGenerator() }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify( Diagnostic("CS8785").WithArguments("PipelineCallbackGenerator", "ArgumentException", "The hintName 'test.cs' of the added source file must be unique within a generator. (Parameter 'hintName')").WithLocation(1, 1) ); Assert.Equal(1, outputCompilation.SyntaxTrees.Count()); } [Fact] public void Generator_HintName_Is_Appended_With_GeneratorName() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new SingleFileTestGenerator("public class D {}", "source.cs"); var generator2 = new SingleFileTestGenerator2("public class E {}", "source.cs"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify(); Assert.Equal(3, outputCompilation.SyntaxTrees.Count()); var filePaths = outputCompilation.SyntaxTrees.Skip(1).Select(t => t.FilePath).ToArray(); Assert.Equal(new[] { Path.Combine(generator.GetType().Assembly.GetName().Name!, generator.GetType().FullName!, "source.cs"), Path.Combine(generator2.GetType().Assembly.GetName().Name!, generator2.GetType().FullName!, "source.cs") }, filePaths); } [Fact] public void RunResults_Are_Empty_Before_Generation() { GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray<ISourceGenerator>.Empty, parseOptions: TestOptions.Regular); var results = driver.GetRunResult(); Assert.Empty(results.GeneratedTrees); Assert.Empty(results.Diagnostics); Assert.Empty(results.Results); } [Fact] public void RunResults_Are_Available_After_Generation() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("test", SourceText.From("public class D {}", Encoding.UTF8)); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Single(results.GeneratedTrees); Assert.Single(results.Results); Assert.Empty(results.Diagnostics); var result = results.Results.Single(); Assert.Null(result.Exception); Assert.Empty(result.Diagnostics); Assert.Single(result.GeneratedSources); Assert.Equal(results.GeneratedTrees.Single(), result.GeneratedSources.Single().SyntaxTree); } [Fact] public void RunResults_Combine_SyntaxTrees() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("test", SourceText.From("public class D {}", Encoding.UTF8)); sgc.AddSource("test2", SourceText.From("public class E {}", Encoding.UTF8)); }); var generator2 = new SingleFileTestGenerator("public class F{}"); var generator3 = new SingleFileTestGenerator2("public class G{}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2, generator3 }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Equal(4, results.GeneratedTrees.Length); Assert.Equal(3, results.Results.Length); Assert.Empty(results.Diagnostics); var result1 = results.Results[0]; var result2 = results.Results[1]; var result3 = results.Results[2]; Assert.Null(result1.Exception); Assert.Empty(result1.Diagnostics); Assert.Equal(2, result1.GeneratedSources.Length); Assert.Equal(results.GeneratedTrees[0], result1.GeneratedSources[0].SyntaxTree); Assert.Equal(results.GeneratedTrees[1], result1.GeneratedSources[1].SyntaxTree); Assert.Null(result2.Exception); Assert.Empty(result2.Diagnostics); Assert.Single(result2.GeneratedSources); Assert.Equal(results.GeneratedTrees[2], result2.GeneratedSources[0].SyntaxTree); Assert.Null(result3.Exception); Assert.Empty(result3.Diagnostics); Assert.Single(result3.GeneratedSources); Assert.Equal(results.GeneratedTrees[3], result3.GeneratedSources[0].SyntaxTree); } [Fact] public void RunResults_Combine_Diagnostics() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); string description = "This is a test diagnostic"; DiagnosticDescriptor generatorDiagnostic1 = new DiagnosticDescriptor("TG001", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); DiagnosticDescriptor generatorDiagnostic2 = new DiagnosticDescriptor("TG002", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); DiagnosticDescriptor generatorDiagnostic3 = new DiagnosticDescriptor("TG003", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); var diagnostic1 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic1, Location.None); var diagnostic2 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic2, Location.None); var diagnostic3 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic3, Location.None); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic1); sgc.ReportDiagnostic(diagnostic2); }); var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic3); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Equal(2, results.Results.Length); Assert.Equal(3, results.Diagnostics.Length); Assert.Empty(results.GeneratedTrees); var result1 = results.Results[0]; var result2 = results.Results[1]; Assert.Null(result1.Exception); Assert.Equal(2, result1.Diagnostics.Length); Assert.Empty(result1.GeneratedSources); Assert.Equal(results.Diagnostics[0], result1.Diagnostics[0]); Assert.Equal(results.Diagnostics[1], result1.Diagnostics[1]); Assert.Null(result2.Exception); Assert.Single(result2.Diagnostics); Assert.Empty(result2.GeneratedSources); Assert.Equal(results.Diagnostics[2], result2.Diagnostics[0]); } [Fact] public void FullGeneration_Diagnostics_AreSame_As_RunResults() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); string description = "This is a test diagnostic"; DiagnosticDescriptor generatorDiagnostic1 = new DiagnosticDescriptor("TG001", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); DiagnosticDescriptor generatorDiagnostic2 = new DiagnosticDescriptor("TG002", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); DiagnosticDescriptor generatorDiagnostic3 = new DiagnosticDescriptor("TG003", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); var diagnostic1 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic1, Location.None); var diagnostic2 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic2, Location.None); var diagnostic3 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic3, Location.None); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic1); sgc.ReportDiagnostic(diagnostic2); }); var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic3); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out var fullDiagnostics); var results = driver.GetRunResult(); Assert.Equal(3, results.Diagnostics.Length); Assert.Equal(3, fullDiagnostics.Length); AssertEx.Equal(results.Diagnostics, fullDiagnostics); } [Fact] public void Cancellation_During_Execution_Doesnt_Report_As_Generator_Error() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); CancellationTokenSource cts = new CancellationTokenSource(); var testGenerator = new CallbackGenerator( onInit: (i) => { }, onExecute: (e) => { cts.Cancel(); } ); // test generator cancels the token. Check that the call to this generator doesn't make it look like it errored. var testGenerator2 = new CallbackGenerator2( onInit: (i) => { }, onExecute: (e) => { e.AddSource("a", SourceText.From("public class E {}", Encoding.UTF8)); e.CancellationToken.ThrowIfCancellationRequested(); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator, testGenerator2 }, parseOptions: parseOptions); var oldDriver = driver; Assert.Throws<OperationCanceledException>(() => driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var outputDiagnostics, cts.Token) ); Assert.Same(oldDriver, driver); } [ConditionalFact(typeof(MonoOrCoreClrOnly), Reason = "Desktop CLR displays argument exceptions differently")] public void Adding_A_Source_Text_Without_Encoding_Fails_Generation() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("a", SourceText.From("")); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out var outputDiagnostics); Assert.Single(outputDiagnostics); outputDiagnostics.Verify( Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "ArgumentException", "The SourceText with hintName 'a.cs' must have an explicit encoding set. (Parameter 'source')").WithLocation(1, 1) ); } [Fact] public void ParseOptions_Are_Passed_To_Generator() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); ParseOptions? passedOptions = null; var testGenerator = new CallbackGenerator( onInit: (i) => { }, onExecute: (e) => { passedOptions = e.ParseOptions; } ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.Same(parseOptions, passedOptions); } [Fact] public void AdditionalFiles_Are_Passed_To_Generator() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var texts = ImmutableArray.Create<AdditionalText>(new InMemoryAdditionalText("a", "abc"), new InMemoryAdditionalText("b", "def")); ImmutableArray<AdditionalText> passedIn = default; var testGenerator = new CallbackGenerator( onInit: (i) => { }, onExecute: (e) => passedIn = e.AdditionalFiles ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions, additionalTexts: texts); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.Equal(2, passedIn.Length); Assert.Equal<AdditionalText>(texts, passedIn); } [Fact] public void AnalyzerConfigOptions_Are_Passed_To_Generator() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var options = new CompilerAnalyzerConfigOptionsProvider(ImmutableDictionary<object, AnalyzerConfigOptions>.Empty, new CompilerAnalyzerConfigOptions(ImmutableDictionary<string, string>.Empty.Add("a", "abc").Add("b", "def"))); AnalyzerConfigOptionsProvider? passedIn = null; var testGenerator = new CallbackGenerator( onInit: (i) => { }, onExecute: (e) => passedIn = e.AnalyzerConfigOptions ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions, optionsProvider: options); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.NotNull(passedIn); Assert.True(passedIn!.GlobalOptions.TryGetValue("a", out var item1)); Assert.Equal("abc", item1); Assert.True(passedIn!.GlobalOptions.TryGetValue("b", out var item2)); Assert.Equal("def", item2); } [Fact] public void Generator_Can_Provide_Source_In_PostInit() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); static void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); } var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => { }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); outputCompilation.VerifyDiagnostics(); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); } [Fact] public void PostInit_Source_Is_Available_During_Execute() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); static void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); } INamedTypeSymbol? dSymbol = null; var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => { dSymbol = sgc.Compilation.GetTypeByMetadataName("D"); }, source = "public class E : D {}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); outputCompilation.VerifyDiagnostics(); Assert.NotNull(dSymbol); } [Fact] public void PostInit_Source_Is_Available_To_Other_Generators_During_Execute() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); static void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); } INamedTypeSymbol? dSymbol = null; var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => { }); var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { dSymbol = sgc.Compilation.GetTypeByMetadataName("D"); }, source = "public class E : D {}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); outputCompilation.VerifyDiagnostics(); Assert.NotNull(dSymbol); } [Fact] public void PostInit_Is_Only_Called_Once() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int postInitCount = 0; int executeCount = 0; void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); postInitCount++; } var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => executeCount++, source = "public class E : D {}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); outputCompilation.VerifyDiagnostics(); Assert.Equal(1, postInitCount); Assert.Equal(3, executeCount); } [Fact] public void Error_During_PostInit_Is_Reported() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); static void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); throw new InvalidOperationException("post init error"); } var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => Assert.True(false, "Should not execute"), source = "public class E : D {}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); generatorDiagnostics.Verify( // warning CS8784: Generator 'CallbackGenerator' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'post init error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "InvalidOperationException", "post init error").WithLocation(1, 1) ); } [Fact] public void Error_During_Initialization_PostInit_Does_Not_Run() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); static void init(GeneratorInitializationContext context) { context.RegisterForPostInitialization(postInit); throw new InvalidOperationException("init error"); } static void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); Assert.True(false, "Should not execute"); } var generator = new CallbackGenerator(init, (sgc) => Assert.True(false, "Should not execute"), source = "public class E : D {}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); generatorDiagnostics.Verify( // warning CS8784: Generator 'CallbackGenerator' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'init error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "InvalidOperationException", "init error").WithLocation(1, 1) ); } [Fact] public void PostInit_SyntaxTrees_Are_Available_In_RunResults() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(pic => pic.AddSource("postInit", "public class D{}")), (sgc) => { }, "public class E{}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Single(results.Results); Assert.Empty(results.Diagnostics); var result = results.Results[0]; Assert.Null(result.Exception); Assert.Empty(result.Diagnostics); Assert.Equal(2, result.GeneratedSources.Length); } [Fact] public void PostInit_SyntaxTrees_Are_Combined_In_RunResults() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(pic => pic.AddSource("postInit", "public class D{}")), (sgc) => { }, "public class E{}"); var generator2 = new SingleFileTestGenerator("public class F{}"); var generator3 = new SingleFileTestGenerator2("public class G{}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2, generator3 }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Equal(4, results.GeneratedTrees.Length); Assert.Equal(3, results.Results.Length); Assert.Empty(results.Diagnostics); var result1 = results.Results[0]; var result2 = results.Results[1]; var result3 = results.Results[2]; Assert.Null(result1.Exception); Assert.Empty(result1.Diagnostics); Assert.Equal(2, result1.GeneratedSources.Length); Assert.Equal(results.GeneratedTrees[0], result1.GeneratedSources[0].SyntaxTree); Assert.Equal(results.GeneratedTrees[1], result1.GeneratedSources[1].SyntaxTree); Assert.Null(result2.Exception); Assert.Empty(result2.Diagnostics); Assert.Single(result2.GeneratedSources); Assert.Equal(results.GeneratedTrees[2], result2.GeneratedSources[0].SyntaxTree); Assert.Null(result3.Exception); Assert.Empty(result3.Diagnostics); Assert.Single(result3.GeneratedSources); Assert.Equal(results.GeneratedTrees[3], result3.GeneratedSources[0].SyntaxTree); } [Fact] public void SyntaxTrees_Are_Lazy() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new SingleFileTestGenerator("public class D {}", "source.cs"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); var tree = Assert.Single(results.GeneratedTrees); Assert.False(tree.TryGetRoot(out _)); var rootFromGetRoot = tree.GetRoot(); Assert.NotNull(rootFromGetRoot); Assert.True(tree.TryGetRoot(out var rootFromTryGetRoot)); Assert.Same(rootFromGetRoot, rootFromTryGetRoot); } [Fact] public void Diagnostics_Respect_Suppression() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); CallbackGenerator gen = new CallbackGenerator((c) => { }, (c) => { c.ReportDiagnostic(CSDiagnostic.Create("GEN001", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 2)); c.ReportDiagnostic(CSDiagnostic.Create("GEN002", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 3)); }); var options = ((CSharpCompilationOptions)compilation.Options); // generator driver diagnostics are reported separately from the compilation verifyDiagnosticsWithOptions(options, Diagnostic("GEN001").WithLocation(1, 1), Diagnostic("GEN002").WithLocation(1, 1)); // warnings can be individually suppressed verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN001", ReportDiagnostic.Suppress), Diagnostic("GEN002").WithLocation(1, 1)); verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN002", ReportDiagnostic.Suppress), Diagnostic("GEN001").WithLocation(1, 1)); // warning level is respected verifyDiagnosticsWithOptions(options.WithWarningLevel(0)); verifyDiagnosticsWithOptions(options.WithWarningLevel(2), Diagnostic("GEN001").WithLocation(1, 1)); verifyDiagnosticsWithOptions(options.WithWarningLevel(3), Diagnostic("GEN001").WithLocation(1, 1), Diagnostic("GEN002").WithLocation(1, 1)); // warnings can be upgraded to errors verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN001", ReportDiagnostic.Error), Diagnostic("GEN001").WithLocation(1, 1).WithWarningAsError(true), Diagnostic("GEN002").WithLocation(1, 1)); verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN002", ReportDiagnostic.Error), Diagnostic("GEN001").WithLocation(1, 1), Diagnostic("GEN002").WithLocation(1, 1).WithWarningAsError(true)); void verifyDiagnosticsWithOptions(CompilationOptions options, params DiagnosticDescription[] expected) { GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray.Create(gen), parseOptions: parseOptions); var updatedCompilation = compilation.WithOptions(options); driver.RunGeneratorsAndUpdateCompilation(updatedCompilation, out var outputCompilation, out var diagnostics); outputCompilation.VerifyDiagnostics(); diagnostics.Verify(expected); } } [Fact] public void Diagnostics_Respect_Pragma_Suppression() { var gen001 = CSDiagnostic.Create("GEN001", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 2); // reported diagnostics can have a location in source verifyDiagnosticsWithSource("//comment", new[] { (gen001, TextSpan.FromBounds(2, 5)) }, Diagnostic("GEN001", "com").WithLocation(1, 3)); // diagnostics are suppressed via #pragma verifyDiagnosticsWithSource( @"#pragma warning disable //comment", new[] { (gen001, TextSpan.FromBounds(27, 30)) }, Diagnostic("GEN001", "com", isSuppressed: true).WithLocation(2, 3)); // but not when they don't have a source location verifyDiagnosticsWithSource( @"#pragma warning disable //comment", new[] { (gen001, new TextSpan(0, 0)) }, Diagnostic("GEN001").WithLocation(1, 1)); // can be suppressed explicitly verifyDiagnosticsWithSource( @"#pragma warning disable GEN001 //comment", new[] { (gen001, TextSpan.FromBounds(34, 37)) }, Diagnostic("GEN001", "com", isSuppressed: true).WithLocation(2, 3)); // suppress + restore verifyDiagnosticsWithSource( @"#pragma warning disable GEN001 //comment #pragma warning restore GEN001 //another", new[] { (gen001, TextSpan.FromBounds(34, 37)), (gen001, TextSpan.FromBounds(77, 80)) }, Diagnostic("GEN001", "com", isSuppressed: true).WithLocation(2, 3), Diagnostic("GEN001", "ano").WithLocation(4, 3)); void verifyDiagnosticsWithSource(string source, (Diagnostic, TextSpan)[] reportDiagnostics, params DiagnosticDescription[] expected) { var parseOptions = TestOptions.Regular; source = source.Replace(Environment.NewLine, "\r\n"); Compilation compilation = CreateCompilation(source, sourceFileName: "sourcefile.cs", options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); CallbackGenerator gen = new CallbackGenerator((c) => { }, (c) => { foreach ((var d, var l) in reportDiagnostics) { if (l.IsEmpty) { c.ReportDiagnostic(d); } else { c.ReportDiagnostic(d.WithLocation(Location.Create(c.Compilation.SyntaxTrees.First(), l))); } } }); GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray.Create(gen), parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics); outputCompilation.VerifyDiagnostics(); diagnostics.Verify(expected); } } [Fact] public void GeneratorDriver_Prefers_Incremental_Generators() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int initCount = 0, executeCount = 0; var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++); int incrementalInitCount = 0; var generator2 = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => incrementalInitCount++)); int dualInitCount = 0, dualExecuteCount = 0, dualIncrementalInitCount = 0; var generator3 = new IncrementalAndSourceCallbackGenerator((ic) => dualInitCount++, (sgc) => dualExecuteCount++, (ic) => dualIncrementalInitCount++); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2, generator3 }, parseOptions: parseOptions); driver.RunGenerators(compilation); // ran individual incremental and source generators Assert.Equal(1, initCount); Assert.Equal(1, executeCount); Assert.Equal(1, incrementalInitCount); // ran the combined generator only as an IIncrementalGenerator Assert.Equal(0, dualInitCount); Assert.Equal(0, dualExecuteCount); Assert.Equal(1, dualIncrementalInitCount); } [Fact] public void GeneratorDriver_Initializes_Incremental_Generators() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int incrementalInitCount = 0; var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => incrementalInitCount++)); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver.RunGenerators(compilation); // ran the incremental generator Assert.Equal(1, incrementalInitCount); } [Fact] public void Incremental_Generators_Exception_During_Initialization() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var e = new InvalidOperationException("abc"); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => throw e)); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var runResults = driver.GetRunResult(); Assert.Single(runResults.Diagnostics); Assert.Single(runResults.Results); Assert.Empty(runResults.GeneratedTrees); Assert.Equal(e, runResults.Results[0].Exception); } [Fact] public void Incremental_Generators_Exception_During_Execution() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var e = new InvalidOperationException("abc"); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => throw e))); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var runResults = driver.GetRunResult(); Assert.Single(runResults.Diagnostics); Assert.Single(runResults.Results); Assert.Empty(runResults.GeneratedTrees); Assert.Equal(e, runResults.Results[0].Exception); } [Fact] public void Incremental_Generators_Exception_During_Execution_Doesnt_Produce_AnySource() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var e = new InvalidOperationException("abc"); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => spc.AddSource("test", "")); ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => throw e); })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var runResults = driver.GetRunResult(); Assert.Single(runResults.Diagnostics); Assert.Single(runResults.Results); Assert.Empty(runResults.GeneratedTrees); Assert.Equal(e, runResults.Results[0].Exception); } [Fact] public void Incremental_Generators_Exception_During_Execution_Doesnt_Stop_Other_Generators() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var e = new InvalidOperationException("abc"); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => throw e); })); var generator2 = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator2((ctx) => { ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => spc.AddSource("test", "")); })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2 }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var runResults = driver.GetRunResult(); Assert.Single(runResults.Diagnostics); Assert.Equal(2, runResults.Results.Length); Assert.Single(runResults.GeneratedTrees); Assert.Equal(e, runResults.Results[0].Exception); } [Fact] public void IncrementalGenerator_With_No_Pipeline_Callback_Is_Valid() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => { })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics); outputCompilation.VerifyDiagnostics(); Assert.Empty(diagnostics); } [Fact] public void IncrementalGenerator_Can_Add_PostInit_Source() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => ic.RegisterPostInitializationOutput(c => c.AddSource("a", "class D {}")))); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); Assert.Empty(diagnostics); } [Fact] public void User_WrappedFunc_Throw_Exceptions() { Func<int, CancellationToken, int> func = (input, _) => input; Func<int, CancellationToken, int> throwsFunc = (input, _) => throw new InvalidOperationException("user code exception"); Func<int, CancellationToken, int> timeoutFunc = (input, ct) => { ct.ThrowIfCancellationRequested(); return input; }; Func<int, CancellationToken, int> otherTimeoutFunc = (input, _) => throw new OperationCanceledException(); var userFunc = func.WrapUserFunction(); var userThrowsFunc = throwsFunc.WrapUserFunction(); var userTimeoutFunc = timeoutFunc.WrapUserFunction(); var userOtherTimeoutFunc = otherTimeoutFunc.WrapUserFunction(); // user functions return same values when wrapped var result = userFunc(10, CancellationToken.None); var userResult = userFunc(10, CancellationToken.None); Assert.Equal(10, result); Assert.Equal(result, userResult); // exceptions thrown in user code are wrapped Assert.Throws<InvalidOperationException>(() => throwsFunc(20, CancellationToken.None)); Assert.Throws<UserFunctionException>(() => userThrowsFunc(20, CancellationToken.None)); try { userThrowsFunc(20, CancellationToken.None); } catch (UserFunctionException e) { Assert.IsType<InvalidOperationException>(e.InnerException); } // cancellation is not wrapped, and is bubbled up Assert.Throws<OperationCanceledException>(() => timeoutFunc(30, new CancellationToken(true))); Assert.Throws<OperationCanceledException>(() => userTimeoutFunc(30, new CancellationToken(true))); // unless it wasn't *our* cancellation token, in which case it still gets wrapped Assert.Throws<OperationCanceledException>(() => otherTimeoutFunc(30, CancellationToken.None)); Assert.Throws<UserFunctionException>(() => userOtherTimeoutFunc(30, CancellationToken.None)); } [Fact] public void IncrementalGenerator_Doesnt_Run_For_Same_Input() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<Compilation> compilationsCalledFor = new List<Compilation>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { var filePaths = ctx.CompilationProvider.SelectMany((c, _) => c.SyntaxTrees).Select((tree, _) => tree.FilePath); ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => { compilationsCalledFor.Add(c); }); })); // run the generator once, and check it was passed the compilation GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(compilation, compilationsCalledFor[0]); // run the same compilation through again, and confirm the output wasn't called driver = driver.RunGenerators(compilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(compilation, compilationsCalledFor[0]); } [Fact] public void IncrementalGenerator_Runs_Only_For_Changed_Inputs() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var text1 = new InMemoryAdditionalText("Text1", "content1"); var text2 = new InMemoryAdditionalText("Text2", "content2"); List<Compilation> compilationsCalledFor = new List<Compilation>(); List<AdditionalText> textsCalledFor = new List<AdditionalText>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => { compilationsCalledFor.Add(c); }); ctx.RegisterSourceOutput(ctx.AdditionalTextsProvider, (spc, c) => { textsCalledFor.Add(c); }); })); // run the generator once, and check it was passed the compilation GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, additionalTexts: new[] { text1 }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(compilation, compilationsCalledFor[0]); Assert.Equal(1, textsCalledFor.Count); Assert.Equal(text1, textsCalledFor[0]); // clear the results, add an additional text, but keep the compilation the same compilationsCalledFor.Clear(); textsCalledFor.Clear(); driver = driver.AddAdditionalTexts(ImmutableArray.Create<AdditionalText>(text2)); driver = driver.RunGenerators(compilation); Assert.Equal(0, compilationsCalledFor.Count); Assert.Equal(1, textsCalledFor.Count); Assert.Equal(text2, textsCalledFor[0]); // now edit the compilation compilationsCalledFor.Clear(); textsCalledFor.Clear(); var newCompilation = compilation.WithOptions(compilation.Options.WithModuleName("newComp")); driver = driver.RunGenerators(newCompilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(newCompilation, compilationsCalledFor[0]); Assert.Equal(0, textsCalledFor.Count); // re run without changing anything compilationsCalledFor.Clear(); textsCalledFor.Clear(); driver = driver.RunGenerators(newCompilation); Assert.Equal(0, compilationsCalledFor.Count); Assert.Equal(0, textsCalledFor.Count); } [Fact] public void IncrementalGenerator_Can_Add_Comparer_To_Input_Node() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<Compilation> compilationsCalledFor = new List<Compilation>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { var compilationSource = ctx.CompilationProvider.WithComparer(new LambdaComparer<Compilation>((c1, c2) => true, 0)); ctx.RegisterSourceOutput(compilationSource, (spc, c) => { compilationsCalledFor.Add(c); }); })); // run the generator once, and check it was passed the compilation GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(compilation, compilationsCalledFor[0]); // now edit the compilation, run the generator, and confirm that the output was not called again this time Compilation newCompilation = compilation.WithOptions(compilation.Options.WithModuleName("newCompilation")); driver = driver.RunGenerators(newCompilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(compilation, compilationsCalledFor[0]); } [Fact] public void IncrementalGenerator_Can_Add_Comparer_To_Combine_Node() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<AdditionalText> texts = new List<AdditionalText>() { new InMemoryAdditionalText("abc", "") }; List<(Compilation, ImmutableArray<AdditionalText>)> calledFor = new List<(Compilation, ImmutableArray<AdditionalText>)>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { var compilationSource = ctx.CompilationProvider.Combine(ctx.AdditionalTextsProvider.Collect()) // comparer that ignores the LHS (additional texts) .WithComparer(new LambdaComparer<(Compilation, ImmutableArray<AdditionalText>)>((c1, c2) => c1.Item1 == c2.Item1, 0)); ctx.RegisterSourceOutput(compilationSource, (spc, c) => { calledFor.Add(c); }); })); // run the generator once, and check it was passed the compilation + additional texts GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, additionalTexts: texts); driver = driver.RunGenerators(compilation); Assert.Equal(1, calledFor.Count); Assert.Equal(compilation, calledFor[0].Item1); Assert.Equal(texts[0], calledFor[0].Item2.Single()); // edit the additional texts, and verify that the output was *not* called again on the next run driver = driver.RemoveAdditionalTexts(texts.ToImmutableArray()); driver = driver.RunGenerators(compilation); Assert.Equal(1, calledFor.Count); // now edit the compilation, run the generator, and confirm that the output *was* called again this time with the new compilation and no additional texts Compilation newCompilation = compilation.WithOptions(compilation.Options.WithModuleName("newCompilation")); driver = driver.RunGenerators(newCompilation); Assert.Equal(2, calledFor.Count); Assert.Equal(newCompilation, calledFor[1].Item1); Assert.Empty(calledFor[1].Item2); } [Fact] public void IncrementalGenerator_Register_End_Node_Only_Once_Through_Combines() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<Compilation> compilationsCalledFor = new List<Compilation>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { var source = ctx.CompilationProvider; var source2 = ctx.CompilationProvider.Combine(source); var source3 = ctx.CompilationProvider.Combine(source2); var source4 = ctx.CompilationProvider.Combine(source3); var source5 = ctx.CompilationProvider.Combine(source4); ctx.RegisterSourceOutput(source5, (spc, c) => { compilationsCalledFor.Add(c.Item1); }); })); // run the generator and check that we didn't multiple register the generate source node through the combine GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(compilation, compilationsCalledFor[0]); } [Fact] public void IncrementalGenerator_PostInit_Source_Is_Cached() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<ClassDeclarationSyntax> classes = new List<ClassDeclarationSyntax>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => { ctx.RegisterPostInitializationOutput(c => c.AddSource("a", "class D {}")); ctx.RegisterSourceOutput(ctx.SyntaxProvider.CreateSyntaxProvider(static (n, _) => n is ClassDeclarationSyntax, (gsc, _) => (ClassDeclarationSyntax)gsc.Node), (spc, node) => classes.Add(node)); })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(2, classes.Count); Assert.Equal("C", classes[0].Identifier.ValueText); Assert.Equal("D", classes[1].Identifier.ValueText); // clear classes, re-run classes.Clear(); driver = driver.RunGenerators(compilation); Assert.Empty(classes); // modify the original tree, see that the post init is still cached var c2 = compilation.ReplaceSyntaxTree(compilation.SyntaxTrees.First(), CSharpSyntaxTree.ParseText("class E{}", parseOptions)); classes.Clear(); driver = driver.RunGenerators(c2); Assert.Single(classes); Assert.Equal("E", classes[0].Identifier.ValueText); } [Fact] public void Incremental_Generators_Can_Be_Cancelled() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); CancellationTokenSource cts = new CancellationTokenSource(); bool generatorCancelled = false; var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => { var step1 = ctx.CompilationProvider.Select((c, ct) => { generatorCancelled = true; cts.Cancel(); return c; }); var step2 = step1.Select((c, ct) => { ct.ThrowIfCancellationRequested(); return c; }); ctx.RegisterSourceOutput(step2, (spc, c) => spc.AddSource("a", "")); })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); Assert.Throws<OperationCanceledException>(() => driver = driver.RunGenerators(compilation, cancellationToken: cts.Token)); Assert.True(generatorCancelled); } [Fact] public void ParseOptions_Can_Be_Updated() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<ParseOptions> parseOptionsCalledFor = new List<ParseOptions>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, p) => { parseOptionsCalledFor.Add(p); }); })); // run the generator once, and check it was passed the parse options GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(1, parseOptionsCalledFor.Count); Assert.Equal(parseOptions, parseOptionsCalledFor[0]); // clear the results, and re-run parseOptionsCalledFor.Clear(); driver = driver.RunGenerators(compilation); Assert.Empty(parseOptionsCalledFor); // now update the parse options parseOptionsCalledFor.Clear(); var newParseOptions = parseOptions.WithDocumentationMode(DocumentationMode.Diagnose); driver = driver.WithUpdatedParseOptions(newParseOptions); // check we ran driver = driver.RunGenerators(compilation); Assert.Equal(1, parseOptionsCalledFor.Count); Assert.Equal(newParseOptions, parseOptionsCalledFor[0]); // clear the results, and re-run parseOptionsCalledFor.Clear(); driver = driver.RunGenerators(compilation); Assert.Empty(parseOptionsCalledFor); // replace it with null, and check that it throws Assert.Throws<ArgumentNullException>(() => driver.WithUpdatedParseOptions(null!)); } [Fact] public void AnalyzerConfig_Can_Be_Updated() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); string? analyzerOptionsValue = string.Empty; var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { ctx.RegisterSourceOutput(ctx.AnalyzerConfigOptionsProvider, (spc, p) => p.GlobalOptions.TryGetValue("test", out analyzerOptionsValue)); })); var builder = ImmutableDictionary<string, string>.Empty.ToBuilder(); builder.Add("test", "value1"); var optionsProvider = new CompilerAnalyzerConfigOptionsProvider(ImmutableDictionary<object, AnalyzerConfigOptions>.Empty, new CompilerAnalyzerConfigOptions(builder.ToImmutable())); // run the generator once, and check it was passed the configs GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, optionsProvider: optionsProvider); driver = driver.RunGenerators(compilation); Assert.Equal("value1", analyzerOptionsValue); // clear the results, and re-run analyzerOptionsValue = null; driver = driver.RunGenerators(compilation); Assert.Null(analyzerOptionsValue); // now update the config analyzerOptionsValue = null; builder.Clear(); builder.Add("test", "value2"); var newOptionsProvider = optionsProvider.WithGlobalOptions(new CompilerAnalyzerConfigOptions(builder.ToImmutable())); driver = driver.WithUpdatedAnalyzerConfigOptions(newOptionsProvider); // check we ran driver = driver.RunGenerators(compilation); Assert.Equal("value2", analyzerOptionsValue); // replace it with null, and check that it throws Assert.Throws<ArgumentNullException>(() => driver.WithUpdatedAnalyzerConfigOptions(null!)); } [Fact] public void AdditionalText_Can_Be_Replaced() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); InMemoryAdditionalText additionalText1 = new InMemoryAdditionalText("path1.txt", ""); InMemoryAdditionalText additionalText2 = new InMemoryAdditionalText("path2.txt", ""); InMemoryAdditionalText additionalText3 = new InMemoryAdditionalText("path3.txt", ""); List<string?> additionalTextPaths = new List<string?>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { ctx.RegisterSourceOutput(ctx.AdditionalTextsProvider.Select((t, _) => t.Path), (spc, p) => { additionalTextPaths.Add(p); }); })); // run the generator once and check we saw the additional file GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, additionalTexts: new[] { additionalText1, additionalText2, additionalText3 }); driver = driver.RunGenerators(compilation); Assert.Equal(3, additionalTextPaths.Count); Assert.Equal("path1.txt", additionalTextPaths[0]); Assert.Equal("path2.txt", additionalTextPaths[1]); Assert.Equal("path3.txt", additionalTextPaths[2]); // re-run and check nothing else got added additionalTextPaths.Clear(); driver = driver.RunGenerators(compilation); Assert.Empty(additionalTextPaths); // now, update the additional text, but keep the path the same additionalTextPaths.Clear(); driver = driver.ReplaceAdditionalText(additionalText2, new InMemoryAdditionalText("path4.txt", "")); // run, and check that only the replaced file was invoked driver = driver.RunGenerators(compilation); Assert.Single(additionalTextPaths); Assert.Equal("path4.txt", additionalTextPaths[0]); // replace it with null, and check that it throws Assert.Throws<ArgumentNullException>(() => driver.ReplaceAdditionalText(additionalText1, null!)); } [Fact] public void Replaced_Input_Is_Treated_As_Modified() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); InMemoryAdditionalText additionalText = new InMemoryAdditionalText("path.txt", "abc"); List<string?> additionalTextPaths = new List<string?>(); List<string?> additionalTextsContents = new List<string?>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { var texts = ctx.AdditionalTextsProvider; var paths = texts.Select((t, _) => t?.Path); var contents = texts.Select((t, _) => t?.GetText()?.ToString()); ctx.RegisterSourceOutput(paths, (spc, p) => { additionalTextPaths.Add(p); }); ctx.RegisterSourceOutput(contents, (spc, p) => { additionalTextsContents.Add(p); }); })); // run the generator once and check we saw the additional file GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, additionalTexts: new[] { additionalText }); driver = driver.RunGenerators(compilation); Assert.Equal(1, additionalTextPaths.Count); Assert.Equal("path.txt", additionalTextPaths[0]); Assert.Equal(1, additionalTextsContents.Count); Assert.Equal("abc", additionalTextsContents[0]); // re-run and check nothing else got added driver = driver.RunGenerators(compilation); Assert.Equal(1, additionalTextPaths.Count); Assert.Equal(1, additionalTextsContents.Count); // now, update the additional text, but keep the path the same additionalTextPaths.Clear(); additionalTextsContents.Clear(); var secondText = new InMemoryAdditionalText("path.txt", "def"); driver = driver.ReplaceAdditionalText(additionalText, secondText); // run, and check that only the contents got re-run driver = driver.RunGenerators(compilation); Assert.Empty(additionalTextPaths); Assert.Equal(1, additionalTextsContents.Count); Assert.Equal("def", additionalTextsContents[0]); // now replace the text with a different path, but the same text additionalTextPaths.Clear(); additionalTextsContents.Clear(); var thirdText = new InMemoryAdditionalText("path2.txt", "def"); driver = driver.ReplaceAdditionalText(secondText, thirdText); // run, and check that only the paths got re-run driver = driver.RunGenerators(compilation); Assert.Equal(1, additionalTextPaths.Count); Assert.Equal("path2.txt", additionalTextPaths[0]); Assert.Empty(additionalTextsContents); } [Theory] [CombinatorialData] [InlineData(IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.Implementation)] [InlineData(IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.PostInit)] [InlineData(IncrementalGeneratorOutputKind.Implementation | IncrementalGeneratorOutputKind.PostInit)] [InlineData(IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.Implementation | IncrementalGeneratorOutputKind.PostInit)] public void Generator_Output_Kinds_Can_Be_Disabled(IncrementalGeneratorOutputKind disabledOutput) { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new PipelineCallbackGenerator(ctx => { ctx.RegisterPostInitializationOutput((context) => context.AddSource("PostInit", "")); ctx.RegisterSourceOutput(ctx.CompilationProvider, (context, ct) => context.AddSource("Source", "")); ctx.RegisterImplementationSourceOutput(ctx.CompilationProvider, (context, ct) => context.AddSource("Implementation", "")); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator.AsSourceGenerator() }, driverOptions: new GeneratorDriverOptions(disabledOutput), parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var result = driver.GetRunResult(); Assert.Single(result.Results); Assert.Empty(result.Results[0].Diagnostics); // verify the expected outputs were generated // NOTE: adding new output types will cause this test to fail. Update above as needed. foreach (IncrementalGeneratorOutputKind kind in Enum.GetValues(typeof(IncrementalGeneratorOutputKind))) { if (kind == IncrementalGeneratorOutputKind.None) continue; if (disabledOutput.HasFlag((IncrementalGeneratorOutputKind)kind)) { Assert.DoesNotContain(result.Results[0].GeneratedSources, isTextForKind); } else { Assert.Contains(result.Results[0].GeneratedSources, isTextForKind); } bool isTextForKind(GeneratedSourceResult s) => s.HintName == Enum.GetName(typeof(IncrementalGeneratorOutputKind), kind) + ".cs"; } } [Fact] public void Metadata_References_Provider() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; var metadataRefs = new[] { MetadataReference.CreateFromAssemblyInternal(this.GetType().Assembly), MetadataReference.CreateFromAssemblyInternal(typeof(object).Assembly) }; Compilation compilation = CreateEmptyCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions, references: metadataRefs); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<string?> referenceList = new List<string?>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { ctx.RegisterSourceOutput(ctx.MetadataReferencesProvider, (spc, r) => { referenceList.Add(r.Display); }); })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(referenceList[0], metadataRefs[0].Display); Assert.Equal(referenceList[1], metadataRefs[1].Display); // re-run and check we didn't see anything new referenceList.Clear(); driver = driver.RunGenerators(compilation); Assert.Empty(referenceList); // Modify the reference var modifiedRef = metadataRefs[0].WithAliases(new[] { "Alias " }); metadataRefs[0] = modifiedRef; compilation = compilation.WithReferences(metadataRefs); driver = driver.RunGenerators(compilation); Assert.Single(referenceList, modifiedRef.Display); } } }
// Licensed to the .NET Foundation under one or more 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.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.TestGenerators; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.SourceGeneration { public class GeneratorDriverTests : CSharpTestBase { [Fact] public void Running_With_No_Changes_Is_NoOp() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray<ISourceGenerator>.Empty, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics); Assert.Empty(diagnostics); Assert.Single(outputCompilation.SyntaxTrees); Assert.Equal(compilation, outputCompilation); } [Fact] public void Generator_Is_Initialized_Before_Running() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int initCount = 0, executeCount = 0; var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics); Assert.Equal(1, initCount); Assert.Equal(1, executeCount); } [Fact] public void Generator_Is_Not_Initialized_If_Not_Run() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int initCount = 0, executeCount = 0; var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); Assert.Equal(0, initCount); Assert.Equal(0, executeCount); } [Fact] public void Generator_Is_Only_Initialized_Once() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int initCount = 0, executeCount = 0; var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++, source: "public class C { }"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); driver = driver.RunGeneratorsAndUpdateCompilation(outputCompilation, out outputCompilation, out _); driver.RunGeneratorsAndUpdateCompilation(outputCompilation, out outputCompilation, out _); Assert.Equal(1, initCount); Assert.Equal(3, executeCount); } [Fact] public void Single_File_Is_Added() { var source = @" class C { } "; var generatorSource = @" class GeneratedClass { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); SingleFileTestGenerator testGenerator = new SingleFileTestGenerator(generatorSource); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); Assert.NotEqual(compilation, outputCompilation); var generatedClass = outputCompilation.GlobalNamespace.GetTypeMembers("GeneratedClass").Single(); Assert.True(generatedClass.Locations.Single().IsInSource); } [Fact] public void Analyzer_Is_Run() { var source = @" class C { } "; var generatorSource = @" class GeneratedClass { } "; var parseOptions = TestOptions.Regular; var analyzer = new Analyzer_Is_Run_Analyzer(); Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); compilation.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(0, analyzer.GeneratedClassCount); SingleFileTestGenerator testGenerator = new SingleFileTestGenerator(generatorSource); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); outputCompilation.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.GeneratedClassCount); } private class Analyzer_Is_Run_Analyzer : DiagnosticAnalyzer { public int GeneratedClassCount; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(Handle, SymbolKind.NamedType); } private void Handle(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "GeneratedClass": Interlocked.Increment(ref GeneratedClassCount); break; case "C": case "System.Runtime.CompilerServices.IsExternalInit": break; default: Assert.True(false); break; } } } [Fact] public void Single_File_Is_Added_OnlyOnce_For_Multiple_Calls() { var source = @" class C { } "; var generatorSource = @" class GeneratedClass { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); SingleFileTestGenerator testGenerator = new SingleFileTestGenerator(generatorSource); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation1, out _); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation2, out _); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation3, out _); Assert.Equal(2, outputCompilation1.SyntaxTrees.Count()); Assert.Equal(2, outputCompilation2.SyntaxTrees.Count()); Assert.Equal(2, outputCompilation3.SyntaxTrees.Count()); Assert.NotEqual(compilation, outputCompilation1); Assert.NotEqual(compilation, outputCompilation2); Assert.NotEqual(compilation, outputCompilation3); } [Fact] public void User_Source_Can_Depend_On_Generated_Source() { var source = @" #pragma warning disable CS0649 class C { public D d; } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics( // (5,12): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?) // public D d; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(5, 12) ); Assert.Single(compilation.SyntaxTrees); var generator = new SingleFileTestGenerator("public class D { }"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify(); } [Fact] public void Error_During_Initialization_Is_Reported() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("init error"); var generator = new CallbackGenerator((ic) => throw exception, (sgc) => { }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify( // warning CS8784: Generator 'CallbackGenerator' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'init error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "InvalidOperationException", "init error").WithLocation(1, 1) ); } [Fact] public void Error_During_Initialization_Generator_Does_Not_Run() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("init error"); var generator = new CallbackGenerator((ic) => throw exception, (sgc) => { }, source: "class D { }"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); Assert.Single(outputCompilation.SyntaxTrees); } [Fact] public void Error_During_Generation_Is_Reported() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("generate error"); var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify( // warning CS8785: Generator 'CallbackGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'generate error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "InvalidOperationException", "generate error").WithLocation(1, 1) ); } [Fact] public void Error_During_Generation_Does_Not_Affect_Other_Generators() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("generate error"); var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception); var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { }, source: "public class D { }"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); generatorDiagnostics.Verify( // warning CS8785: Generator 'CallbackGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'generate error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "InvalidOperationException", "generate error").WithLocation(1, 1) ); } [Fact] public void Error_During_Generation_With_Dependent_Source() { var source = @" #pragma warning disable CS0649 class C { public D d; } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics( // (5,12): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?) // public D d; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(5, 12) ); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("generate error"); var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception, source: "public class D { }"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics( // (5,12): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?) // public D d; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(5, 12) ); generatorDiagnostics.Verify( // warning CS8785: Generator 'CallbackGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'generate error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "InvalidOperationException", "generate error").WithLocation(1, 1) ); } [Fact] public void Error_During_Generation_Has_Exception_In_Description() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var exception = new InvalidOperationException("generate error"); var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); // Since translated description strings can have punctuation that differs based on locale, simply ensure the // exception message is contains in the diagnostic description. Assert.Contains(exception.ToString(), generatorDiagnostics.Single().Descriptor.Description.ToString()); } [Fact] public void Generator_Can_Report_Diagnostics() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); string description = "This is a test diagnostic"; DiagnosticDescriptor generatorDiagnostic = new DiagnosticDescriptor("TG001", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); var diagnostic = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic, Location.None); var generator = new CallbackGenerator((ic) => { }, (sgc) => sgc.ReportDiagnostic(diagnostic)); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify( Diagnostic("TG001").WithLocation(1, 1) ); } [Fact] public void Generator_HintName_MustBe_Unique() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8)); // the assert should swallow the exception, so we'll actually successfully generate Assert.Throws<ArgumentException>("hintName", () => sgc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8))); // also throws for <name> vs <name>.cs Assert.Throws<ArgumentException>("hintName", () => sgc.AddSource("test.cs", SourceText.From("public class D{}", Encoding.UTF8))); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify(); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); } [ConditionalFact(typeof(MonoOrCoreClrOnly), Reason = "Desktop CLR displays argument exceptions differently")] public void Generator_HintName_MustBe_Unique_Across_Outputs() { var source = @" class C { } "; var parseOptions = TestOptions.Regular.WithLanguageVersion(LanguageVersion.Preview); Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => { spc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8)); // throws immediately, because we're within the same output node Assert.Throws<ArgumentException>("hintName", () => spc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8))); // throws for .cs too Assert.Throws<ArgumentException>("hintName", () => spc.AddSource("test.cs", SourceText.From("public class D{}", Encoding.UTF8))); }); ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => { // will not throw at this point, because we have no way of knowing what the other outputs added // we *will* throw later in the driver when we combine them however (this is a change for V2, but not visible from V1) spc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8)); }); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator.AsSourceGenerator() }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify( Diagnostic("CS8785").WithArguments("PipelineCallbackGenerator", "ArgumentException", "The hintName 'test.cs' of the added source file must be unique within a generator. (Parameter 'hintName')").WithLocation(1, 1) ); Assert.Equal(1, outputCompilation.SyntaxTrees.Count()); } [Fact] public void Generator_HintName_Is_Appended_With_GeneratorName() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new SingleFileTestGenerator("public class D {}", "source.cs"); var generator2 = new SingleFileTestGenerator2("public class E {}", "source.cs"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); generatorDiagnostics.Verify(); Assert.Equal(3, outputCompilation.SyntaxTrees.Count()); var filePaths = outputCompilation.SyntaxTrees.Skip(1).Select(t => t.FilePath).ToArray(); Assert.Equal(new[] { Path.Combine(generator.GetType().Assembly.GetName().Name!, generator.GetType().FullName!, "source.cs"), Path.Combine(generator2.GetType().Assembly.GetName().Name!, generator2.GetType().FullName!, "source.cs") }, filePaths); } [Fact] public void RunResults_Are_Empty_Before_Generation() { GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray<ISourceGenerator>.Empty, parseOptions: TestOptions.Regular); var results = driver.GetRunResult(); Assert.Empty(results.GeneratedTrees); Assert.Empty(results.Diagnostics); Assert.Empty(results.Results); } [Fact] public void RunResults_Are_Available_After_Generation() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("test", SourceText.From("public class D {}", Encoding.UTF8)); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Single(results.GeneratedTrees); Assert.Single(results.Results); Assert.Empty(results.Diagnostics); var result = results.Results.Single(); Assert.Null(result.Exception); Assert.Empty(result.Diagnostics); Assert.Single(result.GeneratedSources); Assert.Equal(results.GeneratedTrees.Single(), result.GeneratedSources.Single().SyntaxTree); } [Fact] public void RunResults_Combine_SyntaxTrees() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("test", SourceText.From("public class D {}", Encoding.UTF8)); sgc.AddSource("test2", SourceText.From("public class E {}", Encoding.UTF8)); }); var generator2 = new SingleFileTestGenerator("public class F{}"); var generator3 = new SingleFileTestGenerator2("public class G{}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2, generator3 }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Equal(4, results.GeneratedTrees.Length); Assert.Equal(3, results.Results.Length); Assert.Empty(results.Diagnostics); var result1 = results.Results[0]; var result2 = results.Results[1]; var result3 = results.Results[2]; Assert.Null(result1.Exception); Assert.Empty(result1.Diagnostics); Assert.Equal(2, result1.GeneratedSources.Length); Assert.Equal(results.GeneratedTrees[0], result1.GeneratedSources[0].SyntaxTree); Assert.Equal(results.GeneratedTrees[1], result1.GeneratedSources[1].SyntaxTree); Assert.Null(result2.Exception); Assert.Empty(result2.Diagnostics); Assert.Single(result2.GeneratedSources); Assert.Equal(results.GeneratedTrees[2], result2.GeneratedSources[0].SyntaxTree); Assert.Null(result3.Exception); Assert.Empty(result3.Diagnostics); Assert.Single(result3.GeneratedSources); Assert.Equal(results.GeneratedTrees[3], result3.GeneratedSources[0].SyntaxTree); } [Fact] public void RunResults_Combine_Diagnostics() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); string description = "This is a test diagnostic"; DiagnosticDescriptor generatorDiagnostic1 = new DiagnosticDescriptor("TG001", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); DiagnosticDescriptor generatorDiagnostic2 = new DiagnosticDescriptor("TG002", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); DiagnosticDescriptor generatorDiagnostic3 = new DiagnosticDescriptor("TG003", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); var diagnostic1 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic1, Location.None); var diagnostic2 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic2, Location.None); var diagnostic3 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic3, Location.None); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic1); sgc.ReportDiagnostic(diagnostic2); }); var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic3); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Equal(2, results.Results.Length); Assert.Equal(3, results.Diagnostics.Length); Assert.Empty(results.GeneratedTrees); var result1 = results.Results[0]; var result2 = results.Results[1]; Assert.Null(result1.Exception); Assert.Equal(2, result1.Diagnostics.Length); Assert.Empty(result1.GeneratedSources); Assert.Equal(results.Diagnostics[0], result1.Diagnostics[0]); Assert.Equal(results.Diagnostics[1], result1.Diagnostics[1]); Assert.Null(result2.Exception); Assert.Single(result2.Diagnostics); Assert.Empty(result2.GeneratedSources); Assert.Equal(results.Diagnostics[2], result2.Diagnostics[0]); } [Fact] public void FullGeneration_Diagnostics_AreSame_As_RunResults() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); string description = "This is a test diagnostic"; DiagnosticDescriptor generatorDiagnostic1 = new DiagnosticDescriptor("TG001", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); DiagnosticDescriptor generatorDiagnostic2 = new DiagnosticDescriptor("TG002", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); DiagnosticDescriptor generatorDiagnostic3 = new DiagnosticDescriptor("TG003", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description); var diagnostic1 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic1, Location.None); var diagnostic2 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic2, Location.None); var diagnostic3 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic3, Location.None); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic1); sgc.ReportDiagnostic(diagnostic2); }); var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic3); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out var fullDiagnostics); var results = driver.GetRunResult(); Assert.Equal(3, results.Diagnostics.Length); Assert.Equal(3, fullDiagnostics.Length); AssertEx.Equal(results.Diagnostics, fullDiagnostics); } [Fact] public void Cancellation_During_Execution_Doesnt_Report_As_Generator_Error() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); CancellationTokenSource cts = new CancellationTokenSource(); var testGenerator = new CallbackGenerator( onInit: (i) => { }, onExecute: (e) => { cts.Cancel(); } ); // test generator cancels the token. Check that the call to this generator doesn't make it look like it errored. var testGenerator2 = new CallbackGenerator2( onInit: (i) => { }, onExecute: (e) => { e.AddSource("a", SourceText.From("public class E {}", Encoding.UTF8)); e.CancellationToken.ThrowIfCancellationRequested(); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator, testGenerator2 }, parseOptions: parseOptions); var oldDriver = driver; Assert.Throws<OperationCanceledException>(() => driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var outputDiagnostics, cts.Token) ); Assert.Same(oldDriver, driver); } [ConditionalFact(typeof(MonoOrCoreClrOnly), Reason = "Desktop CLR displays argument exceptions differently")] public void Adding_A_Source_Text_Without_Encoding_Fails_Generation() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("a", SourceText.From("")); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out var outputDiagnostics); Assert.Single(outputDiagnostics); outputDiagnostics.Verify( Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "ArgumentException", "The SourceText with hintName 'a.cs' must have an explicit encoding set. (Parameter 'source')").WithLocation(1, 1) ); } [Fact] public void ParseOptions_Are_Passed_To_Generator() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); ParseOptions? passedOptions = null; var testGenerator = new CallbackGenerator( onInit: (i) => { }, onExecute: (e) => { passedOptions = e.ParseOptions; } ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.Same(parseOptions, passedOptions); } [Fact] public void AdditionalFiles_Are_Passed_To_Generator() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var texts = ImmutableArray.Create<AdditionalText>(new InMemoryAdditionalText("a", "abc"), new InMemoryAdditionalText("b", "def")); ImmutableArray<AdditionalText> passedIn = default; var testGenerator = new CallbackGenerator( onInit: (i) => { }, onExecute: (e) => passedIn = e.AdditionalFiles ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions, additionalTexts: texts); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.Equal(2, passedIn.Length); Assert.Equal<AdditionalText>(texts, passedIn); } [Fact] public void AnalyzerConfigOptions_Are_Passed_To_Generator() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var options = new CompilerAnalyzerConfigOptionsProvider(ImmutableDictionary<object, AnalyzerConfigOptions>.Empty, new CompilerAnalyzerConfigOptions(ImmutableDictionary<string, string>.Empty.Add("a", "abc").Add("b", "def"))); AnalyzerConfigOptionsProvider? passedIn = null; var testGenerator = new CallbackGenerator( onInit: (i) => { }, onExecute: (e) => passedIn = e.AnalyzerConfigOptions ); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions, optionsProvider: options); driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); Assert.NotNull(passedIn); Assert.True(passedIn!.GlobalOptions.TryGetValue("a", out var item1)); Assert.Equal("abc", item1); Assert.True(passedIn!.GlobalOptions.TryGetValue("b", out var item2)); Assert.Equal("def", item2); } [Fact] public void Generator_Can_Provide_Source_In_PostInit() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); static void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); } var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => { }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); outputCompilation.VerifyDiagnostics(); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); } [Fact] public void PostInit_Source_Is_Available_During_Execute() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); static void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); } INamedTypeSymbol? dSymbol = null; var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => { dSymbol = sgc.Compilation.GetTypeByMetadataName("D"); }, source = "public class E : D {}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); outputCompilation.VerifyDiagnostics(); Assert.NotNull(dSymbol); } [Fact] public void PostInit_Source_Is_Available_To_Other_Generators_During_Execute() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); static void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); } INamedTypeSymbol? dSymbol = null; var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => { }); var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { dSymbol = sgc.Compilation.GetTypeByMetadataName("D"); }, source = "public class E : D {}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); outputCompilation.VerifyDiagnostics(); Assert.NotNull(dSymbol); } [Fact] public void PostInit_Is_Only_Called_Once() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int postInitCount = 0; int executeCount = 0; void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); postInitCount++; } var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => executeCount++, source = "public class E : D {}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _); outputCompilation.VerifyDiagnostics(); Assert.Equal(1, postInitCount); Assert.Equal(3, executeCount); } [Fact] public void Error_During_PostInit_Is_Reported() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); static void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); throw new InvalidOperationException("post init error"); } var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => Assert.True(false, "Should not execute"), source = "public class E : D {}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); generatorDiagnostics.Verify( // warning CS8784: Generator 'CallbackGenerator' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'post init error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "InvalidOperationException", "post init error").WithLocation(1, 1) ); } [Fact] public void Error_During_Initialization_PostInit_Does_Not_Run() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); static void init(GeneratorInitializationContext context) { context.RegisterForPostInitialization(postInit); throw new InvalidOperationException("init error"); } static void postInit(GeneratorPostInitializationContext context) { context.AddSource("postInit", "public class D {} "); Assert.True(false, "Should not execute"); } var generator = new CallbackGenerator(init, (sgc) => Assert.True(false, "Should not execute"), source = "public class E : D {}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); outputCompilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); generatorDiagnostics.Verify( // warning CS8784: Generator 'CallbackGenerator' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'init error' Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "InvalidOperationException", "init error").WithLocation(1, 1) ); } [Fact] public void PostInit_SyntaxTrees_Are_Available_In_RunResults() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(pic => pic.AddSource("postInit", "public class D{}")), (sgc) => { }, "public class E{}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Single(results.Results); Assert.Empty(results.Diagnostics); var result = results.Results[0]; Assert.Null(result.Exception); Assert.Empty(result.Diagnostics); Assert.Equal(2, result.GeneratedSources.Length); } [Fact] public void PostInit_SyntaxTrees_Are_Combined_In_RunResults() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(pic => pic.AddSource("postInit", "public class D{}")), (sgc) => { }, "public class E{}"); var generator2 = new SingleFileTestGenerator("public class F{}"); var generator3 = new SingleFileTestGenerator2("public class G{}"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2, generator3 }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); Assert.Equal(4, results.GeneratedTrees.Length); Assert.Equal(3, results.Results.Length); Assert.Empty(results.Diagnostics); var result1 = results.Results[0]; var result2 = results.Results[1]; var result3 = results.Results[2]; Assert.Null(result1.Exception); Assert.Empty(result1.Diagnostics); Assert.Equal(2, result1.GeneratedSources.Length); Assert.Equal(results.GeneratedTrees[0], result1.GeneratedSources[0].SyntaxTree); Assert.Equal(results.GeneratedTrees[1], result1.GeneratedSources[1].SyntaxTree); Assert.Null(result2.Exception); Assert.Empty(result2.Diagnostics); Assert.Single(result2.GeneratedSources); Assert.Equal(results.GeneratedTrees[2], result2.GeneratedSources[0].SyntaxTree); Assert.Null(result3.Exception); Assert.Empty(result3.Diagnostics); Assert.Single(result3.GeneratedSources); Assert.Equal(results.GeneratedTrees[3], result3.GeneratedSources[0].SyntaxTree); } [Fact] public void SyntaxTrees_Are_Lazy() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new SingleFileTestGenerator("public class D {}", "source.cs"); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var results = driver.GetRunResult(); var tree = Assert.Single(results.GeneratedTrees); Assert.False(tree.TryGetRoot(out _)); var rootFromGetRoot = tree.GetRoot(); Assert.NotNull(rootFromGetRoot); Assert.True(tree.TryGetRoot(out var rootFromTryGetRoot)); Assert.Same(rootFromGetRoot, rootFromTryGetRoot); } [Fact] public void Diagnostics_Respect_Suppression() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); CallbackGenerator gen = new CallbackGenerator((c) => { }, (c) => { c.ReportDiagnostic(CSDiagnostic.Create("GEN001", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 2)); c.ReportDiagnostic(CSDiagnostic.Create("GEN002", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 3)); }); var options = ((CSharpCompilationOptions)compilation.Options); // generator driver diagnostics are reported separately from the compilation verifyDiagnosticsWithOptions(options, Diagnostic("GEN001").WithLocation(1, 1), Diagnostic("GEN002").WithLocation(1, 1)); // warnings can be individually suppressed verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN001", ReportDiagnostic.Suppress), Diagnostic("GEN002").WithLocation(1, 1)); verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN002", ReportDiagnostic.Suppress), Diagnostic("GEN001").WithLocation(1, 1)); // warning level is respected verifyDiagnosticsWithOptions(options.WithWarningLevel(0)); verifyDiagnosticsWithOptions(options.WithWarningLevel(2), Diagnostic("GEN001").WithLocation(1, 1)); verifyDiagnosticsWithOptions(options.WithWarningLevel(3), Diagnostic("GEN001").WithLocation(1, 1), Diagnostic("GEN002").WithLocation(1, 1)); // warnings can be upgraded to errors verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN001", ReportDiagnostic.Error), Diagnostic("GEN001").WithLocation(1, 1).WithWarningAsError(true), Diagnostic("GEN002").WithLocation(1, 1)); verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN002", ReportDiagnostic.Error), Diagnostic("GEN001").WithLocation(1, 1), Diagnostic("GEN002").WithLocation(1, 1).WithWarningAsError(true)); void verifyDiagnosticsWithOptions(CompilationOptions options, params DiagnosticDescription[] expected) { GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray.Create(gen), parseOptions: parseOptions); var updatedCompilation = compilation.WithOptions(options); driver.RunGeneratorsAndUpdateCompilation(updatedCompilation, out var outputCompilation, out var diagnostics); outputCompilation.VerifyDiagnostics(); diagnostics.Verify(expected); } } [Fact] public void Diagnostics_Respect_Pragma_Suppression() { var gen001 = CSDiagnostic.Create("GEN001", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 2); // reported diagnostics can have a location in source verifyDiagnosticsWithSource("//comment", new[] { (gen001, TextSpan.FromBounds(2, 5)) }, Diagnostic("GEN001", "com").WithLocation(1, 3)); // diagnostics are suppressed via #pragma verifyDiagnosticsWithSource( @"#pragma warning disable //comment", new[] { (gen001, TextSpan.FromBounds(27, 30)) }, Diagnostic("GEN001", "com", isSuppressed: true).WithLocation(2, 3)); // but not when they don't have a source location verifyDiagnosticsWithSource( @"#pragma warning disable //comment", new[] { (gen001, new TextSpan(0, 0)) }, Diagnostic("GEN001").WithLocation(1, 1)); // can be suppressed explicitly verifyDiagnosticsWithSource( @"#pragma warning disable GEN001 //comment", new[] { (gen001, TextSpan.FromBounds(34, 37)) }, Diagnostic("GEN001", "com", isSuppressed: true).WithLocation(2, 3)); // suppress + restore verifyDiagnosticsWithSource( @"#pragma warning disable GEN001 //comment #pragma warning restore GEN001 //another", new[] { (gen001, TextSpan.FromBounds(34, 37)), (gen001, TextSpan.FromBounds(77, 80)) }, Diagnostic("GEN001", "com", isSuppressed: true).WithLocation(2, 3), Diagnostic("GEN001", "ano").WithLocation(4, 3)); void verifyDiagnosticsWithSource(string source, (Diagnostic, TextSpan)[] reportDiagnostics, params DiagnosticDescription[] expected) { var parseOptions = TestOptions.Regular; source = source.Replace(Environment.NewLine, "\r\n"); Compilation compilation = CreateCompilation(source, sourceFileName: "sourcefile.cs", options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); CallbackGenerator gen = new CallbackGenerator((c) => { }, (c) => { foreach ((var d, var l) in reportDiagnostics) { if (l.IsEmpty) { c.ReportDiagnostic(d); } else { c.ReportDiagnostic(d.WithLocation(Location.Create(c.Compilation.SyntaxTrees.First(), l))); } } }); GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray.Create(gen), parseOptions: parseOptions); driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics); outputCompilation.VerifyDiagnostics(); diagnostics.Verify(expected); } } [Fact] public void GeneratorDriver_Prefers_Incremental_Generators() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int initCount = 0, executeCount = 0; var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++); int incrementalInitCount = 0; var generator2 = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => incrementalInitCount++)); int dualInitCount = 0, dualExecuteCount = 0, dualIncrementalInitCount = 0; var generator3 = new IncrementalAndSourceCallbackGenerator((ic) => dualInitCount++, (sgc) => dualExecuteCount++, (ic) => dualIncrementalInitCount++); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2, generator3 }, parseOptions: parseOptions); driver.RunGenerators(compilation); // ran individual incremental and source generators Assert.Equal(1, initCount); Assert.Equal(1, executeCount); Assert.Equal(1, incrementalInitCount); // ran the combined generator only as an IIncrementalGenerator Assert.Equal(0, dualInitCount); Assert.Equal(0, dualExecuteCount); Assert.Equal(1, dualIncrementalInitCount); } [Fact] public void GeneratorDriver_Initializes_Incremental_Generators() { var source = @" class C { } "; var parseOptions = TestOptions.Regular; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); int incrementalInitCount = 0; var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => incrementalInitCount++)); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver.RunGenerators(compilation); // ran the incremental generator Assert.Equal(1, incrementalInitCount); } [Fact] public void Incremental_Generators_Exception_During_Initialization() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var e = new InvalidOperationException("abc"); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => throw e)); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var runResults = driver.GetRunResult(); Assert.Single(runResults.Diagnostics); Assert.Single(runResults.Results); Assert.Empty(runResults.GeneratedTrees); Assert.Equal(e, runResults.Results[0].Exception); } [Fact] public void Incremental_Generators_Exception_During_Execution() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var e = new InvalidOperationException("abc"); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => throw e))); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var runResults = driver.GetRunResult(); Assert.Single(runResults.Diagnostics); Assert.Single(runResults.Results); Assert.Empty(runResults.GeneratedTrees); Assert.Equal(e, runResults.Results[0].Exception); } [Fact] public void Incremental_Generators_Exception_During_Execution_Doesnt_Produce_AnySource() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var e = new InvalidOperationException("abc"); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => spc.AddSource("test", "")); ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => throw e); })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var runResults = driver.GetRunResult(); Assert.Single(runResults.Diagnostics); Assert.Single(runResults.Results); Assert.Empty(runResults.GeneratedTrees); Assert.Equal(e, runResults.Results[0].Exception); } [Fact] public void Incremental_Generators_Exception_During_Execution_Doesnt_Stop_Other_Generators() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var e = new InvalidOperationException("abc"); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => throw e); })); var generator2 = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator2((ctx) => { ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => spc.AddSource("test", "")); })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2 }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var runResults = driver.GetRunResult(); Assert.Single(runResults.Diagnostics); Assert.Equal(2, runResults.Results.Length); Assert.Single(runResults.GeneratedTrees); Assert.Equal(e, runResults.Results[0].Exception); } [Fact] public void IncrementalGenerator_With_No_Pipeline_Callback_Is_Valid() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => { })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics); outputCompilation.VerifyDiagnostics(); Assert.Empty(diagnostics); } [Fact] public void IncrementalGenerator_Can_Add_PostInit_Source() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => ic.RegisterPostInitializationOutput(c => c.AddSource("a", "class D {}")))); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics); Assert.Equal(2, outputCompilation.SyntaxTrees.Count()); Assert.Empty(diagnostics); } [Fact] public void User_WrappedFunc_Throw_Exceptions() { Func<int, CancellationToken, int> func = (input, _) => input; Func<int, CancellationToken, int> throwsFunc = (input, _) => throw new InvalidOperationException("user code exception"); Func<int, CancellationToken, int> timeoutFunc = (input, ct) => { ct.ThrowIfCancellationRequested(); return input; }; Func<int, CancellationToken, int> otherTimeoutFunc = (input, _) => throw new OperationCanceledException(); var userFunc = func.WrapUserFunction(); var userThrowsFunc = throwsFunc.WrapUserFunction(); var userTimeoutFunc = timeoutFunc.WrapUserFunction(); var userOtherTimeoutFunc = otherTimeoutFunc.WrapUserFunction(); // user functions return same values when wrapped var result = userFunc(10, CancellationToken.None); var userResult = userFunc(10, CancellationToken.None); Assert.Equal(10, result); Assert.Equal(result, userResult); // exceptions thrown in user code are wrapped Assert.Throws<InvalidOperationException>(() => throwsFunc(20, CancellationToken.None)); Assert.Throws<UserFunctionException>(() => userThrowsFunc(20, CancellationToken.None)); try { userThrowsFunc(20, CancellationToken.None); } catch (UserFunctionException e) { Assert.IsType<InvalidOperationException>(e.InnerException); } // cancellation is not wrapped, and is bubbled up Assert.Throws<OperationCanceledException>(() => timeoutFunc(30, new CancellationToken(true))); Assert.Throws<OperationCanceledException>(() => userTimeoutFunc(30, new CancellationToken(true))); // unless it wasn't *our* cancellation token, in which case it still gets wrapped Assert.Throws<OperationCanceledException>(() => otherTimeoutFunc(30, CancellationToken.None)); Assert.Throws<UserFunctionException>(() => userOtherTimeoutFunc(30, CancellationToken.None)); } [Fact] public void IncrementalGenerator_Doesnt_Run_For_Same_Input() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<Compilation> compilationsCalledFor = new List<Compilation>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { var filePaths = ctx.CompilationProvider.SelectMany((c, _) => c.SyntaxTrees).Select((tree, _) => tree.FilePath); ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => { compilationsCalledFor.Add(c); }); })); // run the generator once, and check it was passed the compilation GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(compilation, compilationsCalledFor[0]); // run the same compilation through again, and confirm the output wasn't called driver = driver.RunGenerators(compilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(compilation, compilationsCalledFor[0]); } [Fact] public void IncrementalGenerator_Runs_Only_For_Changed_Inputs() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var text1 = new InMemoryAdditionalText("Text1", "content1"); var text2 = new InMemoryAdditionalText("Text2", "content2"); List<Compilation> compilationsCalledFor = new List<Compilation>(); List<AdditionalText> textsCalledFor = new List<AdditionalText>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => { compilationsCalledFor.Add(c); }); ctx.RegisterSourceOutput(ctx.AdditionalTextsProvider, (spc, c) => { textsCalledFor.Add(c); }); })); // run the generator once, and check it was passed the compilation GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, additionalTexts: new[] { text1 }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(compilation, compilationsCalledFor[0]); Assert.Equal(1, textsCalledFor.Count); Assert.Equal(text1, textsCalledFor[0]); // clear the results, add an additional text, but keep the compilation the same compilationsCalledFor.Clear(); textsCalledFor.Clear(); driver = driver.AddAdditionalTexts(ImmutableArray.Create<AdditionalText>(text2)); driver = driver.RunGenerators(compilation); Assert.Equal(0, compilationsCalledFor.Count); Assert.Equal(1, textsCalledFor.Count); Assert.Equal(text2, textsCalledFor[0]); // now edit the compilation compilationsCalledFor.Clear(); textsCalledFor.Clear(); var newCompilation = compilation.WithOptions(compilation.Options.WithModuleName("newComp")); driver = driver.RunGenerators(newCompilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(newCompilation, compilationsCalledFor[0]); Assert.Equal(0, textsCalledFor.Count); // re run without changing anything compilationsCalledFor.Clear(); textsCalledFor.Clear(); driver = driver.RunGenerators(newCompilation); Assert.Equal(0, compilationsCalledFor.Count); Assert.Equal(0, textsCalledFor.Count); } [Fact] public void IncrementalGenerator_Can_Add_Comparer_To_Input_Node() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<Compilation> compilationsCalledFor = new List<Compilation>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { var compilationSource = ctx.CompilationProvider.WithComparer(new LambdaComparer<Compilation>((c1, c2) => true, 0)); ctx.RegisterSourceOutput(compilationSource, (spc, c) => { compilationsCalledFor.Add(c); }); })); // run the generator once, and check it was passed the compilation GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(compilation, compilationsCalledFor[0]); // now edit the compilation, run the generator, and confirm that the output was not called again this time Compilation newCompilation = compilation.WithOptions(compilation.Options.WithModuleName("newCompilation")); driver = driver.RunGenerators(newCompilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(compilation, compilationsCalledFor[0]); } [Fact] public void IncrementalGenerator_Can_Add_Comparer_To_Combine_Node() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<AdditionalText> texts = new List<AdditionalText>() { new InMemoryAdditionalText("abc", "") }; List<(Compilation, ImmutableArray<AdditionalText>)> calledFor = new List<(Compilation, ImmutableArray<AdditionalText>)>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { var compilationSource = ctx.CompilationProvider.Combine(ctx.AdditionalTextsProvider.Collect()) // comparer that ignores the LHS (additional texts) .WithComparer(new LambdaComparer<(Compilation, ImmutableArray<AdditionalText>)>((c1, c2) => c1.Item1 == c2.Item1, 0)); ctx.RegisterSourceOutput(compilationSource, (spc, c) => { calledFor.Add(c); }); })); // run the generator once, and check it was passed the compilation + additional texts GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, additionalTexts: texts); driver = driver.RunGenerators(compilation); Assert.Equal(1, calledFor.Count); Assert.Equal(compilation, calledFor[0].Item1); Assert.Equal(texts[0], calledFor[0].Item2.Single()); // edit the additional texts, and verify that the output was *not* called again on the next run driver = driver.RemoveAdditionalTexts(texts.ToImmutableArray()); driver = driver.RunGenerators(compilation); Assert.Equal(1, calledFor.Count); // now edit the compilation, run the generator, and confirm that the output *was* called again this time with the new compilation and no additional texts Compilation newCompilation = compilation.WithOptions(compilation.Options.WithModuleName("newCompilation")); driver = driver.RunGenerators(newCompilation); Assert.Equal(2, calledFor.Count); Assert.Equal(newCompilation, calledFor[1].Item1); Assert.Empty(calledFor[1].Item2); } [Fact] public void IncrementalGenerator_Register_End_Node_Only_Once_Through_Combines() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<Compilation> compilationsCalledFor = new List<Compilation>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { var source = ctx.CompilationProvider; var source2 = ctx.CompilationProvider.Combine(source); var source3 = ctx.CompilationProvider.Combine(source2); var source4 = ctx.CompilationProvider.Combine(source3); var source5 = ctx.CompilationProvider.Combine(source4); ctx.RegisterSourceOutput(source5, (spc, c) => { compilationsCalledFor.Add(c.Item1); }); })); // run the generator and check that we didn't multiple register the generate source node through the combine GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(1, compilationsCalledFor.Count); Assert.Equal(compilation, compilationsCalledFor[0]); } [Fact] public void IncrementalGenerator_PostInit_Source_Is_Cached() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<ClassDeclarationSyntax> classes = new List<ClassDeclarationSyntax>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => { ctx.RegisterPostInitializationOutput(c => c.AddSource("a", "class D {}")); ctx.RegisterSourceOutput(ctx.SyntaxProvider.CreateSyntaxProvider(static (n, _) => n is ClassDeclarationSyntax, (gsc, _) => (ClassDeclarationSyntax)gsc.Node), (spc, node) => classes.Add(node)); })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(2, classes.Count); Assert.Equal("C", classes[0].Identifier.ValueText); Assert.Equal("D", classes[1].Identifier.ValueText); // clear classes, re-run classes.Clear(); driver = driver.RunGenerators(compilation); Assert.Empty(classes); // modify the original tree, see that the post init is still cached var c2 = compilation.ReplaceSyntaxTree(compilation.SyntaxTrees.First(), CSharpSyntaxTree.ParseText("class E{}", parseOptions)); classes.Clear(); driver = driver.RunGenerators(c2); Assert.Single(classes); Assert.Equal("E", classes[0].Identifier.ValueText); } [Fact] public void Incremental_Generators_Can_Be_Cancelled() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); CancellationTokenSource cts = new CancellationTokenSource(); bool generatorCancelled = false; var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => { var step1 = ctx.CompilationProvider.Select((c, ct) => { generatorCancelled = true; cts.Cancel(); return c; }); var step2 = step1.Select((c, ct) => { ct.ThrowIfCancellationRequested(); return c; }); ctx.RegisterSourceOutput(step2, (spc, c) => spc.AddSource("a", "")); })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); Assert.Throws<OperationCanceledException>(() => driver = driver.RunGenerators(compilation, cancellationToken: cts.Token)); Assert.True(generatorCancelled); } [Fact] public void ParseOptions_Can_Be_Updated() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<ParseOptions> parseOptionsCalledFor = new List<ParseOptions>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, p) => { parseOptionsCalledFor.Add(p); }); })); // run the generator once, and check it was passed the parse options GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(1, parseOptionsCalledFor.Count); Assert.Equal(parseOptions, parseOptionsCalledFor[0]); // clear the results, and re-run parseOptionsCalledFor.Clear(); driver = driver.RunGenerators(compilation); Assert.Empty(parseOptionsCalledFor); // now update the parse options parseOptionsCalledFor.Clear(); var newParseOptions = parseOptions.WithDocumentationMode(DocumentationMode.Diagnose); driver = driver.WithUpdatedParseOptions(newParseOptions); // check we ran driver = driver.RunGenerators(compilation); Assert.Equal(1, parseOptionsCalledFor.Count); Assert.Equal(newParseOptions, parseOptionsCalledFor[0]); // clear the results, and re-run parseOptionsCalledFor.Clear(); driver = driver.RunGenerators(compilation); Assert.Empty(parseOptionsCalledFor); // replace it with null, and check that it throws Assert.Throws<ArgumentNullException>(() => driver.WithUpdatedParseOptions(null!)); } [Fact] public void AnalyzerConfig_Can_Be_Updated() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); string? analyzerOptionsValue = string.Empty; var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { ctx.RegisterSourceOutput(ctx.AnalyzerConfigOptionsProvider, (spc, p) => p.GlobalOptions.TryGetValue("test", out analyzerOptionsValue)); })); var builder = ImmutableDictionary<string, string>.Empty.ToBuilder(); builder.Add("test", "value1"); var optionsProvider = new CompilerAnalyzerConfigOptionsProvider(ImmutableDictionary<object, AnalyzerConfigOptions>.Empty, new CompilerAnalyzerConfigOptions(builder.ToImmutable())); // run the generator once, and check it was passed the configs GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, optionsProvider: optionsProvider); driver = driver.RunGenerators(compilation); Assert.Equal("value1", analyzerOptionsValue); // clear the results, and re-run analyzerOptionsValue = null; driver = driver.RunGenerators(compilation); Assert.Null(analyzerOptionsValue); // now update the config analyzerOptionsValue = null; builder.Clear(); builder.Add("test", "value2"); var newOptionsProvider = optionsProvider.WithGlobalOptions(new CompilerAnalyzerConfigOptions(builder.ToImmutable())); driver = driver.WithUpdatedAnalyzerConfigOptions(newOptionsProvider); // check we ran driver = driver.RunGenerators(compilation); Assert.Equal("value2", analyzerOptionsValue); // replace it with null, and check that it throws Assert.Throws<ArgumentNullException>(() => driver.WithUpdatedAnalyzerConfigOptions(null!)); } [Fact] public void AdditionalText_Can_Be_Replaced() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); InMemoryAdditionalText additionalText1 = new InMemoryAdditionalText("path1.txt", ""); InMemoryAdditionalText additionalText2 = new InMemoryAdditionalText("path2.txt", ""); InMemoryAdditionalText additionalText3 = new InMemoryAdditionalText("path3.txt", ""); List<string?> additionalTextPaths = new List<string?>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { ctx.RegisterSourceOutput(ctx.AdditionalTextsProvider.Select((t, _) => t.Path), (spc, p) => { additionalTextPaths.Add(p); }); })); // run the generator once and check we saw the additional file GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, additionalTexts: new[] { additionalText1, additionalText2, additionalText3 }); driver = driver.RunGenerators(compilation); Assert.Equal(3, additionalTextPaths.Count); Assert.Equal("path1.txt", additionalTextPaths[0]); Assert.Equal("path2.txt", additionalTextPaths[1]); Assert.Equal("path3.txt", additionalTextPaths[2]); // re-run and check nothing else got added additionalTextPaths.Clear(); driver = driver.RunGenerators(compilation); Assert.Empty(additionalTextPaths); // now, update the additional text, but keep the path the same additionalTextPaths.Clear(); driver = driver.ReplaceAdditionalText(additionalText2, new InMemoryAdditionalText("path4.txt", "")); // run, and check that only the replaced file was invoked driver = driver.RunGenerators(compilation); Assert.Single(additionalTextPaths); Assert.Equal("path4.txt", additionalTextPaths[0]); // replace it with null, and check that it throws Assert.Throws<ArgumentNullException>(() => driver.ReplaceAdditionalText(additionalText1, null!)); } [Fact] public void Replaced_Input_Is_Treated_As_Modified() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); InMemoryAdditionalText additionalText = new InMemoryAdditionalText("path.txt", "abc"); List<string?> additionalTextPaths = new List<string?>(); List<string?> additionalTextsContents = new List<string?>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { var texts = ctx.AdditionalTextsProvider; var paths = texts.Select((t, _) => t?.Path); var contents = texts.Select((t, _) => t?.GetText()?.ToString()); ctx.RegisterSourceOutput(paths, (spc, p) => { additionalTextPaths.Add(p); }); ctx.RegisterSourceOutput(contents, (spc, p) => { additionalTextsContents.Add(p); }); })); // run the generator once and check we saw the additional file GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, additionalTexts: new[] { additionalText }); driver = driver.RunGenerators(compilation); Assert.Equal(1, additionalTextPaths.Count); Assert.Equal("path.txt", additionalTextPaths[0]); Assert.Equal(1, additionalTextsContents.Count); Assert.Equal("abc", additionalTextsContents[0]); // re-run and check nothing else got added driver = driver.RunGenerators(compilation); Assert.Equal(1, additionalTextPaths.Count); Assert.Equal(1, additionalTextsContents.Count); // now, update the additional text, but keep the path the same additionalTextPaths.Clear(); additionalTextsContents.Clear(); var secondText = new InMemoryAdditionalText("path.txt", "def"); driver = driver.ReplaceAdditionalText(additionalText, secondText); // run, and check that only the contents got re-run driver = driver.RunGenerators(compilation); Assert.Empty(additionalTextPaths); Assert.Equal(1, additionalTextsContents.Count); Assert.Equal("def", additionalTextsContents[0]); // now replace the text with a different path, but the same text additionalTextPaths.Clear(); additionalTextsContents.Clear(); var thirdText = new InMemoryAdditionalText("path2.txt", "def"); driver = driver.ReplaceAdditionalText(secondText, thirdText); // run, and check that only the paths got re-run driver = driver.RunGenerators(compilation); Assert.Equal(1, additionalTextPaths.Count); Assert.Equal("path2.txt", additionalTextPaths[0]); Assert.Empty(additionalTextsContents); } [Theory] [CombinatorialData] [InlineData(IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.Implementation)] [InlineData(IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.PostInit)] [InlineData(IncrementalGeneratorOutputKind.Implementation | IncrementalGeneratorOutputKind.PostInit)] [InlineData(IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.Implementation | IncrementalGeneratorOutputKind.PostInit)] public void Generator_Output_Kinds_Can_Be_Disabled(IncrementalGeneratorOutputKind disabledOutput) { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); var generator = new PipelineCallbackGenerator(ctx => { ctx.RegisterPostInitializationOutput((context) => context.AddSource("PostInit", "")); ctx.RegisterSourceOutput(ctx.CompilationProvider, (context, ct) => context.AddSource("Source", "")); ctx.RegisterImplementationSourceOutput(ctx.CompilationProvider, (context, ct) => context.AddSource("Implementation", "")); }); GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator.AsSourceGenerator() }, driverOptions: new GeneratorDriverOptions(disabledOutput), parseOptions: parseOptions); driver = driver.RunGenerators(compilation); var result = driver.GetRunResult(); Assert.Single(result.Results); Assert.Empty(result.Results[0].Diagnostics); // verify the expected outputs were generated // NOTE: adding new output types will cause this test to fail. Update above as needed. foreach (IncrementalGeneratorOutputKind kind in Enum.GetValues(typeof(IncrementalGeneratorOutputKind))) { if (kind == IncrementalGeneratorOutputKind.None) continue; if (disabledOutput.HasFlag((IncrementalGeneratorOutputKind)kind)) { Assert.DoesNotContain(result.Results[0].GeneratedSources, isTextForKind); } else { Assert.Contains(result.Results[0].GeneratedSources, isTextForKind); } bool isTextForKind(GeneratedSourceResult s) => s.HintName == Enum.GetName(typeof(IncrementalGeneratorOutputKind), kind) + ".cs"; } } [Fact] public void Metadata_References_Provider() { var source = @" class C { } "; var parseOptions = TestOptions.RegularPreview; var metadataRefs = new[] { MetadataReference.CreateFromAssemblyInternal(this.GetType().Assembly), MetadataReference.CreateFromAssemblyInternal(typeof(object).Assembly) }; Compilation compilation = CreateEmptyCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions, references: metadataRefs); compilation.VerifyDiagnostics(); Assert.Single(compilation.SyntaxTrees); List<string?> referenceList = new List<string?>(); var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx => { ctx.RegisterSourceOutput(ctx.MetadataReferencesProvider, (spc, r) => { referenceList.Add(r.Display); }); })); GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions); driver = driver.RunGenerators(compilation); Assert.Equal(referenceList[0], metadataRefs[0].Display); Assert.Equal(referenceList[1], metadataRefs[1].Display); // re-run and check we didn't see anything new referenceList.Clear(); driver = driver.RunGenerators(compilation); Assert.Empty(referenceList); // Modify the reference var modifiedRef = metadataRefs[0].WithAliases(new[] { "Alias " }); metadataRefs[0] = modifiedRef; compilation = compilation.WithReferences(metadataRefs); driver = driver.RunGenerators(compilation); Assert.Single(referenceList, modifiedRef.Display); } } }
1
dotnet/roslyn
56,095
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-02T00:01:28Z"
"2021-09-02T01:47:21Z"
212ca8da034e484813ea99027c29cc3f6405fe1f
fe389d485fb73f8186b32636bfc747a39a70b028
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/Core/Portable/SourceGeneration/AdditionalSourcesCollection.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.IO; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal sealed class AdditionalSourcesCollection { private readonly ArrayBuilder<GeneratedSourceText> _sourcesAdded; private readonly string _fileExtension; private const StringComparison _hintNameComparison = StringComparison.OrdinalIgnoreCase; private static readonly StringComparer s_hintNameComparer = StringComparer.OrdinalIgnoreCase; internal AdditionalSourcesCollection(string fileExtension) { Debug.Assert(fileExtension.Length > 0 && fileExtension[0] == '.'); _sourcesAdded = ArrayBuilder<GeneratedSourceText>.GetInstance(); _fileExtension = fileExtension; } public void Add(string hintName, SourceText source) { if (string.IsNullOrWhiteSpace(hintName)) { throw new ArgumentNullException(nameof(hintName)); } // allow any identifier character or [.,-_ ()[]{}] for (int i = 0; i < hintName.Length; i++) { char c = hintName[i]; if (!UnicodeCharacterUtilities.IsIdentifierPartCharacter(c) && c != '.' && c != ',' && c != '-' && c != '_' && c != ' ' && c != '(' && c != ')' && c != '[' && c != ']' && c != '{' && c != '}') { throw new ArgumentException(string.Format(CodeAnalysisResources.HintNameInvalidChar, hintName, c, i), nameof(hintName)); } } hintName = AppendExtensionIfRequired(hintName); if (this.Contains(hintName)) { throw new ArgumentException(string.Format(CodeAnalysisResources.HintNameUniquePerGenerator, hintName), nameof(hintName)); } if (source.Encoding is null) { throw new ArgumentException(string.Format(CodeAnalysisResources.SourceTextRequiresEncoding, hintName), nameof(source)); } _sourcesAdded.Add(new GeneratedSourceText(hintName, source)); } public void RemoveSource(string hintName) { hintName = AppendExtensionIfRequired(hintName); for (int i = 0; i < _sourcesAdded.Count; i++) { if (s_hintNameComparer.Equals(_sourcesAdded[i].HintName, hintName)) { _sourcesAdded.RemoveAt(i); return; } } } public bool Contains(string hintName) { hintName = AppendExtensionIfRequired(hintName); for (int i = 0; i < _sourcesAdded.Count; i++) { if (s_hintNameComparer.Equals(_sourcesAdded[i].HintName, hintName)) { return true; } } return false; } public void CopyTo(AdditionalSourcesCollection asc) { // we know the individual hint names are valid, but we do need to check that they // don't collide with any we already have if (asc._sourcesAdded.Count == 0) { asc._sourcesAdded.AddRange(this._sourcesAdded); } else { foreach (var source in this._sourcesAdded) { if (asc.Contains(source.HintName)) { throw new ArgumentException(string.Format(CodeAnalysisResources.HintNameUniquePerGenerator, source.HintName), "hintName"); } asc._sourcesAdded.Add(source); } } } internal ImmutableArray<GeneratedSourceText> ToImmutableAndFree() => _sourcesAdded.ToImmutableAndFree(); internal ImmutableArray<GeneratedSourceText> ToImmutable() => _sourcesAdded.ToImmutable(); internal void Free() => _sourcesAdded.Free(); private string AppendExtensionIfRequired(string hintName) { if (!hintName.EndsWith(_fileExtension, _hintNameComparison)) { hintName = string.Concat(hintName, _fileExtension); } return hintName; } } }
// Licensed to the .NET Foundation under one or more 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.IO; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal sealed class AdditionalSourcesCollection { private readonly ArrayBuilder<GeneratedSourceText> _sourcesAdded; private readonly string _fileExtension; private const StringComparison _hintNameComparison = StringComparison.OrdinalIgnoreCase; private static readonly StringComparer s_hintNameComparer = StringComparer.OrdinalIgnoreCase; internal AdditionalSourcesCollection(string fileExtension) { Debug.Assert(fileExtension.Length > 0 && fileExtension[0] == '.'); _sourcesAdded = ArrayBuilder<GeneratedSourceText>.GetInstance(); _fileExtension = fileExtension; } public void Add(string hintName, SourceText source) { if (string.IsNullOrWhiteSpace(hintName)) { throw new ArgumentNullException(nameof(hintName)); } // allow any identifier character or [.,-_ ()[]{}] for (int i = 0; i < hintName.Length; i++) { char c = hintName[i]; if (!UnicodeCharacterUtilities.IsIdentifierPartCharacter(c) && c != '.' && c != ',' && c != '-' && c != '_' && c != ' ' && c != '(' && c != ')' && c != '[' && c != ']' && c != '{' && c != '}') { throw new ArgumentException(string.Format(CodeAnalysisResources.HintNameInvalidChar, hintName, c, i), nameof(hintName)); } } hintName = AppendExtensionIfRequired(hintName); if (this.Contains(hintName)) { throw new ArgumentException(string.Format(CodeAnalysisResources.HintNameUniquePerGenerator, hintName), nameof(hintName)); } if (source.Encoding is null) { throw new ArgumentException(string.Format(CodeAnalysisResources.SourceTextRequiresEncoding, hintName), nameof(source)); } _sourcesAdded.Add(new GeneratedSourceText(hintName, source)); } public void RemoveSource(string hintName) { hintName = AppendExtensionIfRequired(hintName); for (int i = 0; i < _sourcesAdded.Count; i++) { if (s_hintNameComparer.Equals(_sourcesAdded[i].HintName, hintName)) { _sourcesAdded.RemoveAt(i); return; } } } public bool Contains(string hintName) { hintName = AppendExtensionIfRequired(hintName); for (int i = 0; i < _sourcesAdded.Count; i++) { if (s_hintNameComparer.Equals(_sourcesAdded[i].HintName, hintName)) { return true; } } return false; } public void CopyTo(AdditionalSourcesCollection asc) { // we know the individual hint names are valid, but we do need to check that they // don't collide with any we already have if (asc._sourcesAdded.Count == 0) { asc._sourcesAdded.AddRange(this._sourcesAdded); } else { foreach (var source in this._sourcesAdded) { if (asc.Contains(source.HintName)) { throw new ArgumentException(string.Format(CodeAnalysisResources.HintNameUniquePerGenerator, source.HintName), "hintName"); } asc._sourcesAdded.Add(source); } } } internal ImmutableArray<GeneratedSourceText> ToImmutableAndFree() => _sourcesAdded.ToImmutableAndFree(); internal ImmutableArray<GeneratedSourceText> ToImmutable() => _sourcesAdded.ToImmutable(); internal void Free() => _sourcesAdded.Free(); private string AppendExtensionIfRequired(string hintName) { if (!hintName.EndsWith(_fileExtension, _hintNameComparison)) { hintName = string.Concat(hintName, _fileExtension); } return hintName; } } }
1
dotnet/roslyn
56,095
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-02T00:01:28Z"
"2021-09-02T01:47:21Z"
212ca8da034e484813ea99027c29cc3f6405fe1f
fe389d485fb73f8186b32636bfc747a39a70b028
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/Core/Portable/SourceGeneration/GeneratorAdaptor.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.Linq; using System.Threading; namespace Microsoft.CodeAnalysis { /// <summary> /// Adapts an ISourceGenerator to an incremental generator that /// by providing an execution environment that matches the old one /// </summary> internal sealed class SourceGeneratorAdaptor : IIncrementalGenerator { private readonly string _sourceExtension; internal ISourceGenerator SourceGenerator { get; } public SourceGeneratorAdaptor(ISourceGenerator generator, string sourceExtension) { SourceGenerator = generator; _sourceExtension = sourceExtension; } public void Initialize(IncrementalGeneratorInitializationContext context) { GeneratorInitializationContext generatorInitContext = new GeneratorInitializationContext(CancellationToken.None); SourceGenerator.Initialize(generatorInitContext); if (generatorInitContext.InfoBuilder.PostInitCallback is object) { context.RegisterPostInitializationOutput(generatorInitContext.InfoBuilder.PostInitCallback); } var contextBuilderSource = context.CompilationProvider .Select((c, _) => new GeneratorContextBuilder(c)) .Combine(context.ParseOptionsProvider).Select((p, _) => p.Item1 with { ParseOptions = p.Item2 }) .Combine(context.AnalyzerConfigOptionsProvider).Select((p, _) => p.Item1 with { ConfigOptions = p.Item2 }) .Combine(context.AdditionalTextsProvider.Collect()).Select((p, _) => p.Item1 with { AdditionalTexts = p.Item2 }); var syntaxContextReceiverCreator = generatorInitContext.InfoBuilder.SyntaxContextReceiverCreator; if (syntaxContextReceiverCreator is object) { contextBuilderSource = contextBuilderSource .Combine(context.SyntaxProvider.CreateSyntaxReceiverProvider(syntaxContextReceiverCreator)) .Select((p, _) => p.Item1 with { Receiver = p.Item2 }); } context.RegisterSourceOutput(contextBuilderSource, (productionContext, contextBuilder) => { var generatorExecutionContext = contextBuilder.ToExecutionContext(_sourceExtension, productionContext.CancellationToken); SourceGenerator.Execute(generatorExecutionContext); // copy the contents of the old context to the new generatorExecutionContext.CopyToProductionContext(productionContext); generatorExecutionContext.Free(); }); } internal record GeneratorContextBuilder(Compilation Compilation) { public ParseOptions? ParseOptions; public ImmutableArray<AdditionalText> AdditionalTexts; public Diagnostics.AnalyzerConfigOptionsProvider? ConfigOptions; public ISyntaxContextReceiver? Receiver; public GeneratorExecutionContext ToExecutionContext(string sourceExtension, CancellationToken cancellationToken) { Debug.Assert(ParseOptions is object && ConfigOptions is object); return new GeneratorExecutionContext(Compilation, ParseOptions, AdditionalTexts, ConfigOptions, Receiver, sourceExtension, 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.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; namespace Microsoft.CodeAnalysis { /// <summary> /// Adapts an ISourceGenerator to an incremental generator that /// by providing an execution environment that matches the old one /// </summary> internal sealed class SourceGeneratorAdaptor : IIncrementalGenerator { private readonly string _sourceExtension; internal ISourceGenerator SourceGenerator { get; } public SourceGeneratorAdaptor(ISourceGenerator generator, string sourceExtension) { SourceGenerator = generator; _sourceExtension = sourceExtension; } public void Initialize(IncrementalGeneratorInitializationContext context) { GeneratorInitializationContext generatorInitContext = new GeneratorInitializationContext(CancellationToken.None); SourceGenerator.Initialize(generatorInitContext); if (generatorInitContext.InfoBuilder.PostInitCallback is object) { context.RegisterPostInitializationOutput(generatorInitContext.InfoBuilder.PostInitCallback); } var contextBuilderSource = context.CompilationProvider .Select((c, _) => new GeneratorContextBuilder(c)) .Combine(context.ParseOptionsProvider).Select((p, _) => p.Item1 with { ParseOptions = p.Item2 }) .Combine(context.AnalyzerConfigOptionsProvider).Select((p, _) => p.Item1 with { ConfigOptions = p.Item2 }) .Combine(context.AdditionalTextsProvider.Collect()).Select((p, _) => p.Item1 with { AdditionalTexts = p.Item2 }); var syntaxContextReceiverCreator = generatorInitContext.InfoBuilder.SyntaxContextReceiverCreator; if (syntaxContextReceiverCreator is object) { contextBuilderSource = contextBuilderSource .Combine(context.SyntaxProvider.CreateSyntaxReceiverProvider(syntaxContextReceiverCreator)) .Select((p, _) => p.Item1 with { Receiver = p.Item2 }); } context.RegisterSourceOutput(contextBuilderSource, (productionContext, contextBuilder) => { var generatorExecutionContext = contextBuilder.ToExecutionContext(_sourceExtension, productionContext.CancellationToken); SourceGenerator.Execute(generatorExecutionContext); // copy the contents of the old context to the new generatorExecutionContext.CopyToProductionContext(productionContext); generatorExecutionContext.Free(); }); } internal record GeneratorContextBuilder(Compilation Compilation) { public ParseOptions? ParseOptions; public ImmutableArray<AdditionalText> AdditionalTexts; public Diagnostics.AnalyzerConfigOptionsProvider? ConfigOptions; public ISyntaxContextReceiver? Receiver; public GeneratorExecutionContext ToExecutionContext(string sourceExtension, CancellationToken cancellationToken) { Debug.Assert(ParseOptions is object && ConfigOptions is object); return new GeneratorExecutionContext(Compilation, ParseOptions, AdditionalTexts, ConfigOptions, Receiver, sourceExtension, cancellationToken); } } } }
1
dotnet/roslyn
56,095
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-02T00:01:28Z"
"2021-09-02T01:47:21Z"
212ca8da034e484813ea99027c29cc3f6405fe1f
fe389d485fb73f8186b32636bfc747a39a70b028
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/Core/Portable/SourceGeneration/GeneratorContexts.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.Text; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Context passed to a source generator when <see cref="ISourceGenerator.Execute(GeneratorExecutionContext)"/> is called /// </summary> public readonly struct GeneratorExecutionContext { private readonly DiagnosticBag _diagnostics; private readonly AdditionalSourcesCollection _additionalSources; internal GeneratorExecutionContext(Compilation compilation, ParseOptions parseOptions, ImmutableArray<AdditionalText> additionalTexts, AnalyzerConfigOptionsProvider optionsProvider, ISyntaxContextReceiver? syntaxReceiver, string sourceExtension, CancellationToken cancellationToken = default) { Compilation = compilation; ParseOptions = parseOptions; AdditionalFiles = additionalTexts; AnalyzerConfigOptions = optionsProvider; SyntaxReceiver = (syntaxReceiver as SyntaxContextReceiverAdaptor)?.Receiver; SyntaxContextReceiver = (syntaxReceiver is SyntaxContextReceiverAdaptor) ? null : syntaxReceiver; CancellationToken = cancellationToken; _additionalSources = new AdditionalSourcesCollection(sourceExtension); _diagnostics = new DiagnosticBag(); } /// <summary> /// Get the current <see cref="CodeAnalysis.Compilation"/> at the time of execution. /// </summary> /// <remarks> /// This compilation contains only the user supplied code; other generated code is not /// available. As user code can depend on the results of generation, it is possible that /// this compilation will contain errors. /// </remarks> public Compilation Compilation { get; } /// <summary> /// Get the <see cref="CodeAnalysis.ParseOptions"/> that will be used to parse any added sources. /// </summary> public ParseOptions ParseOptions { get; } /// <summary> /// A set of additional non-code text files that can be used by generators. /// </summary> public ImmutableArray<AdditionalText> AdditionalFiles { get; } /// <summary> /// Allows access to options provided by an analyzer config /// </summary> public AnalyzerConfigOptionsProvider AnalyzerConfigOptions { get; } /// <summary> /// If the generator registered an <see cref="ISyntaxReceiver"/> during initialization, this will be the instance created for this generation pass. /// </summary> public ISyntaxReceiver? SyntaxReceiver { get; } /// <summary> /// If the generator registered an <see cref="ISyntaxContextReceiver"/> during initialization, this will be the instance created for this generation pass. /// </summary> public ISyntaxContextReceiver? SyntaxContextReceiver { get; } /// <summary> /// A <see cref="System.Threading.CancellationToken"/> that can be checked to see if the generation should be cancelled. /// </summary> public CancellationToken CancellationToken { get; } /// <summary> /// Adds source code in the form of a <see cref="string"/> to the compilation. /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="source">The source code to add to the compilation</param> public void AddSource(string hintName, string source) => AddSource(hintName, SourceText.From(source, Encoding.UTF8)); /// <summary> /// Adds a <see cref="SourceText"/> to the compilation /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="sourceText">The <see cref="SourceText"/> to add to the compilation</param> public void AddSource(string hintName, SourceText sourceText) => _additionalSources.Add(hintName, sourceText); /// <summary> /// Adds a <see cref="Diagnostic"/> to the users compilation /// </summary> /// <param name="diagnostic">The diagnostic that should be added to the compilation</param> /// <remarks> /// The severity of the diagnostic may cause the compilation to fail, depending on the <see cref="Compilation"/> settings. /// </remarks> public void ReportDiagnostic(Diagnostic diagnostic) => _diagnostics.Add(diagnostic); internal (ImmutableArray<GeneratedSourceText> sources, ImmutableArray<Diagnostic> diagnostics) ToImmutableAndFree() => (_additionalSources.ToImmutableAndFree(), _diagnostics.ToReadOnlyAndFree()); internal void Free() { _additionalSources.Free(); _diagnostics.Free(); } internal void CopyToProductionContext(SourceProductionContext ctx) { _additionalSources.CopyTo(ctx.Sources); ctx.Diagnostics.AddRange(_diagnostics); } } /// <summary> /// Context passed to a source generator when <see cref="ISourceGenerator.Initialize(GeneratorInitializationContext)"/> is called /// </summary> public struct GeneratorInitializationContext { internal GeneratorInitializationContext(CancellationToken cancellationToken = default) { CancellationToken = cancellationToken; InfoBuilder = new GeneratorInfo.Builder(); } /// <summary> /// A <see cref="System.Threading.CancellationToken"/> that can be checked to see if the initialization should be cancelled. /// </summary> public CancellationToken CancellationToken { get; } internal GeneratorInfo.Builder InfoBuilder { get; } /// <summary> /// Register a <see cref="SyntaxReceiverCreator"/> for this generator, which can be used to create an instance of an <see cref="ISyntaxReceiver"/>. /// </summary> /// <remarks> /// This method allows generators to be 'syntax aware'. Before each generation the <paramref name="receiverCreator"/> will be invoked to create /// an instance of <see cref="ISyntaxReceiver"/>. This receiver will have its <see cref="ISyntaxReceiver.OnVisitSyntaxNode(SyntaxNode)"/> /// invoked for each syntax node in the compilation, allowing the receiver to build up information about the compilation before generation occurs. /// /// During <see cref="ISourceGenerator.Execute(GeneratorExecutionContext)"/> the generator can obtain the <see cref="ISyntaxReceiver"/> instance that was /// created by accessing the <see cref="GeneratorExecutionContext.SyntaxReceiver"/> property. Any information that was collected by the receiver can be /// used to generate the final output. /// /// A new instance of <see cref="ISyntaxReceiver"/> is created per-generation, meaning there is no need to manage the lifetime of the /// receiver or its contents. /// </remarks> /// <param name="receiverCreator">A <see cref="SyntaxReceiverCreator"/> that can be invoked to create an instance of <see cref="ISyntaxReceiver"/></param> public void RegisterForSyntaxNotifications(SyntaxReceiverCreator receiverCreator) { CheckIsEmpty(InfoBuilder.SyntaxContextReceiverCreator, $"{nameof(SyntaxReceiverCreator)} / {nameof(SyntaxContextReceiverCreator)}"); InfoBuilder.SyntaxContextReceiverCreator = SyntaxContextReceiverAdaptor.Create(receiverCreator); } /// <summary> /// Register a <see cref="SyntaxContextReceiverCreator"/> for this generator, which can be used to create an instance of an <see cref="ISyntaxContextReceiver"/>. /// </summary> /// <remarks> /// This method allows generators to be 'syntax aware'. Before each generation the <paramref name="receiverCreator"/> will be invoked to create /// an instance of <see cref="ISyntaxContextReceiver"/>. This receiver will have its <see cref="ISyntaxContextReceiver.OnVisitSyntaxNode(GeneratorSyntaxContext)"/> /// invoked for each syntax node in the compilation, allowing the receiver to build up information about the compilation before generation occurs. /// /// During <see cref="ISourceGenerator.Execute(GeneratorExecutionContext)"/> the generator can obtain the <see cref="ISyntaxContextReceiver"/> instance that was /// created by accessing the <see cref="GeneratorExecutionContext.SyntaxContextReceiver"/> property. Any information that was collected by the receiver can be /// used to generate the final output. /// /// A new instance of <see cref="ISyntaxContextReceiver"/> is created prior to every call to <see cref="ISourceGenerator.Execute(GeneratorExecutionContext)"/>, /// meaning there is no need to manage the lifetime of the receiver or its contents. /// </remarks> /// <param name="receiverCreator">A <see cref="SyntaxContextReceiverCreator"/> that can be invoked to create an instance of <see cref="ISyntaxContextReceiver"/></param> public void RegisterForSyntaxNotifications(SyntaxContextReceiverCreator receiverCreator) { CheckIsEmpty(InfoBuilder.SyntaxContextReceiverCreator, $"{nameof(SyntaxReceiverCreator)} / {nameof(SyntaxContextReceiverCreator)}"); InfoBuilder.SyntaxContextReceiverCreator = receiverCreator; } /// <summary> /// Register a callback that is invoked after initialization. /// </summary> /// <remarks> /// This method allows a generator to opt-in to an extra phase in the generator lifecycle called PostInitialization. After being initialized /// any generators that have opted in will have their provided callback invoked with a <see cref="GeneratorPostInitializationContext"/> instance /// that can be used to alter the compilation that is provided to subsequent generator phases. /// /// For example a generator may choose to add sources during PostInitialization. These will be added to the compilation before execution and /// will be visited by a registered <see cref="ISyntaxReceiver"/> and available for semantic analysis as part of the <see cref="GeneratorExecutionContext.Compilation"/> /// /// Note that any sources added during PostInitialization <i>will</i> be visible to the later phases of other generators operating on the compilation. /// </remarks> /// <param name="callback">An <see cref="Action{T}"/> that accepts a <see cref="GeneratorPostInitializationContext"/> that will be invoked after initialization.</param> public void RegisterForPostInitialization(Action<GeneratorPostInitializationContext> callback) { CheckIsEmpty(InfoBuilder.PostInitCallback); InfoBuilder.PostInitCallback = (context) => callback(new GeneratorPostInitializationContext(context.AdditionalSources, context.CancellationToken)); } private static void CheckIsEmpty<T>(T x, string? typeName = null) where T : class? { if (x is object) { throw new InvalidOperationException(string.Format(CodeAnalysisResources.Single_type_per_generator_0, typeName ?? typeof(T).Name)); } } } /// <summary> /// Context passed to an <see cref="ISyntaxContextReceiver"/> when <see cref="ISyntaxContextReceiver.OnVisitSyntaxNode(GeneratorSyntaxContext)"/> is called /// </summary> public readonly struct GeneratorSyntaxContext { internal GeneratorSyntaxContext(SyntaxNode node, SemanticModel semanticModel) { Node = node; SemanticModel = semanticModel; } /// <summary> /// The <see cref="SyntaxNode"/> currently being visited /// </summary> public SyntaxNode Node { get; } /// <summary> /// The <see cref="CodeAnalysis.SemanticModel" /> that can be queried to obtain information about <see cref="Node"/>. /// </summary> public SemanticModel SemanticModel { get; } } /// <summary> /// Context passed to a source generator when it has opted-in to PostInitialization via <see cref="GeneratorInitializationContext.RegisterForPostInitialization(Action{GeneratorPostInitializationContext})"/> /// </summary> public readonly struct GeneratorPostInitializationContext { private readonly AdditionalSourcesCollection _additionalSources; internal GeneratorPostInitializationContext(AdditionalSourcesCollection additionalSources, CancellationToken cancellationToken) { _additionalSources = additionalSources; CancellationToken = cancellationToken; } /// <summary> /// A <see cref="System.Threading.CancellationToken"/> that can be checked to see if the PostInitialization should be cancelled. /// </summary> public CancellationToken CancellationToken { get; } /// <summary> /// Adds source code in the form of a <see cref="string"/> to the compilation that will be available during subsequent phases /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="source">The source code to add to the compilation</param> public void AddSource(string hintName, string source) => AddSource(hintName, SourceText.From(source, Encoding.UTF8)); /// <summary> /// Adds a <see cref="SourceText"/> to the compilation that will be available during subsequent phases /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="sourceText">The <see cref="SourceText"/> to add to the compilation</param> public void AddSource(string hintName, SourceText sourceText) => _additionalSources.Add(hintName, sourceText); } }
// Licensed to the .NET Foundation under one or more 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.Text; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Context passed to a source generator when <see cref="ISourceGenerator.Execute(GeneratorExecutionContext)"/> is called /// </summary> public readonly struct GeneratorExecutionContext { private readonly DiagnosticBag _diagnostics; private readonly AdditionalSourcesCollection _additionalSources; internal GeneratorExecutionContext(Compilation compilation, ParseOptions parseOptions, ImmutableArray<AdditionalText> additionalTexts, AnalyzerConfigOptionsProvider optionsProvider, ISyntaxContextReceiver? syntaxReceiver, string sourceExtension, CancellationToken cancellationToken = default) { Compilation = compilation; ParseOptions = parseOptions; AdditionalFiles = additionalTexts; AnalyzerConfigOptions = optionsProvider; SyntaxReceiver = (syntaxReceiver as SyntaxContextReceiverAdaptor)?.Receiver; SyntaxContextReceiver = (syntaxReceiver is SyntaxContextReceiverAdaptor) ? null : syntaxReceiver; CancellationToken = cancellationToken; _additionalSources = new AdditionalSourcesCollection(sourceExtension); _diagnostics = new DiagnosticBag(); } /// <summary> /// Get the current <see cref="CodeAnalysis.Compilation"/> at the time of execution. /// </summary> /// <remarks> /// This compilation contains only the user supplied code; other generated code is not /// available. As user code can depend on the results of generation, it is possible that /// this compilation will contain errors. /// </remarks> public Compilation Compilation { get; } /// <summary> /// Get the <see cref="CodeAnalysis.ParseOptions"/> that will be used to parse any added sources. /// </summary> public ParseOptions ParseOptions { get; } /// <summary> /// A set of additional non-code text files that can be used by generators. /// </summary> public ImmutableArray<AdditionalText> AdditionalFiles { get; } /// <summary> /// Allows access to options provided by an analyzer config /// </summary> public AnalyzerConfigOptionsProvider AnalyzerConfigOptions { get; } /// <summary> /// If the generator registered an <see cref="ISyntaxReceiver"/> during initialization, this will be the instance created for this generation pass. /// </summary> public ISyntaxReceiver? SyntaxReceiver { get; } /// <summary> /// If the generator registered an <see cref="ISyntaxContextReceiver"/> during initialization, this will be the instance created for this generation pass. /// </summary> public ISyntaxContextReceiver? SyntaxContextReceiver { get; } /// <summary> /// A <see cref="System.Threading.CancellationToken"/> that can be checked to see if the generation should be cancelled. /// </summary> public CancellationToken CancellationToken { get; } /// <summary> /// Adds source code in the form of a <see cref="string"/> to the compilation. /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="source">The source code to add to the compilation</param> public void AddSource(string hintName, string source) => AddSource(hintName, SourceText.From(source, Encoding.UTF8)); /// <summary> /// Adds a <see cref="SourceText"/> to the compilation /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="sourceText">The <see cref="SourceText"/> to add to the compilation</param> public void AddSource(string hintName, SourceText sourceText) => _additionalSources.Add(hintName, sourceText); /// <summary> /// Adds a <see cref="Diagnostic"/> to the users compilation /// </summary> /// <param name="diagnostic">The diagnostic that should be added to the compilation</param> /// <remarks> /// The severity of the diagnostic may cause the compilation to fail, depending on the <see cref="Compilation"/> settings. /// </remarks> public void ReportDiagnostic(Diagnostic diagnostic) => _diagnostics.Add(diagnostic); internal (ImmutableArray<GeneratedSourceText> sources, ImmutableArray<Diagnostic> diagnostics) ToImmutableAndFree() => (_additionalSources.ToImmutableAndFree(), _diagnostics.ToReadOnlyAndFree()); internal void Free() { _additionalSources.Free(); _diagnostics.Free(); } internal void CopyToProductionContext(SourceProductionContext ctx) { _additionalSources.CopyTo(ctx.Sources); ctx.Diagnostics.AddRange(_diagnostics); } } /// <summary> /// Context passed to a source generator when <see cref="ISourceGenerator.Initialize(GeneratorInitializationContext)"/> is called /// </summary> public struct GeneratorInitializationContext { internal GeneratorInitializationContext(CancellationToken cancellationToken = default) { CancellationToken = cancellationToken; InfoBuilder = new GeneratorInfo.Builder(); } /// <summary> /// A <see cref="System.Threading.CancellationToken"/> that can be checked to see if the initialization should be cancelled. /// </summary> public CancellationToken CancellationToken { get; } internal GeneratorInfo.Builder InfoBuilder { get; } /// <summary> /// Register a <see cref="SyntaxReceiverCreator"/> for this generator, which can be used to create an instance of an <see cref="ISyntaxReceiver"/>. /// </summary> /// <remarks> /// This method allows generators to be 'syntax aware'. Before each generation the <paramref name="receiverCreator"/> will be invoked to create /// an instance of <see cref="ISyntaxReceiver"/>. This receiver will have its <see cref="ISyntaxReceiver.OnVisitSyntaxNode(SyntaxNode)"/> /// invoked for each syntax node in the compilation, allowing the receiver to build up information about the compilation before generation occurs. /// /// During <see cref="ISourceGenerator.Execute(GeneratorExecutionContext)"/> the generator can obtain the <see cref="ISyntaxReceiver"/> instance that was /// created by accessing the <see cref="GeneratorExecutionContext.SyntaxReceiver"/> property. Any information that was collected by the receiver can be /// used to generate the final output. /// /// A new instance of <see cref="ISyntaxReceiver"/> is created per-generation, meaning there is no need to manage the lifetime of the /// receiver or its contents. /// </remarks> /// <param name="receiverCreator">A <see cref="SyntaxReceiverCreator"/> that can be invoked to create an instance of <see cref="ISyntaxReceiver"/></param> public void RegisterForSyntaxNotifications(SyntaxReceiverCreator receiverCreator) { CheckIsEmpty(InfoBuilder.SyntaxContextReceiverCreator, $"{nameof(SyntaxReceiverCreator)} / {nameof(SyntaxContextReceiverCreator)}"); InfoBuilder.SyntaxContextReceiverCreator = SyntaxContextReceiverAdaptor.Create(receiverCreator); } /// <summary> /// Register a <see cref="SyntaxContextReceiverCreator"/> for this generator, which can be used to create an instance of an <see cref="ISyntaxContextReceiver"/>. /// </summary> /// <remarks> /// This method allows generators to be 'syntax aware'. Before each generation the <paramref name="receiverCreator"/> will be invoked to create /// an instance of <see cref="ISyntaxContextReceiver"/>. This receiver will have its <see cref="ISyntaxContextReceiver.OnVisitSyntaxNode(GeneratorSyntaxContext)"/> /// invoked for each syntax node in the compilation, allowing the receiver to build up information about the compilation before generation occurs. /// /// During <see cref="ISourceGenerator.Execute(GeneratorExecutionContext)"/> the generator can obtain the <see cref="ISyntaxContextReceiver"/> instance that was /// created by accessing the <see cref="GeneratorExecutionContext.SyntaxContextReceiver"/> property. Any information that was collected by the receiver can be /// used to generate the final output. /// /// A new instance of <see cref="ISyntaxContextReceiver"/> is created prior to every call to <see cref="ISourceGenerator.Execute(GeneratorExecutionContext)"/>, /// meaning there is no need to manage the lifetime of the receiver or its contents. /// </remarks> /// <param name="receiverCreator">A <see cref="SyntaxContextReceiverCreator"/> that can be invoked to create an instance of <see cref="ISyntaxContextReceiver"/></param> public void RegisterForSyntaxNotifications(SyntaxContextReceiverCreator receiverCreator) { CheckIsEmpty(InfoBuilder.SyntaxContextReceiverCreator, $"{nameof(SyntaxReceiverCreator)} / {nameof(SyntaxContextReceiverCreator)}"); InfoBuilder.SyntaxContextReceiverCreator = receiverCreator; } /// <summary> /// Register a callback that is invoked after initialization. /// </summary> /// <remarks> /// This method allows a generator to opt-in to an extra phase in the generator lifecycle called PostInitialization. After being initialized /// any generators that have opted in will have their provided callback invoked with a <see cref="GeneratorPostInitializationContext"/> instance /// that can be used to alter the compilation that is provided to subsequent generator phases. /// /// For example a generator may choose to add sources during PostInitialization. These will be added to the compilation before execution and /// will be visited by a registered <see cref="ISyntaxReceiver"/> and available for semantic analysis as part of the <see cref="GeneratorExecutionContext.Compilation"/> /// /// Note that any sources added during PostInitialization <i>will</i> be visible to the later phases of other generators operating on the compilation. /// </remarks> /// <param name="callback">An <see cref="Action{T}"/> that accepts a <see cref="GeneratorPostInitializationContext"/> that will be invoked after initialization.</param> public void RegisterForPostInitialization(Action<GeneratorPostInitializationContext> callback) { CheckIsEmpty(InfoBuilder.PostInitCallback); InfoBuilder.PostInitCallback = (context) => callback(new GeneratorPostInitializationContext(context.AdditionalSources, context.CancellationToken)); } private static void CheckIsEmpty<T>(T x, string? typeName = null) where T : class? { if (x is object) { throw new InvalidOperationException(string.Format(CodeAnalysisResources.Single_type_per_generator_0, typeName ?? typeof(T).Name)); } } } /// <summary> /// Context passed to an <see cref="ISyntaxContextReceiver"/> when <see cref="ISyntaxContextReceiver.OnVisitSyntaxNode(GeneratorSyntaxContext)"/> is called /// </summary> public readonly struct GeneratorSyntaxContext { internal GeneratorSyntaxContext(SyntaxNode node, SemanticModel semanticModel) { Node = node; SemanticModel = semanticModel; } /// <summary> /// The <see cref="SyntaxNode"/> currently being visited /// </summary> public SyntaxNode Node { get; } /// <summary> /// The <see cref="CodeAnalysis.SemanticModel" /> that can be queried to obtain information about <see cref="Node"/>. /// </summary> public SemanticModel SemanticModel { get; } } /// <summary> /// Context passed to a source generator when it has opted-in to PostInitialization via <see cref="GeneratorInitializationContext.RegisterForPostInitialization(Action{GeneratorPostInitializationContext})"/> /// </summary> public readonly struct GeneratorPostInitializationContext { private readonly AdditionalSourcesCollection _additionalSources; internal GeneratorPostInitializationContext(AdditionalSourcesCollection additionalSources, CancellationToken cancellationToken) { _additionalSources = additionalSources; CancellationToken = cancellationToken; } /// <summary> /// A <see cref="System.Threading.CancellationToken"/> that can be checked to see if the PostInitialization should be cancelled. /// </summary> public CancellationToken CancellationToken { get; } /// <summary> /// Adds source code in the form of a <see cref="string"/> to the compilation that will be available during subsequent phases /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="source">The source code to add to the compilation</param> public void AddSource(string hintName, string source) => AddSource(hintName, SourceText.From(source, Encoding.UTF8)); /// <summary> /// Adds a <see cref="SourceText"/> to the compilation that will be available during subsequent phases /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="sourceText">The <see cref="SourceText"/> to add to the compilation</param> public void AddSource(string hintName, SourceText sourceText) => _additionalSources.Add(hintName, sourceText); } }
1
dotnet/roslyn
56,095
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-02T00:01:28Z"
"2021-09-02T01:47:21Z"
212ca8da034e484813ea99027c29cc3f6405fe1f
fe389d485fb73f8186b32636bfc747a39a70b028
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/Core/Portable/SourceGeneration/GeneratorDriver.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; using System.Globalization; using System.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Responsible for orchestrating a source generation pass /// </summary> /// <remarks> /// GeneratorDriver is an immutable class that can be manipulated by returning a mutated copy of itself. /// In the compiler we only ever create a single instance and ignore the mutated copy. The IDE may perform /// multiple edits, or generation passes of the same driver, re-using the state as needed. /// </remarks> public abstract class GeneratorDriver { internal readonly GeneratorDriverState _state; internal GeneratorDriver(GeneratorDriverState state) { Debug.Assert(state.Generators.GroupBy(s => s.GetGeneratorType()).Count() == state.Generators.Length); // ensure we don't have duplicate generator types _state = state; } internal GeneratorDriver(ParseOptions parseOptions, ImmutableArray<ISourceGenerator> generators, AnalyzerConfigOptionsProvider optionsProvider, ImmutableArray<AdditionalText> additionalTexts, GeneratorDriverOptions driverOptions) { (var filteredGenerators, var incrementalGenerators) = GetIncrementalGenerators(generators, SourceExtension); _state = new GeneratorDriverState(parseOptions, optionsProvider, filteredGenerators, incrementalGenerators, additionalTexts, ImmutableArray.Create(new GeneratorState[filteredGenerators.Length]), DriverStateTable.Empty, driverOptions.DisabledOutputs); } public GeneratorDriver RunGenerators(Compilation compilation, CancellationToken cancellationToken = default) { var state = RunGeneratorsCore(compilation, diagnosticsBag: null, cancellationToken); //don't directly collect diagnostics on this path return FromState(state); } public GeneratorDriver RunGeneratorsAndUpdateCompilation(Compilation compilation, out Compilation outputCompilation, out ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken = default) { var diagnosticsBag = DiagnosticBag.GetInstance(); var state = RunGeneratorsCore(compilation, diagnosticsBag, cancellationToken); // build the output compilation diagnostics = diagnosticsBag.ToReadOnlyAndFree(); ArrayBuilder<SyntaxTree> trees = ArrayBuilder<SyntaxTree>.GetInstance(); foreach (var generatorState in state.GeneratorStates) { trees.AddRange(generatorState.PostInitTrees.Select(t => t.Tree)); trees.AddRange(generatorState.GeneratedTrees.Select(t => t.Tree)); } outputCompilation = compilation.AddSyntaxTrees(trees); trees.Free(); return FromState(state); } public GeneratorDriver AddGenerators(ImmutableArray<ISourceGenerator> generators) { (var filteredGenerators, var incrementalGenerators) = GetIncrementalGenerators(generators, SourceExtension); var newState = _state.With(sourceGenerators: _state.Generators.AddRange(filteredGenerators), incrementalGenerators: _state.IncrementalGenerators.AddRange(incrementalGenerators), generatorStates: _state.GeneratorStates.AddRange(new GeneratorState[filteredGenerators.Length])); return FromState(newState); } public GeneratorDriver RemoveGenerators(ImmutableArray<ISourceGenerator> generators) { var newGenerators = _state.Generators; var newStates = _state.GeneratorStates; var newIncrementalGenerators = _state.IncrementalGenerators; for (int i = 0; i < newGenerators.Length; i++) { if (generators.Contains(newGenerators[i])) { newGenerators = newGenerators.RemoveAt(i); newStates = newStates.RemoveAt(i); newIncrementalGenerators = newIncrementalGenerators.RemoveAt(i); i--; } } return FromState(_state.With(sourceGenerators: newGenerators, incrementalGenerators: newIncrementalGenerators, generatorStates: newStates)); } public GeneratorDriver AddAdditionalTexts(ImmutableArray<AdditionalText> additionalTexts) { var newState = _state.With(additionalTexts: _state.AdditionalTexts.AddRange(additionalTexts)); return FromState(newState); } public GeneratorDriver RemoveAdditionalTexts(ImmutableArray<AdditionalText> additionalTexts) { var newState = _state.With(additionalTexts: _state.AdditionalTexts.RemoveRange(additionalTexts)); return FromState(newState); } public GeneratorDriver ReplaceAdditionalText(AdditionalText oldText, AdditionalText newText) { if (oldText is null) { throw new ArgumentNullException(nameof(oldText)); } if (newText is null) { throw new ArgumentNullException(nameof(newText)); } var newState = _state.With(additionalTexts: _state.AdditionalTexts.Replace(oldText, newText)); return FromState(newState); } public GeneratorDriver WithUpdatedParseOptions(ParseOptions newOptions) => newOptions is object ? FromState(_state.With(parseOptions: newOptions)) : throw new ArgumentNullException(nameof(newOptions)); public GeneratorDriver WithUpdatedAnalyzerConfigOptions(AnalyzerConfigOptionsProvider newOptions) => newOptions is object ? FromState(_state.With(optionsProvider: newOptions)) : throw new ArgumentNullException(nameof(newOptions)); public GeneratorDriverRunResult GetRunResult() { var results = _state.Generators.ZipAsArray( _state.GeneratorStates, (generator, generatorState) => new GeneratorRunResult(generator, diagnostics: generatorState.Diagnostics, exception: generatorState.Exception, generatedSources: getGeneratorSources(generatorState))); return new GeneratorDriverRunResult(results); static ImmutableArray<GeneratedSourceResult> getGeneratorSources(GeneratorState generatorState) { ArrayBuilder<GeneratedSourceResult> sources = ArrayBuilder<GeneratedSourceResult>.GetInstance(generatorState.PostInitTrees.Length + generatorState.GeneratedTrees.Length); foreach (var tree in generatorState.PostInitTrees) { sources.Add(new GeneratedSourceResult(tree.Tree, tree.Text, tree.HintName)); } foreach (var tree in generatorState.GeneratedTrees) { sources.Add(new GeneratedSourceResult(tree.Tree, tree.Text, tree.HintName)); } return sources.ToImmutableAndFree(); } } internal GeneratorDriverState RunGeneratorsCore(Compilation compilation, DiagnosticBag? diagnosticsBag, CancellationToken cancellationToken = default) { // with no generators, there is no work to do if (_state.Generators.IsEmpty) { return _state.With(stateTable: DriverStateTable.Empty); } // run the actual generation var state = _state; var stateBuilder = ArrayBuilder<GeneratorState>.GetInstance(state.Generators.Length); var constantSourcesBuilder = ArrayBuilder<SyntaxTree>.GetInstance(); var syntaxInputNodes = ArrayBuilder<ISyntaxInputNode>.GetInstance(); for (int i = 0; i < state.IncrementalGenerators.Length; i++) { var generator = state.IncrementalGenerators[i]; var generatorState = state.GeneratorStates[i]; var sourceGenerator = state.Generators[i]; // initialize the generator if needed if (!generatorState.Initialized) { var outputBuilder = ArrayBuilder<IIncrementalGeneratorOutputNode>.GetInstance(); var inputBuilder = ArrayBuilder<ISyntaxInputNode>.GetInstance(); var postInitSources = ImmutableArray<GeneratedSyntaxTree>.Empty; var pipelineContext = new IncrementalGeneratorInitializationContext(inputBuilder, outputBuilder, SourceExtension); Exception? ex = null; try { generator.Initialize(pipelineContext); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { ex = e; } var outputNodes = outputBuilder.ToImmutableAndFree(); var inputNodes = inputBuilder.ToImmutableAndFree(); // run post init if (ex is null) { try { IncrementalExecutionContext context = UpdateOutputs(outputNodes, IncrementalGeneratorOutputKind.PostInit, cancellationToken); postInitSources = ParseAdditionalSources(sourceGenerator, context.ToImmutableAndFree().sources, cancellationToken); } catch (UserFunctionException e) { ex = e.InnerException; } } generatorState = ex is null ? new GeneratorState(generatorState.Info, postInitSources, inputNodes, outputNodes) : SetGeneratorException(MessageProvider, generatorState, sourceGenerator, ex, diagnosticsBag, isInit: true); } // if the pipeline registered any syntax input nodes, record them if (!generatorState.InputNodes.IsEmpty) { syntaxInputNodes.AddRange(generatorState.InputNodes); } // record any constant sources if (generatorState.Exception is null && generatorState.PostInitTrees.Length > 0) { constantSourcesBuilder.AddRange(generatorState.PostInitTrees.Select(t => t.Tree)); } stateBuilder.Add(generatorState); } // update the compilation with any constant sources if (constantSourcesBuilder.Count > 0) { compilation = compilation.AddSyntaxTrees(constantSourcesBuilder); } constantSourcesBuilder.Free(); var driverStateBuilder = new DriverStateTable.Builder(compilation, _state, syntaxInputNodes.ToImmutableAndFree(), cancellationToken); for (int i = 0; i < state.IncrementalGenerators.Length; i++) { var generatorState = stateBuilder[i]; if (generatorState.Exception is object) { continue; } try { var context = UpdateOutputs(generatorState.OutputNodes, IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.Implementation, cancellationToken, driverStateBuilder); (var sources, var generatorDiagnostics) = context.ToImmutableAndFree(); generatorDiagnostics = FilterDiagnostics(compilation, generatorDiagnostics, driverDiagnostics: diagnosticsBag, cancellationToken); stateBuilder[i] = new GeneratorState(generatorState.Info, generatorState.PostInitTrees, generatorState.InputNodes, generatorState.OutputNodes, ParseAdditionalSources(state.Generators[i], sources, cancellationToken), generatorDiagnostics); } catch (UserFunctionException ufe) { stateBuilder[i] = SetGeneratorException(MessageProvider, stateBuilder[i], state.Generators[i], ufe.InnerException, diagnosticsBag); } } state = state.With(stateTable: driverStateBuilder.ToImmutable(), generatorStates: stateBuilder.ToImmutableAndFree()); return state; } private IncrementalExecutionContext UpdateOutputs(ImmutableArray<IIncrementalGeneratorOutputNode> outputNodes, IncrementalGeneratorOutputKind outputKind, CancellationToken cancellationToken, DriverStateTable.Builder? driverStateBuilder = null) { Debug.Assert(outputKind != IncrementalGeneratorOutputKind.None); IncrementalExecutionContext context = new IncrementalExecutionContext(driverStateBuilder, new AdditionalSourcesCollection(SourceExtension)); foreach (var outputNode in outputNodes) { // if we're looking for this output kind, and it has not been explicitly disabled if (outputKind.HasFlag(outputNode.Kind) && !_state.DisabledOutputs.HasFlag(outputNode.Kind)) { outputNode.AppendOutputs(context, cancellationToken); } } return context; } private ImmutableArray<GeneratedSyntaxTree> ParseAdditionalSources(ISourceGenerator generator, ImmutableArray<GeneratedSourceText> generatedSources, CancellationToken cancellationToken) { var trees = ArrayBuilder<GeneratedSyntaxTree>.GetInstance(generatedSources.Length); var type = generator.GetGeneratorType(); var prefix = GetFilePathPrefixForGenerator(generator); foreach (var source in generatedSources) { var tree = ParseGeneratedSourceText(source, Path.Combine(prefix, source.HintName), cancellationToken); trees.Add(new GeneratedSyntaxTree(source.HintName, source.Text, tree)); } return trees.ToImmutableAndFree(); } private static GeneratorState SetGeneratorException(CommonMessageProvider provider, GeneratorState generatorState, ISourceGenerator generator, Exception e, DiagnosticBag? diagnosticBag, bool isInit = false) { var errorCode = isInit ? provider.WRN_GeneratorFailedDuringInitialization : provider.WRN_GeneratorFailedDuringGeneration; // ISSUE: Diagnostics don't currently allow descriptions with arguments, so we have to manually create the diagnostic description // ISSUE: Exceptions also don't support IFormattable, so will always be in the current UI Culture. // ISSUE: See https://github.com/dotnet/roslyn/issues/46939 var description = string.Format(provider.GetDescription(errorCode).ToString(CultureInfo.CurrentUICulture), e); var descriptor = new DiagnosticDescriptor( provider.GetIdForErrorCode(errorCode), provider.GetTitle(errorCode), provider.GetMessageFormat(errorCode), description: description, category: "Compiler", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, customTags: WellKnownDiagnosticTags.AnalyzerException); var diagnostic = Diagnostic.Create(descriptor, Location.None, generator.GetGeneratorType().Name, e.GetType().Name, e.Message); diagnosticBag?.Add(diagnostic); return new GeneratorState(generatorState.Info, e, diagnostic); } private static ImmutableArray<Diagnostic> FilterDiagnostics(Compilation compilation, ImmutableArray<Diagnostic> generatorDiagnostics, DiagnosticBag? driverDiagnostics, CancellationToken cancellationToken) { ArrayBuilder<Diagnostic> filteredDiagnostics = ArrayBuilder<Diagnostic>.GetInstance(); foreach (var diag in generatorDiagnostics) { var filtered = compilation.Options.FilterDiagnostic(diag, cancellationToken); if (filtered is object) { filteredDiagnostics.Add(filtered); driverDiagnostics?.Add(filtered); } } return filteredDiagnostics.ToImmutableAndFree(); } internal static string GetFilePathPrefixForGenerator(ISourceGenerator generator) { var type = generator.GetGeneratorType(); return Path.Combine(type.Assembly.GetName().Name ?? string.Empty, type.FullName!); } private static (ImmutableArray<ISourceGenerator>, ImmutableArray<IIncrementalGenerator>) GetIncrementalGenerators(ImmutableArray<ISourceGenerator> generators, string sourceExtension) { return (generators, generators.SelectAsArray(g => g switch { IncrementalGeneratorWrapper igw => igw.Generator, IIncrementalGenerator ig => ig, _ => new SourceGeneratorAdaptor(g, sourceExtension) })); } internal abstract CommonMessageProvider MessageProvider { get; } internal abstract GeneratorDriver FromState(GeneratorDriverState state); internal abstract SyntaxTree ParseGeneratedSourceText(GeneratedSourceText input, string fileName, CancellationToken cancellationToken); internal abstract string SourceExtension { get; } } }
// Licensed to the .NET Foundation under one or more 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; using System.Globalization; using System.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Responsible for orchestrating a source generation pass /// </summary> /// <remarks> /// GeneratorDriver is an immutable class that can be manipulated by returning a mutated copy of itself. /// In the compiler we only ever create a single instance and ignore the mutated copy. The IDE may perform /// multiple edits, or generation passes of the same driver, re-using the state as needed. /// </remarks> public abstract class GeneratorDriver { internal readonly GeneratorDriverState _state; internal GeneratorDriver(GeneratorDriverState state) { Debug.Assert(state.Generators.GroupBy(s => s.GetGeneratorType()).Count() == state.Generators.Length); // ensure we don't have duplicate generator types _state = state; } internal GeneratorDriver(ParseOptions parseOptions, ImmutableArray<ISourceGenerator> generators, AnalyzerConfigOptionsProvider optionsProvider, ImmutableArray<AdditionalText> additionalTexts, GeneratorDriverOptions driverOptions) { (var filteredGenerators, var incrementalGenerators) = GetIncrementalGenerators(generators, SourceExtension); _state = new GeneratorDriverState(parseOptions, optionsProvider, filteredGenerators, incrementalGenerators, additionalTexts, ImmutableArray.Create(new GeneratorState[filteredGenerators.Length]), DriverStateTable.Empty, driverOptions.DisabledOutputs); } public GeneratorDriver RunGenerators(Compilation compilation, CancellationToken cancellationToken = default) { var state = RunGeneratorsCore(compilation, diagnosticsBag: null, cancellationToken); //don't directly collect diagnostics on this path return FromState(state); } public GeneratorDriver RunGeneratorsAndUpdateCompilation(Compilation compilation, out Compilation outputCompilation, out ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken = default) { var diagnosticsBag = DiagnosticBag.GetInstance(); var state = RunGeneratorsCore(compilation, diagnosticsBag, cancellationToken); // build the output compilation diagnostics = diagnosticsBag.ToReadOnlyAndFree(); ArrayBuilder<SyntaxTree> trees = ArrayBuilder<SyntaxTree>.GetInstance(); foreach (var generatorState in state.GeneratorStates) { trees.AddRange(generatorState.PostInitTrees.Select(t => t.Tree)); trees.AddRange(generatorState.GeneratedTrees.Select(t => t.Tree)); } outputCompilation = compilation.AddSyntaxTrees(trees); trees.Free(); return FromState(state); } public GeneratorDriver AddGenerators(ImmutableArray<ISourceGenerator> generators) { (var filteredGenerators, var incrementalGenerators) = GetIncrementalGenerators(generators, SourceExtension); var newState = _state.With(sourceGenerators: _state.Generators.AddRange(filteredGenerators), incrementalGenerators: _state.IncrementalGenerators.AddRange(incrementalGenerators), generatorStates: _state.GeneratorStates.AddRange(new GeneratorState[filteredGenerators.Length])); return FromState(newState); } public GeneratorDriver RemoveGenerators(ImmutableArray<ISourceGenerator> generators) { var newGenerators = _state.Generators; var newStates = _state.GeneratorStates; var newIncrementalGenerators = _state.IncrementalGenerators; for (int i = 0; i < newGenerators.Length; i++) { if (generators.Contains(newGenerators[i])) { newGenerators = newGenerators.RemoveAt(i); newStates = newStates.RemoveAt(i); newIncrementalGenerators = newIncrementalGenerators.RemoveAt(i); i--; } } return FromState(_state.With(sourceGenerators: newGenerators, incrementalGenerators: newIncrementalGenerators, generatorStates: newStates)); } public GeneratorDriver AddAdditionalTexts(ImmutableArray<AdditionalText> additionalTexts) { var newState = _state.With(additionalTexts: _state.AdditionalTexts.AddRange(additionalTexts)); return FromState(newState); } public GeneratorDriver RemoveAdditionalTexts(ImmutableArray<AdditionalText> additionalTexts) { var newState = _state.With(additionalTexts: _state.AdditionalTexts.RemoveRange(additionalTexts)); return FromState(newState); } public GeneratorDriver ReplaceAdditionalText(AdditionalText oldText, AdditionalText newText) { if (oldText is null) { throw new ArgumentNullException(nameof(oldText)); } if (newText is null) { throw new ArgumentNullException(nameof(newText)); } var newState = _state.With(additionalTexts: _state.AdditionalTexts.Replace(oldText, newText)); return FromState(newState); } public GeneratorDriver WithUpdatedParseOptions(ParseOptions newOptions) => newOptions is object ? FromState(_state.With(parseOptions: newOptions)) : throw new ArgumentNullException(nameof(newOptions)); public GeneratorDriver WithUpdatedAnalyzerConfigOptions(AnalyzerConfigOptionsProvider newOptions) => newOptions is object ? FromState(_state.With(optionsProvider: newOptions)) : throw new ArgumentNullException(nameof(newOptions)); public GeneratorDriverRunResult GetRunResult() { var results = _state.Generators.ZipAsArray( _state.GeneratorStates, (generator, generatorState) => new GeneratorRunResult(generator, diagnostics: generatorState.Diagnostics, exception: generatorState.Exception, generatedSources: getGeneratorSources(generatorState))); return new GeneratorDriverRunResult(results); static ImmutableArray<GeneratedSourceResult> getGeneratorSources(GeneratorState generatorState) { ArrayBuilder<GeneratedSourceResult> sources = ArrayBuilder<GeneratedSourceResult>.GetInstance(generatorState.PostInitTrees.Length + generatorState.GeneratedTrees.Length); foreach (var tree in generatorState.PostInitTrees) { sources.Add(new GeneratedSourceResult(tree.Tree, tree.Text, tree.HintName)); } foreach (var tree in generatorState.GeneratedTrees) { sources.Add(new GeneratedSourceResult(tree.Tree, tree.Text, tree.HintName)); } return sources.ToImmutableAndFree(); } } internal GeneratorDriverState RunGeneratorsCore(Compilation compilation, DiagnosticBag? diagnosticsBag, CancellationToken cancellationToken = default) { // with no generators, there is no work to do if (_state.Generators.IsEmpty) { return _state.With(stateTable: DriverStateTable.Empty); } // run the actual generation var state = _state; var stateBuilder = ArrayBuilder<GeneratorState>.GetInstance(state.Generators.Length); var constantSourcesBuilder = ArrayBuilder<SyntaxTree>.GetInstance(); var syntaxInputNodes = ArrayBuilder<ISyntaxInputNode>.GetInstance(); for (int i = 0; i < state.IncrementalGenerators.Length; i++) { var generator = state.IncrementalGenerators[i]; var generatorState = state.GeneratorStates[i]; var sourceGenerator = state.Generators[i]; // initialize the generator if needed if (!generatorState.Initialized) { var outputBuilder = ArrayBuilder<IIncrementalGeneratorOutputNode>.GetInstance(); var inputBuilder = ArrayBuilder<ISyntaxInputNode>.GetInstance(); var postInitSources = ImmutableArray<GeneratedSyntaxTree>.Empty; var pipelineContext = new IncrementalGeneratorInitializationContext(inputBuilder, outputBuilder, SourceExtension); Exception? ex = null; try { generator.Initialize(pipelineContext); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { ex = e; } var outputNodes = outputBuilder.ToImmutableAndFree(); var inputNodes = inputBuilder.ToImmutableAndFree(); // run post init if (ex is null) { try { IncrementalExecutionContext context = UpdateOutputs(outputNodes, IncrementalGeneratorOutputKind.PostInit, cancellationToken); postInitSources = ParseAdditionalSources(sourceGenerator, context.ToImmutableAndFree().sources, cancellationToken); } catch (UserFunctionException e) { ex = e.InnerException; } } generatorState = ex is null ? new GeneratorState(generatorState.Info, postInitSources, inputNodes, outputNodes) : SetGeneratorException(MessageProvider, generatorState, sourceGenerator, ex, diagnosticsBag, isInit: true); } // if the pipeline registered any syntax input nodes, record them if (!generatorState.InputNodes.IsEmpty) { syntaxInputNodes.AddRange(generatorState.InputNodes); } // record any constant sources if (generatorState.Exception is null && generatorState.PostInitTrees.Length > 0) { constantSourcesBuilder.AddRange(generatorState.PostInitTrees.Select(t => t.Tree)); } stateBuilder.Add(generatorState); } // update the compilation with any constant sources if (constantSourcesBuilder.Count > 0) { compilation = compilation.AddSyntaxTrees(constantSourcesBuilder); } constantSourcesBuilder.Free(); var driverStateBuilder = new DriverStateTable.Builder(compilation, _state, syntaxInputNodes.ToImmutableAndFree(), cancellationToken); for (int i = 0; i < state.IncrementalGenerators.Length; i++) { var generatorState = stateBuilder[i]; if (generatorState.Exception is object) { continue; } try { var context = UpdateOutputs(generatorState.OutputNodes, IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.Implementation, cancellationToken, driverStateBuilder); (var sources, var generatorDiagnostics) = context.ToImmutableAndFree(); generatorDiagnostics = FilterDiagnostics(compilation, generatorDiagnostics, driverDiagnostics: diagnosticsBag, cancellationToken); stateBuilder[i] = new GeneratorState(generatorState.Info, generatorState.PostInitTrees, generatorState.InputNodes, generatorState.OutputNodes, ParseAdditionalSources(state.Generators[i], sources, cancellationToken), generatorDiagnostics); } catch (UserFunctionException ufe) { stateBuilder[i] = SetGeneratorException(MessageProvider, stateBuilder[i], state.Generators[i], ufe.InnerException, diagnosticsBag); } } state = state.With(stateTable: driverStateBuilder.ToImmutable(), generatorStates: stateBuilder.ToImmutableAndFree()); return state; } private IncrementalExecutionContext UpdateOutputs(ImmutableArray<IIncrementalGeneratorOutputNode> outputNodes, IncrementalGeneratorOutputKind outputKind, CancellationToken cancellationToken, DriverStateTable.Builder? driverStateBuilder = null) { Debug.Assert(outputKind != IncrementalGeneratorOutputKind.None); IncrementalExecutionContext context = new IncrementalExecutionContext(driverStateBuilder, new AdditionalSourcesCollection(SourceExtension)); foreach (var outputNode in outputNodes) { // if we're looking for this output kind, and it has not been explicitly disabled if (outputKind.HasFlag(outputNode.Kind) && !_state.DisabledOutputs.HasFlag(outputNode.Kind)) { outputNode.AppendOutputs(context, cancellationToken); } } return context; } private ImmutableArray<GeneratedSyntaxTree> ParseAdditionalSources(ISourceGenerator generator, ImmutableArray<GeneratedSourceText> generatedSources, CancellationToken cancellationToken) { var trees = ArrayBuilder<GeneratedSyntaxTree>.GetInstance(generatedSources.Length); var type = generator.GetGeneratorType(); var prefix = GetFilePathPrefixForGenerator(generator); foreach (var source in generatedSources) { var tree = ParseGeneratedSourceText(source, Path.Combine(prefix, source.HintName), cancellationToken); trees.Add(new GeneratedSyntaxTree(source.HintName, source.Text, tree)); } return trees.ToImmutableAndFree(); } private static GeneratorState SetGeneratorException(CommonMessageProvider provider, GeneratorState generatorState, ISourceGenerator generator, Exception e, DiagnosticBag? diagnosticBag, bool isInit = false) { var errorCode = isInit ? provider.WRN_GeneratorFailedDuringInitialization : provider.WRN_GeneratorFailedDuringGeneration; // ISSUE: Diagnostics don't currently allow descriptions with arguments, so we have to manually create the diagnostic description // ISSUE: Exceptions also don't support IFormattable, so will always be in the current UI Culture. // ISSUE: See https://github.com/dotnet/roslyn/issues/46939 var description = string.Format(provider.GetDescription(errorCode).ToString(CultureInfo.CurrentUICulture), e); var descriptor = new DiagnosticDescriptor( provider.GetIdForErrorCode(errorCode), provider.GetTitle(errorCode), provider.GetMessageFormat(errorCode), description: description, category: "Compiler", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, customTags: WellKnownDiagnosticTags.AnalyzerException); var diagnostic = Diagnostic.Create(descriptor, Location.None, generator.GetGeneratorType().Name, e.GetType().Name, e.Message); diagnosticBag?.Add(diagnostic); return new GeneratorState(generatorState.Info, e, diagnostic); } private static ImmutableArray<Diagnostic> FilterDiagnostics(Compilation compilation, ImmutableArray<Diagnostic> generatorDiagnostics, DiagnosticBag? driverDiagnostics, CancellationToken cancellationToken) { ArrayBuilder<Diagnostic> filteredDiagnostics = ArrayBuilder<Diagnostic>.GetInstance(); foreach (var diag in generatorDiagnostics) { var filtered = compilation.Options.FilterDiagnostic(diag, cancellationToken); if (filtered is object) { filteredDiagnostics.Add(filtered); driverDiagnostics?.Add(filtered); } } return filteredDiagnostics.ToImmutableAndFree(); } internal static string GetFilePathPrefixForGenerator(ISourceGenerator generator) { var type = generator.GetGeneratorType(); return Path.Combine(type.Assembly.GetName().Name ?? string.Empty, type.FullName!); } private static (ImmutableArray<ISourceGenerator>, ImmutableArray<IIncrementalGenerator>) GetIncrementalGenerators(ImmutableArray<ISourceGenerator> generators, string sourceExtension) { return (generators, generators.SelectAsArray(g => g switch { IncrementalGeneratorWrapper igw => igw.Generator, IIncrementalGenerator ig => ig, _ => new SourceGeneratorAdaptor(g, sourceExtension) })); } internal abstract CommonMessageProvider MessageProvider { get; } internal abstract GeneratorDriver FromState(GeneratorDriverState state); internal abstract SyntaxTree ParseGeneratedSourceText(GeneratedSourceText input, string fileName, CancellationToken cancellationToken); internal abstract string SourceExtension { get; } } }
1
dotnet/roslyn
56,095
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-02T00:01:28Z"
"2021-09-02T01:47:21Z"
212ca8da034e484813ea99027c29cc3f6405fe1f
fe389d485fb73f8186b32636bfc747a39a70b028
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/Core/Portable/SourceGeneration/IncrementalContexts.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.Text; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Context passed to an incremental generator when <see cref="IIncrementalGenerator.Initialize(IncrementalGeneratorInitializationContext)"/> is called /// </summary> public readonly struct IncrementalGeneratorInitializationContext { private readonly ArrayBuilder<ISyntaxInputNode> _syntaxInputBuilder; private readonly ArrayBuilder<IIncrementalGeneratorOutputNode> _outputNodes; private readonly string _sourceExtension; internal IncrementalGeneratorInitializationContext(ArrayBuilder<ISyntaxInputNode> syntaxInputBuilder, ArrayBuilder<IIncrementalGeneratorOutputNode> outputNodes, string sourceExtension) { _syntaxInputBuilder = syntaxInputBuilder; _outputNodes = outputNodes; _sourceExtension = sourceExtension; } public SyntaxValueProvider SyntaxProvider => new SyntaxValueProvider(_syntaxInputBuilder, RegisterOutput); public IncrementalValueProvider<Compilation> CompilationProvider => new IncrementalValueProvider<Compilation>(SharedInputNodes.Compilation.WithRegisterOutput(RegisterOutput)); public IncrementalValueProvider<ParseOptions> ParseOptionsProvider => new IncrementalValueProvider<ParseOptions>(SharedInputNodes.ParseOptions.WithRegisterOutput(RegisterOutput)); public IncrementalValuesProvider<AdditionalText> AdditionalTextsProvider => new IncrementalValuesProvider<AdditionalText>(SharedInputNodes.AdditionalTexts.WithRegisterOutput(RegisterOutput)); public IncrementalValueProvider<AnalyzerConfigOptionsProvider> AnalyzerConfigOptionsProvider => new IncrementalValueProvider<AnalyzerConfigOptionsProvider>(SharedInputNodes.AnalyzerConfigOptions.WithRegisterOutput(RegisterOutput)); public IncrementalValueProvider<MetadataReference> MetadataReferencesProvider => new IncrementalValueProvider<MetadataReference>(SharedInputNodes.MetadataReferences.WithRegisterOutput(RegisterOutput)); public void RegisterSourceOutput<TSource>(IncrementalValueProvider<TSource> source, Action<SourceProductionContext, TSource> action) => RegisterSourceOutput(source.Node, action, IncrementalGeneratorOutputKind.Source, _sourceExtension); public void RegisterSourceOutput<TSource>(IncrementalValuesProvider<TSource> source, Action<SourceProductionContext, TSource> action) => RegisterSourceOutput(source.Node, action, IncrementalGeneratorOutputKind.Source, _sourceExtension); public void RegisterImplementationSourceOutput<TSource>(IncrementalValueProvider<TSource> source, Action<SourceProductionContext, TSource> action) => RegisterSourceOutput(source.Node, action, IncrementalGeneratorOutputKind.Implementation, _sourceExtension); public void RegisterImplementationSourceOutput<TSource>(IncrementalValuesProvider<TSource> source, Action<SourceProductionContext, TSource> action) => RegisterSourceOutput(source.Node, action, IncrementalGeneratorOutputKind.Implementation, _sourceExtension); public void RegisterPostInitializationOutput(Action<IncrementalGeneratorPostInitializationContext> callback) => _outputNodes.Add(new PostInitOutputNode(callback.WrapUserAction())); private void RegisterOutput(IIncrementalGeneratorOutputNode outputNode) { if (!_outputNodes.Contains(outputNode)) { _outputNodes.Add(outputNode); } } private static void RegisterSourceOutput<TSource>(IIncrementalGeneratorNode<TSource> node, Action<SourceProductionContext, TSource> action, IncrementalGeneratorOutputKind kind, string sourceExt) { node.RegisterOutput(new SourceOutputNode<TSource>(node, action.WrapUserAction(), kind, sourceExt)); } } /// <summary> /// Context passed to an incremental generator when it has registered an output via <see cref="IncrementalGeneratorInitializationContext.RegisterPostInitializationOutput(Action{IncrementalGeneratorPostInitializationContext})"/> /// </summary> public readonly struct IncrementalGeneratorPostInitializationContext { internal readonly AdditionalSourcesCollection AdditionalSources; internal IncrementalGeneratorPostInitializationContext(AdditionalSourcesCollection additionalSources, CancellationToken cancellationToken) { AdditionalSources = additionalSources; CancellationToken = cancellationToken; } /// <summary> /// A <see cref="System.Threading.CancellationToken"/> that can be checked to see if the PostInitialization should be cancelled. /// </summary> public CancellationToken CancellationToken { get; } /// <summary> /// Adds source code in the form of a <see cref="string"/> to the compilation that will be available during subsequent phases /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="source">The source code to add to the compilation</param> public void AddSource(string hintName, string source) => AddSource(hintName, SourceText.From(source, Encoding.UTF8)); /// <summary> /// Adds a <see cref="SourceText"/> to the compilation that will be available during subsequent phases /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="sourceText">The <see cref="SourceText"/> to add to the compilation</param> public void AddSource(string hintName, SourceText sourceText) => AdditionalSources.Add(hintName, sourceText); } /// <summary> /// Context passed to an incremental generator when it has registered an output via <see cref="IncrementalGeneratorInitializationContext.RegisterSourceOutput{TSource}(IncrementalValueProvider{TSource}, Action{SourceProductionContext, TSource})"/> /// </summary> public readonly struct SourceProductionContext { internal readonly AdditionalSourcesCollection Sources; internal readonly DiagnosticBag Diagnostics; internal SourceProductionContext(AdditionalSourcesCollection sources, DiagnosticBag diagnostics, CancellationToken cancellationToken) { CancellationToken = cancellationToken; Sources = sources; Diagnostics = diagnostics; } public CancellationToken CancellationToken { get; } /// <summary> /// Adds source code in the form of a <see cref="string"/> to the compilation. /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="source">The source code to add to the compilation</param> public void AddSource(string hintName, string source) => AddSource(hintName, SourceText.From(source, Encoding.UTF8)); /// <summary> /// Adds a <see cref="SourceText"/> to the compilation /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="sourceText">The <see cref="SourceText"/> to add to the compilation</param> public void AddSource(string hintName, SourceText sourceText) => Sources.Add(hintName, sourceText); /// <summary> /// Adds a <see cref="Diagnostic"/> to the users compilation /// </summary> /// <param name="diagnostic">The diagnostic that should be added to the compilation</param> /// <remarks> /// The severity of the diagnostic may cause the compilation to fail, depending on the <see cref="Compilation"/> settings. /// </remarks> public void ReportDiagnostic(Diagnostic diagnostic) => Diagnostics.Add(diagnostic); } // https://github.com/dotnet/roslyn/issues/53608 right now we only support generating source + diagnostics, but actively want to support generation of other things internal readonly struct IncrementalExecutionContext { internal readonly DiagnosticBag Diagnostics; internal readonly AdditionalSourcesCollection Sources; internal readonly DriverStateTable.Builder? TableBuilder; public IncrementalExecutionContext(DriverStateTable.Builder? tableBuilder, AdditionalSourcesCollection sources) { TableBuilder = tableBuilder; Sources = sources; Diagnostics = DiagnosticBag.GetInstance(); } internal (ImmutableArray<GeneratedSourceText> sources, ImmutableArray<Diagnostic> diagnostics) ToImmutableAndFree() => (Sources.ToImmutableAndFree(), Diagnostics.ToReadOnlyAndFree()); internal void Free() { Sources.Free(); Diagnostics.Free(); } } }
// Licensed to the .NET Foundation under one or more 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.Text; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Context passed to an incremental generator when <see cref="IIncrementalGenerator.Initialize(IncrementalGeneratorInitializationContext)"/> is called /// </summary> public readonly struct IncrementalGeneratorInitializationContext { private readonly ArrayBuilder<ISyntaxInputNode> _syntaxInputBuilder; private readonly ArrayBuilder<IIncrementalGeneratorOutputNode> _outputNodes; private readonly string _sourceExtension; internal IncrementalGeneratorInitializationContext(ArrayBuilder<ISyntaxInputNode> syntaxInputBuilder, ArrayBuilder<IIncrementalGeneratorOutputNode> outputNodes, string sourceExtension) { _syntaxInputBuilder = syntaxInputBuilder; _outputNodes = outputNodes; _sourceExtension = sourceExtension; } public SyntaxValueProvider SyntaxProvider => new SyntaxValueProvider(_syntaxInputBuilder, RegisterOutput); public IncrementalValueProvider<Compilation> CompilationProvider => new IncrementalValueProvider<Compilation>(SharedInputNodes.Compilation.WithRegisterOutput(RegisterOutput)); public IncrementalValueProvider<ParseOptions> ParseOptionsProvider => new IncrementalValueProvider<ParseOptions>(SharedInputNodes.ParseOptions.WithRegisterOutput(RegisterOutput)); public IncrementalValuesProvider<AdditionalText> AdditionalTextsProvider => new IncrementalValuesProvider<AdditionalText>(SharedInputNodes.AdditionalTexts.WithRegisterOutput(RegisterOutput)); public IncrementalValueProvider<AnalyzerConfigOptionsProvider> AnalyzerConfigOptionsProvider => new IncrementalValueProvider<AnalyzerConfigOptionsProvider>(SharedInputNodes.AnalyzerConfigOptions.WithRegisterOutput(RegisterOutput)); public IncrementalValueProvider<MetadataReference> MetadataReferencesProvider => new IncrementalValueProvider<MetadataReference>(SharedInputNodes.MetadataReferences.WithRegisterOutput(RegisterOutput)); public void RegisterSourceOutput<TSource>(IncrementalValueProvider<TSource> source, Action<SourceProductionContext, TSource> action) => RegisterSourceOutput(source.Node, action, IncrementalGeneratorOutputKind.Source, _sourceExtension); public void RegisterSourceOutput<TSource>(IncrementalValuesProvider<TSource> source, Action<SourceProductionContext, TSource> action) => RegisterSourceOutput(source.Node, action, IncrementalGeneratorOutputKind.Source, _sourceExtension); public void RegisterImplementationSourceOutput<TSource>(IncrementalValueProvider<TSource> source, Action<SourceProductionContext, TSource> action) => RegisterSourceOutput(source.Node, action, IncrementalGeneratorOutputKind.Implementation, _sourceExtension); public void RegisterImplementationSourceOutput<TSource>(IncrementalValuesProvider<TSource> source, Action<SourceProductionContext, TSource> action) => RegisterSourceOutput(source.Node, action, IncrementalGeneratorOutputKind.Implementation, _sourceExtension); public void RegisterPostInitializationOutput(Action<IncrementalGeneratorPostInitializationContext> callback) => _outputNodes.Add(new PostInitOutputNode(callback.WrapUserAction())); private void RegisterOutput(IIncrementalGeneratorOutputNode outputNode) { if (!_outputNodes.Contains(outputNode)) { _outputNodes.Add(outputNode); } } private static void RegisterSourceOutput<TSource>(IIncrementalGeneratorNode<TSource> node, Action<SourceProductionContext, TSource> action, IncrementalGeneratorOutputKind kind, string sourceExt) { node.RegisterOutput(new SourceOutputNode<TSource>(node, action.WrapUserAction(), kind, sourceExt)); } } /// <summary> /// Context passed to an incremental generator when it has registered an output via <see cref="IncrementalGeneratorInitializationContext.RegisterPostInitializationOutput(Action{IncrementalGeneratorPostInitializationContext})"/> /// </summary> public readonly struct IncrementalGeneratorPostInitializationContext { internal readonly AdditionalSourcesCollection AdditionalSources; internal IncrementalGeneratorPostInitializationContext(AdditionalSourcesCollection additionalSources, CancellationToken cancellationToken) { AdditionalSources = additionalSources; CancellationToken = cancellationToken; } /// <summary> /// A <see cref="System.Threading.CancellationToken"/> that can be checked to see if the PostInitialization should be cancelled. /// </summary> public CancellationToken CancellationToken { get; } /// <summary> /// Adds source code in the form of a <see cref="string"/> to the compilation that will be available during subsequent phases /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="source">The source code to add to the compilation</param> public void AddSource(string hintName, string source) => AddSource(hintName, SourceText.From(source, Encoding.UTF8)); /// <summary> /// Adds a <see cref="SourceText"/> to the compilation that will be available during subsequent phases /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="sourceText">The <see cref="SourceText"/> to add to the compilation</param> public void AddSource(string hintName, SourceText sourceText) => AdditionalSources.Add(hintName, sourceText); } /// <summary> /// Context passed to an incremental generator when it has registered an output via <see cref="IncrementalGeneratorInitializationContext.RegisterSourceOutput{TSource}(IncrementalValueProvider{TSource}, Action{SourceProductionContext, TSource})"/> /// </summary> public readonly struct SourceProductionContext { internal readonly AdditionalSourcesCollection Sources; internal readonly DiagnosticBag Diagnostics; internal SourceProductionContext(AdditionalSourcesCollection sources, DiagnosticBag diagnostics, CancellationToken cancellationToken) { CancellationToken = cancellationToken; Sources = sources; Diagnostics = diagnostics; } public CancellationToken CancellationToken { get; } /// <summary> /// Adds source code in the form of a <see cref="string"/> to the compilation. /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="source">The source code to add to the compilation</param> public void AddSource(string hintName, string source) => AddSource(hintName, SourceText.From(source, Encoding.UTF8)); /// <summary> /// Adds a <see cref="SourceText"/> to the compilation /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="sourceText">The <see cref="SourceText"/> to add to the compilation</param> public void AddSource(string hintName, SourceText sourceText) => Sources.Add(hintName, sourceText); /// <summary> /// Adds a <see cref="Diagnostic"/> to the users compilation /// </summary> /// <param name="diagnostic">The diagnostic that should be added to the compilation</param> /// <remarks> /// The severity of the diagnostic may cause the compilation to fail, depending on the <see cref="Compilation"/> settings. /// </remarks> public void ReportDiagnostic(Diagnostic diagnostic) => Diagnostics.Add(diagnostic); } // https://github.com/dotnet/roslyn/issues/53608 right now we only support generating source + diagnostics, but actively want to support generation of other things internal readonly struct IncrementalExecutionContext { internal readonly DiagnosticBag Diagnostics; internal readonly AdditionalSourcesCollection Sources; internal readonly DriverStateTable.Builder? TableBuilder; public IncrementalExecutionContext(DriverStateTable.Builder? tableBuilder, AdditionalSourcesCollection sources) { TableBuilder = tableBuilder; Sources = sources; Diagnostics = DiagnosticBag.GetInstance(); } internal (ImmutableArray<GeneratedSourceText> sources, ImmutableArray<Diagnostic> diagnostics) ToImmutableAndFree() => (Sources.ToImmutableAndFree(), Diagnostics.ToReadOnlyAndFree()); internal void Free() { Sources.Free(); Diagnostics.Free(); } } }
1
dotnet/roslyn
56,095
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-02T00:01:28Z"
"2021-09-02T01:47:21Z"
212ca8da034e484813ea99027c29cc3f6405fe1f
fe389d485fb73f8186b32636bfc747a39a70b028
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/Core/Portable/SourceGeneration/Nodes/SourceOutputNode.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.Threading; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using TOutput = System.ValueTuple<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.GeneratedSourceText>, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostic>>; namespace Microsoft.CodeAnalysis { internal sealed class SourceOutputNode<TInput> : IIncrementalGeneratorOutputNode, IIncrementalGeneratorNode<TOutput> { private readonly IIncrementalGeneratorNode<TInput> _source; private readonly Action<SourceProductionContext, TInput> _action; private readonly IncrementalGeneratorOutputKind _outputKind; private readonly string _sourceExtension; public SourceOutputNode(IIncrementalGeneratorNode<TInput> source, Action<SourceProductionContext, TInput> action, IncrementalGeneratorOutputKind outputKind, string sourceExtension) { _source = source; _action = action; Debug.Assert(outputKind == IncrementalGeneratorOutputKind.Source || outputKind == IncrementalGeneratorOutputKind.Implementation); _outputKind = outputKind; _sourceExtension = sourceExtension; } public IncrementalGeneratorOutputKind Kind => _outputKind; public NodeStateTable<TOutput> UpdateStateTable(DriverStateTable.Builder graphState, NodeStateTable<TOutput> previousTable, CancellationToken cancellationToken) { var sourceTable = graphState.GetLatestStateTableForNode(_source); if (sourceTable.IsCached) { return previousTable; } var nodeTable = previousTable.ToBuilder(); foreach (var entry in sourceTable) { if (entry.state == EntryState.Removed) { nodeTable.RemoveEntries(); } else if (entry.state != EntryState.Cached || !nodeTable.TryUseCachedEntries()) { // we don't currently handle modified any differently than added at the output // we just run the action and mark the new source as added. In theory we could compare // the diagnostics and sources produced and compare them, to see if they are any different // than before. var sourcesBuilder = new AdditionalSourcesCollection(_sourceExtension); var diagnostics = DiagnosticBag.GetInstance(); SourceProductionContext context = new SourceProductionContext(sourcesBuilder, diagnostics, cancellationToken); try { _action(context, entry.item); nodeTable.AddEntry((sourcesBuilder.ToImmutable(), diagnostics.ToReadOnly()), EntryState.Added); } finally { sourcesBuilder.Free(); diagnostics.Free(); } } } return nodeTable.ToImmutableAndFree(); } IIncrementalGeneratorNode<TOutput> IIncrementalGeneratorNode<TOutput>.WithComparer(IEqualityComparer<TOutput> comparer) => throw ExceptionUtilities.Unreachable; void IIncrementalGeneratorNode<TOutput>.RegisterOutput(IIncrementalGeneratorOutputNode output) => throw ExceptionUtilities.Unreachable; public void AppendOutputs(IncrementalExecutionContext context, CancellationToken cancellationToken) { // get our own state table Debug.Assert(context.TableBuilder is object); var table = context.TableBuilder.GetLatestStateTableForNode(this); // add each non-removed entry to the context foreach (var ((sources, diagnostics), state) in table) { if (state != EntryState.Removed) { foreach (var text in sources) { try { context.Sources.Add(text.HintName, text.Text); } catch (ArgumentException e) { throw new UserFunctionException(e); } } context.Diagnostics.AddRange(diagnostics); } } } } }
// Licensed to the .NET Foundation under one or more 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.Threading; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using TOutput = System.ValueTuple<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.GeneratedSourceText>, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostic>>; namespace Microsoft.CodeAnalysis { internal sealed class SourceOutputNode<TInput> : IIncrementalGeneratorOutputNode, IIncrementalGeneratorNode<TOutput> { private readonly IIncrementalGeneratorNode<TInput> _source; private readonly Action<SourceProductionContext, TInput> _action; private readonly IncrementalGeneratorOutputKind _outputKind; private readonly string _sourceExtension; public SourceOutputNode(IIncrementalGeneratorNode<TInput> source, Action<SourceProductionContext, TInput> action, IncrementalGeneratorOutputKind outputKind, string sourceExtension) { _source = source; _action = action; Debug.Assert(outputKind == IncrementalGeneratorOutputKind.Source || outputKind == IncrementalGeneratorOutputKind.Implementation); _outputKind = outputKind; _sourceExtension = sourceExtension; } public IncrementalGeneratorOutputKind Kind => _outputKind; public NodeStateTable<TOutput> UpdateStateTable(DriverStateTable.Builder graphState, NodeStateTable<TOutput> previousTable, CancellationToken cancellationToken) { var sourceTable = graphState.GetLatestStateTableForNode(_source); if (sourceTable.IsCached) { return previousTable; } var nodeTable = previousTable.ToBuilder(); foreach (var entry in sourceTable) { if (entry.state == EntryState.Removed) { nodeTable.RemoveEntries(); } else if (entry.state != EntryState.Cached || !nodeTable.TryUseCachedEntries()) { // we don't currently handle modified any differently than added at the output // we just run the action and mark the new source as added. In theory we could compare // the diagnostics and sources produced and compare them, to see if they are any different // than before. var sourcesBuilder = new AdditionalSourcesCollection(_sourceExtension); var diagnostics = DiagnosticBag.GetInstance(); SourceProductionContext context = new SourceProductionContext(sourcesBuilder, diagnostics, cancellationToken); try { _action(context, entry.item); nodeTable.AddEntry((sourcesBuilder.ToImmutable(), diagnostics.ToReadOnly()), EntryState.Added); } finally { sourcesBuilder.Free(); diagnostics.Free(); } } } return nodeTable.ToImmutableAndFree(); } IIncrementalGeneratorNode<TOutput> IIncrementalGeneratorNode<TOutput>.WithComparer(IEqualityComparer<TOutput> comparer) => throw ExceptionUtilities.Unreachable; void IIncrementalGeneratorNode<TOutput>.RegisterOutput(IIncrementalGeneratorOutputNode output) => throw ExceptionUtilities.Unreachable; public void AppendOutputs(IncrementalExecutionContext context, CancellationToken cancellationToken) { // get our own state table Debug.Assert(context.TableBuilder is object); var table = context.TableBuilder.GetLatestStateTableForNode(this); // add each non-removed entry to the context foreach (var ((sources, diagnostics), state) in table) { if (state != EntryState.Removed) { foreach (var text in sources) { try { context.Sources.Add(text.HintName, text.Text); } catch (ArgumentException e) { throw new UserFunctionException(e); } } context.Diagnostics.AddRange(diagnostics); } } } } }
1
dotnet/roslyn
56,095
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-02T00:01:28Z"
"2021-09-02T01:47:21Z"
212ca8da034e484813ea99027c29cc3f6405fe1f
fe389d485fb73f8186b32636bfc747a39a70b028
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/VisualBasic/Portable/SourceGeneration/VisualBasicGeneratorDriver.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.ComponentModel Imports System.Threading Imports Microsoft.CodeAnalysis.Diagnostics Namespace Microsoft.CodeAnalysis.VisualBasic Public Class VisualBasicGeneratorDriver Inherits GeneratorDriver Private Sub New(state As GeneratorDriverState) MyBase.New(state) End Sub Friend Sub New(parseOptions As VisualBasicParseOptions, generators As ImmutableArray(Of ISourceGenerator), optionsProvider As AnalyzerConfigOptionsProvider, additionalTexts As ImmutableArray(Of AdditionalText), driverOptions As GeneratorDriverOptions) MyBase.New(parseOptions, generators, optionsProvider, additionalTexts, driverOptions) End Sub Friend Overrides ReadOnly Property MessageProvider As CommonMessageProvider Get Return VisualBasic.MessageProvider.Instance End Get End Property Friend Overrides Function FromState(state As GeneratorDriverState) As GeneratorDriver Return New VisualBasicGeneratorDriver(state) End Function Friend Overrides Function ParseGeneratedSourceText(input As GeneratedSourceText, fileName As String, cancellationToken As CancellationToken) As SyntaxTree Return VisualBasicSyntaxTree.ParseTextLazy(input.Text, CType(_state.ParseOptions, VisualBasicParseOptions), fileName) End Function Public Shared Function Create(generators As ImmutableArray(Of ISourceGenerator), Optional additionalTexts As ImmutableArray(Of AdditionalText) = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional analyzerConfigOptionsProvider As AnalyzerConfigOptionsProvider = Nothing, Optional driverOptions As GeneratorDriverOptions = Nothing) As VisualBasicGeneratorDriver Return New VisualBasicGeneratorDriver(parseOptions, generators, If(analyzerConfigOptionsProvider, CompilerAnalyzerConfigOptionsProvider.Empty), additionalTexts.NullToEmpty(), driverOptions) End Function ' 3.11 BACK COMPAT OVERLOAD -- DO NOT TOUCH <EditorBrowsable(EditorBrowsableState.Never)> Public Shared Function Create(generators As ImmutableArray(Of ISourceGenerator), additionalTexts As ImmutableArray(Of AdditionalText), parseOptions As VisualBasicParseOptions, analyzerConfigOptionsProvider As AnalyzerConfigOptionsProvider) As VisualBasicGeneratorDriver Return Create(generators, additionalTexts, parseOptions, analyzerConfigOptionsProvider, driverOptions:=Nothing) End Function Friend Overrides ReadOnly Property SourceExtension As String Get Return ".vb" 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 System.Collections.Immutable Imports System.ComponentModel Imports System.Threading Imports Microsoft.CodeAnalysis.Diagnostics Namespace Microsoft.CodeAnalysis.VisualBasic Public Class VisualBasicGeneratorDriver Inherits GeneratorDriver Private Sub New(state As GeneratorDriverState) MyBase.New(state) End Sub Friend Sub New(parseOptions As VisualBasicParseOptions, generators As ImmutableArray(Of ISourceGenerator), optionsProvider As AnalyzerConfigOptionsProvider, additionalTexts As ImmutableArray(Of AdditionalText), driverOptions As GeneratorDriverOptions) MyBase.New(parseOptions, generators, optionsProvider, additionalTexts, driverOptions) End Sub Friend Overrides ReadOnly Property MessageProvider As CommonMessageProvider Get Return VisualBasic.MessageProvider.Instance End Get End Property Friend Overrides Function FromState(state As GeneratorDriverState) As GeneratorDriver Return New VisualBasicGeneratorDriver(state) End Function Friend Overrides Function ParseGeneratedSourceText(input As GeneratedSourceText, fileName As String, cancellationToken As CancellationToken) As SyntaxTree Return VisualBasicSyntaxTree.ParseTextLazy(input.Text, CType(_state.ParseOptions, VisualBasicParseOptions), fileName) End Function Public Shared Function Create(generators As ImmutableArray(Of ISourceGenerator), Optional additionalTexts As ImmutableArray(Of AdditionalText) = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional analyzerConfigOptionsProvider As AnalyzerConfigOptionsProvider = Nothing, Optional driverOptions As GeneratorDriverOptions = Nothing) As VisualBasicGeneratorDriver Return New VisualBasicGeneratorDriver(parseOptions, generators, If(analyzerConfigOptionsProvider, CompilerAnalyzerConfigOptionsProvider.Empty), additionalTexts.NullToEmpty(), driverOptions) End Function ' 3.11 BACK COMPAT OVERLOAD -- DO NOT TOUCH <EditorBrowsable(EditorBrowsableState.Never)> Public Shared Function Create(generators As ImmutableArray(Of ISourceGenerator), additionalTexts As ImmutableArray(Of AdditionalText), parseOptions As VisualBasicParseOptions, analyzerConfigOptionsProvider As AnalyzerConfigOptionsProvider) As VisualBasicGeneratorDriver Return Create(generators, additionalTexts, parseOptions, analyzerConfigOptionsProvider, driverOptions:=Nothing) End Function Friend Overrides ReadOnly Property SourceExtension As String Get Return ".vb" End Get End Property End Class End Namespace
1
dotnet/roslyn
56,095
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-02T00:01:28Z"
"2021-09-02T01:47:21Z"
212ca8da034e484813ea99027c29cc3f6405fe1f
fe389d485fb73f8186b32636bfc747a39a70b028
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Analyzers/CSharp/Tests/RemoveUnnecessaryParentheses/RemoveUnnecessaryExpressionParenthesesTests.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.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.RemoveUnnecessaryParentheses; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RemoveUnnecessaryParentheses { public partial class RemoveUnnecessaryExpressionParenthesesTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public RemoveUnnecessaryExpressionParenthesesTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpRemoveUnnecessaryExpressionParenthesesDiagnosticAnalyzer(), new CSharpRemoveUnnecessaryParenthesesCodeFixProvider()); private async Task TestAsync(string initial, string expected, bool offeredWhenRequireForClarityIsEnabled, int index = 0) { await TestInRegularAndScriptAsync(initial, expected, options: RemoveAllUnnecessaryParentheses, index: index); if (offeredWhenRequireForClarityIsEnabled) { await TestInRegularAndScriptAsync(initial, expected, options: RequireAllParenthesesForClarity, index: index); } else { await TestMissingAsync(initial, parameters: new TestParameters(options: RequireAllParenthesesForClarity)); } } internal override bool ShouldSkipMessageDescriptionVerification(DiagnosticDescriptor descriptor) => descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.Unnecessary) && descriptor.DefaultSeverity == DiagnosticSeverity.Hidden; private static DiagnosticDescription GetRemoveUnnecessaryParenthesesDiagnostic(string text, int line, int column) => TestHelpers.Diagnostic(IDEDiagnosticIds.RemoveUnnecessaryParenthesesDiagnosticId, text, startLocation: new LinePosition(line, column)); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestVariableInitializer_TestWithAllOptionsSetToIgnore() { await TestMissingAsync( @"class C { void M() { int x = $$(1); } }", new TestParameters(options: IgnoreAllParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] [WorkItem(29736, "https://github.com/dotnet/roslyn/issues/29736")] public async Task TestVariableInitializer_TestMissingParenthesis() { await TestMissingAsync( @"class C { void M() { int x = $$(1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestArithmeticRequiredForClarity1() { await TestMissingAsync( @"class C { void M() { int x = 1 + $$(2 * 3); } }", new TestParameters(options: RequireArithmeticBinaryParenthesesForClarity)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] [WorkItem(44629, "https://github.com/dotnet/roslyn/issues/44629")] public async Task TestStackAlloc() { await TestMissingAsync( @"class C { void M() { var span = $$(stackalloc byte[8]); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] [WorkItem(47365, "https://github.com/dotnet/roslyn/issues/47365")] public async Task TestDynamic() { await TestMissingAsync( @"class C { void M() { dynamic i = 1; dynamic s = ""s""; Console.WriteLine(s + $$(1 + i)); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestArithmeticRequiredForClarity2() { await TestInRegularAndScript1Async( @"class C { void M() { int x = a || $$(b && c); } }", @"class C { void M() { int x = a || b && c; } }", parameters: new TestParameters(options: RequireArithmeticBinaryParenthesesForClarity)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestLogicalRequiredForClarity1() { await TestMissingAsync( @"class C { void M() { int x = a || $$(b && c); } }", new TestParameters(options: RequireOtherBinaryParenthesesForClarity)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestLogicalRequiredForClarity2() { await TestInRegularAndScript1Async( @"class C { void M() { int x = a + $$(b * c); } }", @"class C { void M() { int x = a + b * c; } }", parameters: new TestParameters(options: RequireOtherBinaryParenthesesForClarity)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestArithmeticNotRequiredForClarityWhenPrecedenceStaysTheSame_Integral1() { await TestAsync( @"class C { void M() { int x = 1 + $$(2 + 3); } }", @"class C { void M() { int x = 1 + 2 + 3; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestArithmeticNotRequiredForClarityWhenPrecedenceStaysTheSame_Integral2() { await TestAsync( @"class C { void M() { int x = $$(1 + 2) + 3; } }", @"class C { void M() { int x = 1 + 2 + 3; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestArithmeticRequiredForCorrectnessWhenPrecedenceStaysTheSameIfFloatingPoint() { await TestMissingAsync( @"class C { void M() { int x = 1.0 + $$(2.0 + 3.0); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestArithmeticNotRequiredForClarityWhenPrecedenceStaysTheSame_Floating2() { await TestAsync( @"class C { void M() { int x = $$(1.0 + 2.0) + 3.0; } }", @"class C { void M() { int x = 1.0 + 2.0 + 3.0; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestLogicalNotRequiredForClarityWhenPrecedenceStaysTheSame1() { await TestAsync( @"class C { void M() { int x = a || $$(b || c); } }", @"class C { void M() { int x = a || b || c; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestLogicalNotRequiredForClarityWhenPrecedenceStaysTheSame2() { await TestAsync( @"class C { void M() { int x = $$(a || b) || c; } }", @"class C { void M() { int x = a || b || c; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestVariableInitializer_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { int x = $$(1); } }", @"class C { void M() { int x = 1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestReturnStatement_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { return $$(1 + 2); } }", @"class C { void M() { return 1 + 2; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestExpressionBody_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { int M() => $$(1 + 2); }", @"class C { int M() => 1 + 2; }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestCheckedExpression_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { int i = checked($$(1 + 2)); } }", @"class C { void M() { int i = checked(1 + 2); } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestAssignment_TestAvailableWithAlwaysRemove_And_TestNotAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { i = $$(1 + 2); } }", @"class C { void M() { i = 1 + 2; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestCompoundAssignment_TestAvailableWithAlwaysRemove_And_TestNotAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { i *= $$(1 + 2); } }", @"class C { void M() { i *= 1 + 2; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestPimaryAssignment_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { i = $$(s.Length); } }", @"class C { void M() { i = s.Length; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestNestedParenthesizedExpression_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { int i = ( $$(1 + 2) ); } }", @"class C { void M() { int i = ( 1 + 2 ); } }", offeredWhenRequireForClarityIsEnabled: true, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestIncrementExpression_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { int i = $$(x++); } }", @"class C { void M() { int i = x++; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestLambdaBody_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { Func<int> i = () => $$(1); } }", @"class C { void M() { Func<int> i = () => 1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestArrayElement_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { int[] i = new int[] { $$(1) }; } }", @"class C { void M() { int[] i = new int[] { 1 }; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestWhereClause_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { var q = from c in customer where $$(c.Age > 21) select c; } }", @"class C { void M() { var q = from c in customer where c.Age > 21 select c; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestCastExpression_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { int i = (int)$$(1); } }", @"class C { void M() { int i = (int)1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestMissingForConditionalAccess1() { await TestMissingAsync( @"class C { void M(string s) { var v = $$(s?.Length).ToString(); } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(37046, "https://github.com/dotnet/roslyn/issues/37046")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestMissingForConditionalAccess2() { await TestMissingAsync( @"class C { void M(string s) { var v = $$(s?.Length)?.ToString(); } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestForConditionalAccessNotInExpression() { await TestInRegularAndScriptAsync( @"class C { void M(string s) { var v = $$(s?.Length); } }", @"class C { void M(string s) { var v = s?.Length; } }", options: RemoveAllUnnecessaryParentheses); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestMissingForConditionalIndex() { await TestMissingAsync( @"class C { void M(string s) { var v = $$(s?[0]).ToString(); } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestBinaryInCastExpression() { await TestMissingAsync( @"class C { void M() { int i = (int)$$(1 + 2); } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestAroundCastExpression_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { int i = $$((int)1); } }", @"class C { void M() { int i = (int)1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestConditionalInInterpolation() { await TestMissingAsync( @"class C { void M() { var s = $""{ $$(a ? b : c) }""; } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestConditionalInInterpolation_FixAll_1() { await TestAsync( @"class C { void M() { var s1 = $""{ {|FixAllInDocument:(|}(a ? b : c)) }""; var s2 = $""{ ((a ? b : c)) }""; } }", @"class C { void M() { var s1 = $""{ (a ? b : c) }""; var s2 = $""{ (a ? b : c) }""; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestConditionalInInterpolation_FixAll_2() { await TestAsync( @"class C { void M() { var s1 = $""{ ({|FixAllInDocument:(|}a ? b : c)) }""; var s2 = $""{ ((a ? b : c)) }""; } }", @"class C { void M() { var s1 = $""{ (a ? b : c) }""; var s2 = $""{ (a ? b : c) }""; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestNonConditionalInInterpolation_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { var s = $""{ $$(true) }""; } }", @"class C { void M() { var s = $""{ true }""; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestBinaryExpression_TestAvailableWithAlwaysRemove_And_NotAvailableWhenRequiredForClarity_1() { await TestAsync( @"class C { void M() { var q = $$(a * b) + c; } }", @"class C { void M() { var q = a * b + c; } }", offeredWhenRequireForClarityIsEnabled: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestBinaryExpression_TestAvailableWithAlwaysRemove_And_NotAvailableWhenRequiredForClarity_2() { await TestAsync( @"class C { void M() { var q = c + $$(a * b); } }", @"class C { void M() { var q = c + a * b; } }", offeredWhenRequireForClarityIsEnabled: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestConditionalExpression_TestNotAvailableForComplexChildren1() { await TestMissingAsync( @"class C { void M() { var q = $$(a * b) ? (1 + 2) : (3 + 4); } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestConditionalExpression_TestNotAvailableForComplexChildren2() { await TestMissingAsync( @"class C { void M() { var q = (a * b) ? $$(1 + 2) : (3 + 4); } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestConditionalExpression_TestNotAvailableForComplexChildren3() { await TestMissingAsync( @"class C { void M() { var q = (a * b) ? (1 + 2) : $$(3 + 4); } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestConditionalExpression_TestAvailableForPrimaryChildren1() { await TestAsync( @"class C { void M() { var q = $$(a.X()) ? (1 + 2) : (3 + 4); } }", @"class C { void M() { var q = a.X() ? (1 + 2) : (3 + 4); } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestConditionalExpression_TestAvailableForPrimaryChildren2() { await TestAsync( @"class C { void M() { var q = (a.X()) ? $$(x.Length) : (3 + 4); } }", @"class C { void M() { var q = (a.X()) ? x.Length : (3 + 4); } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestConditionalExpression_TestAvailableForPrimaryChildren3() { await TestAsync( @"class C { void M() { var q = (a.X()) ? (1 + 2) : $$(a[0]); } }", @"class C { void M() { var q = (a.X()) ? (1 + 2) : a[0]; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestIsPattern_TestAvailableWithAlwaysRemove_And_NotAvailableWhenRequiredForClarity_1() { await TestAsync( @"class C { void M() { if ( $$(a[0]) is string s) { } } }", @"class C { void M() { if ( a[0] is string s) { } } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestIsPattern_TestAvailableWithAlwaysRemove_And_NotAvailableWhenRequiredForClarity_2() { await TestAsync( @"class C { void M() { if ( $$(a * b) is int i) { } } }", @"class C { void M() { if ( a * b is int i) { } } }", offeredWhenRequireForClarityIsEnabled: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestForOverloadedOperatorOnLeft() { await TestInRegularAndScript1Async( @"class C { void M(C c1, C c2, C c3) { var x = $$(c1 + c2) + c3; } public static C operator +(C c1, C c2) => null; }", @"class C { void M(C c1, C c2, C c3) { var x = c1 + c2 + c3; } public static C operator +(C c1, C c2) => null; }", parameters: new TestParameters(options: RequireAllParenthesesForClarity)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestMissingForOverloadedOperatorOnRight() { await TestMissingAsync( @"class C { void M(C c1, C c2, C c3) { var x = c1 + $$(c2 + c3); } public static C operator +(C c1, C c2) => null; }", parameters: new TestParameters(options: RequireAllParenthesesForClarity)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestShiftRequiredForClarity1() { await TestMissingAsync( @"class C { void M() { int x = $$(1 + 2) << 3; } }", parameters: new TestParameters(options: RequireArithmeticBinaryParenthesesForClarity)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestShiftRequiredForClarity2() { await TestMissingAsync( @"class C { void M() { int x = $$(1 + 2) << 3; } }", parameters: new TestParameters(options: RequireAllParenthesesForClarity)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestDoNotRemoveShiftAcrossPrecedence() { await TestMissingAsync( @"class C { void M() { int x = $$(1 + 2) << 3; } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestRemoveShiftIfNotNecessary2() { await TestInRegularAndScript1Async( @"class C { void M() { int x = $$(1 << 2) << 3; } }", @"class C { void M() { int x = 1 << 2 << 3; } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestDoNotRemoveShiftAcrossSamePrecedenceIfValueWouldChange() { await TestMissingAsync( @"class C { void M() { int x = 1 << $$(2 << 3); } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestDoNotRemoveShiftIfShiftKindDiffers() { await TestMissingAsync( @"class C { void M() { int x = $$(1 >> 2) << 3; } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestRemoveCoalesceIfNotNecessary1() { await TestMissingAsync( @"class C { void M() { int x = $$(a ?? b) ?? c; } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestRemoveCoalesceIfNotNecessary2() { await TestInRegularAndScript1Async( @"class C { void M() { int x = a ?? $$(b ?? c); } }", @"class C { void M() { int x = a ?? b ?? c; } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestBitwiseExpression_TestMissingWithDifferencePrecedence1() { await TestMissingAsync( @"class C { void M() { var q = $$(a + b) & c; } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestBitwiseExpression_TestMissingWithDifferencePrecedence2() { await TestMissingAsync( @"class C { void M() { var q = $$(a | b) & c; } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestBitwiseExpression_TestAvailableWithSamePrecedenceMissingWithDifferencePrecedence2() { await TestAsync( @"class C { void M() { var q = $$(a & b) & c; } }", @"class C { void M() { var q = a & b & c; } }", offeredWhenRequireForClarityIsEnabled: true); } [WorkItem(25554, "https://github.com/dotnet/roslyn/issues/25554")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestSwitchCase_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { switch (true) { case $$(default(bool)): } } }", @"class C { void M() { switch (true) { case default(bool): } } }", offeredWhenRequireForClarityIsEnabled: true); } [WorkItem(25554, "https://github.com/dotnet/roslyn/issues/25554")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestSwitchCase_WithWhenClause_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { switch (true) { case $$(default(bool)) when true: } } }", @"class C { void M() { switch (true) { case default(bool) when true: } } }", offeredWhenRequireForClarityIsEnabled: true); } [WorkItem(25554, "https://github.com/dotnet/roslyn/issues/25554")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestWhenClause_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { switch (true) { case true when $$(default(bool)): } } }", @"class C { void M() { switch (true) { case true when default(bool): } } }", offeredWhenRequireForClarityIsEnabled: true); } [WorkItem(25554, "https://github.com/dotnet/roslyn/issues/25554")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestConstantPatternExpression_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { if (true is $$(default(bool))) { } } }", @"class C { void M() { if (true is default(bool)) { } } }", offeredWhenRequireForClarityIsEnabled: true); } [WorkItem(25554, "https://github.com/dotnet/roslyn/issues/25554")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestConstantPatternExpression_RequiredForPrecedence() { await TestMissingAsync( @"class C { void M(string s) { if (true is $$(true == true)) { } } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestCastAmbiguity1() { await TestMissingAsync( @"class C { void M() { int x = (X)$$(-1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestCastAmbiguity2() { await TestMissingAsync( @"class C { void M() { int x = (X)$$(+1); } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestCastAmbiguity3() { await TestMissingAsync( @"class C { void M() { int x = (X)$$(&1); } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestCastAmbiguity4() { await TestMissingAsync( @"class C { void M() { int x = (X)$$(*1); } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestPrimitiveCastNoAmbiguity1() { await TestAsync( @"class C { void M() { int x = (int)$$(-1); } }", @"class C { void M() { int x = (int)-1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestPrimitiveCastNoAmbiguity2() { await TestAsync( @"class C { void M() { int x = (int)$$(+1); } }", @"class C { void M() { int x = (int)+1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestPrimitiveCastNoAmbiguity3() { await TestAsync( @"class C { void M() { int x = (int)$$(&x); } }", @"class C { void M() { int x = (int)&x; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestPrimitiveCastNoAmbiguity4() { await TestAsync( @"class C { void M() { int x = (int)$$(*x); } }", @"class C { void M() { int x = (int)*x; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestArrayCastNoAmbiguity1() { await TestAsync( @"class C { void M() { int x = (T[])$$(-1); } }", @"class C { void M() { int x = (T[])-1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestArrayCastNoAmbiguity2() { await TestAsync( @"class C { void M() { int x = (T[])$$(+1); } }", @"class C { void M() { int x = (T[])+1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestArrayCastNoAmbiguity3() { await TestAsync( @"class C { void M() { int x = (T[])$$(&x); } }", @"class C { void M() { int x = (T[])&x; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestArrayCastNoAmbiguity4() { await TestAsync( @"class C { void M() { int x = (T[])$$(*x); } }", @"class C { void M() { int x = (T[])*x; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestPointerCastNoAmbiguity1() { await TestAsync( @"class C { void M() { int x = (T*)$$(-1); } }", @"class C { void M() { int x = (T*)-1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestPointerCastNoAmbiguity2() { await TestAsync( @"class C { void M() { int x = (T*)$$(+1); } }", @"class C { void M() { int x = (T*)+1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestPointerCastNoAmbiguity3() { await TestAsync( @"class C { void M() { int x = (T*)$$(&x); } }", @"class C { void M() { int x = (T*)&x; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestPointerCastNoAmbiguity4() { await TestAsync( @"class C { void M() { int x = (T*)$$(*x); } }", @"class C { void M() { int x = (T*)*x; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestNullableCastNoAmbiguity1() { await TestAsync( @"class C { void M() { int x = (T?)$$(-1); } }", @"class C { void M() { int x = (T?)-1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestNullableCastNoAmbiguity2() { await TestAsync( @"class C { void M() { int x = (T?)$$(+1); } }", @"class C { void M() { int x = (T?)+1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestNullableCastNoAmbiguity3() { await TestAsync( @"class C { void M() { int x = (T?)$$(&x); } }", @"class C { void M() { int x = (T?)&x; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestNullableCastNoAmbiguity4() { await TestAsync( @"class C { void M() { int x = (T?)$$(*x); } }", @"class C { void M() { int x = (T?)*x; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestAliasCastNoAmbiguity1() { await TestAsync( @"class C { void M() { int x = (e::N.T)$$(-1); } }", @"class C { void M() { int x = (e::N.T)-1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestAliasCastNoAmbiguity2() { await TestAsync( @"class C { void M() { int x = (e::N.T)$$(+1); } }", @"class C { void M() { int x = (e::N.T)+1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestAliasCastNoAmbiguity3() { await TestAsync( @"class C { void M() { int x = (e::N.T)$$(&x); } }", @"class C { void M() { int x = (e::N.T)&x; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestAliasCastNoAmbiguity4() { await TestAsync( @"class C { void M() { int x = (e::N.T)$$(*x); } }", @"class C { void M() { int x = (e::N.T)*x; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestCastOfPrimary() { await TestAsync( @"class C { void M() { int x = (X)$$(a); } }", @"class C { void M() { int x = (X)a; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestCastOfMemberAccess() { await TestAsync( @"class C { void M() { int x = (X)$$(a.b); } }", @"class C { void M() { int x = (X)a.b; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestCastOfNonAmbiguousUnary() { await TestAsync( @"class C { void M() { int x = (X)$$(!a); } }", @"class C { void M() { int x = (X)!a; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestCastOfCast() { await TestAsync( @"class C { void M() { int x = (X)$$((Y)a); } }", @"class C { void M() { int x = (X)(Y)a; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestIsPatternAndLogical_TestWithAllOptionsSetToIgnore() { await TestAsync( @"class C { void M(object expression) { if ($$(expression is bool b) && b) { } } }", @"class C { void M(object expression) { if (expression is bool b && b) { } } }", offeredWhenRequireForClarityIsEnabled: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestGuardPatternMissing() { await TestMissingAsync( @"class C { void M(object expression) { if (!$$(expression is bool b)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundLValueMemberAccess() { await TestAsync( @"class C { void M() { $$(this.Property) = Property; } }", @"class C { void M() { this.Property = Property; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundMultiplicationInAddEquals() { await TestAsync( @"class C { void M() { x += $$(y * z) } }", @"class C { void M() { x += y * z } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundAddInMultipleEquals() { await TestAsync( @"class C { void M() { x *= $$(y + z) } }", @"class C { void M() { x *= y + z } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestNecessaryCast() { await TestMissingAsync( @"class C { void M() { $$((short)3).ToString(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundChecked() { await TestAsync( @"class C { void M() { int x = 3 * $$(checked(5)); } }", @"class C { void M() { int x = 3 * checked(5); } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundUnchecked() { await TestAsync( @"class C { void M() { int x = 3 * $$(unchecked(5)); } }", @"class C { void M() { int x = 3 * unchecked(5); } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundNameof() { await TestAsync( @"class C { void M() { string property = ""My "" + $$(nameof(property)); } }", @"class C { void M() { string property = ""My "" + nameof(property); } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensIsCheck() { await TestAsync( @"class C { void M() { bool x = $$("""" is string); } }", @"class C { void M() { bool x = """" is string; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestNecessaryParensAroundIs() { await TestMissingAsync( @"class C { void M() { string x = $$("""" is string).ToString(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundAssignmentInInitialization() { await TestAsync( @"class C { void M() { string y; string x = $$(y = ""text""); } }", @"class C { void M() { string y; string x = y = ""text""; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundLambda1() { await TestAsync( @"class C { void M() { Func<string, string> y2 = $$(v => v); } }", @"class C { void M() { Func<string, string> y2 = v => v; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundLambda2() { await TestAsync( @"class C { void M() { Func<string, string> y2 = $$((v) => v); } }", @"class C { void M() { Func<string, string> y2 = (v) => v; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundCastedLambda1() { await TestMissingAsync( @"class C { void M() { string y = ((Func<string, string>)$$((v) => v))(""text""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundCastedLambda2() { await TestMissingAsync( @"class C { void M() { string y = ($$(Func<string, string>)((v) => v))(""text""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundCastedLambda3() { await TestMissingAsync( @"class C { void M() { string y = $$((Func<string, string>)((v) => v))(""text""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundReturnValue1() { await TestAsync( @"class C { void M() { return$$(value); } }", @"class C { void M() { return value; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundReturnValue2() { await TestAsync( @"class C { void M() { return $$(value); } }", @"class C { void M() { return value; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundPPDirective1() { await TestAsync( @"class C { void M() { #if$$(A || B) #endif } }", @"class C { void M() { #ifA || B #endif } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundPPDirective2() { // Currently producing broken code. await TestAsync( @"class C { void M() { #if( $$(A || B) || C) #endif } }", @"class C { void M() { #if( A || B || C) #endif } }", offeredWhenRequireForClarityIsEnabled: true, index: 1); } [WorkItem(29454, "https://github.com/dotnet/roslyn/issues/29454")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestMissingForPreIncrement() { await TestMissingAsync( @"class C { void M(int x) { var v = (byte)$$(++x); } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(29454, "https://github.com/dotnet/roslyn/issues/29454")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestMissingForPreDecrement() { await TestMissingAsync( @"class C { void M(int x) { var v = (byte)$$(--x); } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(29454, "https://github.com/dotnet/roslyn/issues/29454")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestForPostIncrement() { await TestInRegularAndScript1Async( @"class C { void M(int x) { var v = (byte)$$(x++); } }", @"class C { void M(int x) { var v = (byte)x++; } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(29454, "https://github.com/dotnet/roslyn/issues/29454")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestForPostDecrement() { await TestInRegularAndScript1Async( @"class C { void M(int x) { var v = (byte)$$(x--); } }", @"class C { void M(int x) { var v = (byte)x--; } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(29454, "https://github.com/dotnet/roslyn/issues/29454")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestForPreIncrementInLocalDeclaration() { await TestInRegularAndScript1Async( @"class C { void M(int x) { var v = $$(++x); } }", @"class C { void M(int x) { var v = ++x; } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(29454, "https://github.com/dotnet/roslyn/issues/29454")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestForPreIncrementInSimpleAssignment() { await TestInRegularAndScript1Async( @"class C { void M(int x, int v) { v = $$(++x); } }", @"class C { void M(int x, int v) { v = ++x; } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(29454, "https://github.com/dotnet/roslyn/issues/29454")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestForPreIncrementInArgument() { await TestInRegularAndScript1Async( @"class C { void M(int x) { M($$(++x)); } }", @"class C { void M(int x) { M(++x); } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(29454, "https://github.com/dotnet/roslyn/issues/29454")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestMissingForPreIncrementAfterAdd() { await TestMissingAsync( @"class C { void M(int x) { var v = x+$$(++x); } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(29454, "https://github.com/dotnet/roslyn/issues/29454")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestMissingForUnaryPlusAfterAdd() { await TestMissingAsync( @"class C { void M(int x) { var v = x+$$(+x); } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(31103, "https://github.com/dotnet/roslyn/issues/31103")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestMissingForConditionalRefAsLeftHandSideValue() { await TestMissingAsync( @"class Bar { void Foo(bool cond, double a, double b) { [||](cond ? ref a : ref b) = 6.67e-11; } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(31103, "https://github.com/dotnet/roslyn/issues/31103")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestConditionalExpressionAsRightHandSideValue() { await TestInRegularAndScript1Async( @"class Bar { void Foo(bool cond, double a, double b) { double c = $$(cond ? a : b); } }", @"class Bar { void Foo(bool cond, double a, double b) { double c = cond ? a : b; } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(32085, "https://github.com/dotnet/roslyn/issues/32085")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestMissingForNestedConditionalExpressionInLambda() { await TestMissingAsync( @"class Bar { void Test(bool a) { Func<int, string> lambda = number => number + $""{ ($$a ? ""foo"" : ""bar"") }""; } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(27925, "https://github.com/dotnet/roslyn/issues/27925")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestUnnecessaryParenthesisDiagnosticSingleLineExpression() { var parentheticalExpressionDiagnostic = GetRemoveUnnecessaryParenthesesDiagnostic("(1 + 2)", 4, 16); await TestDiagnosticsAsync( @"class C { void M() { int x = [|(1 + 2)|]; } }", new TestParameters(options: RemoveAllUnnecessaryParentheses), parentheticalExpressionDiagnostic); } [WorkItem(27925, "https://github.com/dotnet/roslyn/issues/27925")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestUnnecessaryParenthesisDiagnosticInMultiLineExpression() { var firstLineParentheticalExpressionDiagnostic = GetRemoveUnnecessaryParenthesesDiagnostic("(1 +", 4, 16); await TestDiagnosticsAsync( @"class C { void M() { int x = [|(1 + 2)|]; } }", new TestParameters(options: RemoveAllUnnecessaryParentheses), firstLineParentheticalExpressionDiagnostic); } [WorkItem(27925, "https://github.com/dotnet/roslyn/issues/27925")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestUnnecessaryParenthesisDiagnosticInNestedExpression() { var outerParentheticalExpressionDiagnostic = GetRemoveUnnecessaryParenthesesDiagnostic("(1 + (2 + 3) + 4)", 4, 16); var innerParentheticalExpressionDiagnostic = GetRemoveUnnecessaryParenthesesDiagnostic("(2 + 3)", 4, 21); var expectedDiagnostics = new DiagnosticDescription[] { outerParentheticalExpressionDiagnostic, innerParentheticalExpressionDiagnostic }; await TestDiagnosticsAsync( @"class C { void M() { int x = [|(1 + (2 + 3) + 4)|]; } }", new TestParameters(options: RemoveAllUnnecessaryParentheses), expectedDiagnostics); } [WorkItem(27925, "https://github.com/dotnet/roslyn/issues/27925")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestUnnecessaryParenthesisDiagnosticInNestedMultiLineExpression() { var outerFirstLineParentheticalExpressionDiagnostic = GetRemoveUnnecessaryParenthesesDiagnostic("(1 + 2 +", 4, 16); var innerParentheticalExpressionDiagnostic = GetRemoveUnnecessaryParenthesesDiagnostic("(3 + 4)", 5, 12); var expectedDiagnostics = new DiagnosticDescription[] { outerFirstLineParentheticalExpressionDiagnostic, innerParentheticalExpressionDiagnostic }; await TestDiagnosticsAsync( @"class C { void M() { int x = [|(1 + 2 + (3 + 4) + 5 + 6)|]; } }", new TestParameters(options: RemoveAllUnnecessaryParentheses), expectedDiagnostics); } [WorkItem(39529, "https://github.com/dotnet/roslyn/issues/39529")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestUnnecessaryParenthesisIncludesFadeLocations() { var input = @"class C { void M() { int x = [|{|expression:{|fade:(|}1 + 2{|fade:)|}|}|]; } }"; var parameters = new TestParameters(options: RemoveAllUnnecessaryParentheses); using var workspace = CreateWorkspaceFromOptions(input, parameters); var expectedSpans = workspace.Documents.First().AnnotatedSpans; var diagnostics = await GetDiagnosticsAsync(workspace, parameters).ConfigureAwait(false); var diagnostic = diagnostics.Single(); Assert.Equal(3, diagnostic.AdditionalLocations.Count); Assert.Equal(expectedSpans["expression"].Single(), diagnostic.AdditionalLocations[0].SourceSpan); Assert.Equal(expectedSpans["fade"][0], diagnostic.AdditionalLocations[1].SourceSpan); Assert.Equal(expectedSpans["fade"][1], diagnostic.AdditionalLocations[2].SourceSpan); Assert.Equal("[1,2]", diagnostic.Properties[WellKnownDiagnosticTags.Unnecessary]); } [WorkItem(27925, "https://github.com/dotnet/roslyn/issues/39363")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestUnnecessaryParenthesesInSwitchExpression() { await TestAsync( @"class C { void M(int x) { var result = x switch { 1 => $$(5), 2 => 10 + 5, _ => 100, } }; }", @"class C { void M(int x) { var result = x switch { 1 => 5, 2 => 10 + 5, _ => 100, } }; }", offeredWhenRequireForClarityIsEnabled: true); } [WorkItem(26311, "https://github.com/dotnet/roslyn/issues/26311")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestUnnecessaryParenthesesAroundDefaultLiteral() { await TestAsync( @"class C { void M() { bool f = false; string s2 = f ? """" : $$(default); } }", @"class C { void M() { bool f = false; string s2 = f ? """" : default; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestRangeWithConstantExpression() { await TestAsync( @"class C { void M(string s) { _ = s[$$(1)..]; } }", @"class C { void M(string s) { _ = s[1..]; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestRangeWithMemberAccessExpression() { await TestAsync( @"class C { void M(string s) { _ = s[$$(s.Length)..]; } }", @"class C { void M(string s) { _ = s[s.Length..]; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestRangeWithElementAccessExpression() { await TestAsync( @"class C { void M(string s, int[] indices) { _ = s[$$(indices[0])..]; } }", @"class C { void M(string s, int[] indices) { _ = s[indices[0]..]; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestRangeWithBinaryExpression() { await TestMissingAsync( @"class C { void M(string s) { _ = s[$$(s.Length - 5)..]; } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestAlwaysUnnecessaryForPrimaryPattern1() { await TestAsync( @"class C { void M(object o) { bool x = o is 1 or $$(2); } }", @"class C { void M(object o) { bool x = o is 1 or 2; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestAlwaysUnnecessaryForPrimaryPattern2() { await TestAsync( @"class C { void M(object o) { bool x = o is $$(1) or 2; } }", @"class C { void M(object o) { bool x = o is 1 or 2; } }", offeredWhenRequireForClarityIsEnabled: true); } [WorkItem(50025, "https://github.com/dotnet/roslyn/issues/50025")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestDoNotRemoveWithConstantAndTypeAmbiguity() { await TestMissingAsync( @" public class C { public const int Goo = 1; public void M(Goo o) { if (o is $$(Goo)) M(1); } } public class Goo { }"); } [WorkItem(50025, "https://github.com/dotnet/roslyn/issues/50025")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestDoRemoveWithNoConstantAndTypeAmbiguity() { await TestAsync( @" public class C { public const int Goo = 1; public void M(object o) { if (o is $$(Goo)) M(1); } } ", @" public class C { public const int Goo = 1; public void M(object o) { if (o is Goo) M(1); } } ", offeredWhenRequireForClarityIsEnabled: 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; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.RemoveUnnecessaryParentheses; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RemoveUnnecessaryParentheses { public partial class RemoveUnnecessaryExpressionParenthesesTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public RemoveUnnecessaryExpressionParenthesesTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpRemoveUnnecessaryExpressionParenthesesDiagnosticAnalyzer(), new CSharpRemoveUnnecessaryParenthesesCodeFixProvider()); private async Task TestAsync(string initial, string expected, bool offeredWhenRequireForClarityIsEnabled, int index = 0) { await TestInRegularAndScriptAsync(initial, expected, options: RemoveAllUnnecessaryParentheses, index: index); if (offeredWhenRequireForClarityIsEnabled) { await TestInRegularAndScriptAsync(initial, expected, options: RequireAllParenthesesForClarity, index: index); } else { await TestMissingAsync(initial, parameters: new TestParameters(options: RequireAllParenthesesForClarity)); } } internal override bool ShouldSkipMessageDescriptionVerification(DiagnosticDescriptor descriptor) => descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.Unnecessary) && descriptor.DefaultSeverity == DiagnosticSeverity.Hidden; private static DiagnosticDescription GetRemoveUnnecessaryParenthesesDiagnostic(string text, int line, int column) => TestHelpers.Diagnostic(IDEDiagnosticIds.RemoveUnnecessaryParenthesesDiagnosticId, text, startLocation: new LinePosition(line, column)); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestVariableInitializer_TestWithAllOptionsSetToIgnore() { await TestMissingAsync( @"class C { void M() { int x = $$(1); } }", new TestParameters(options: IgnoreAllParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] [WorkItem(29736, "https://github.com/dotnet/roslyn/issues/29736")] public async Task TestVariableInitializer_TestMissingParenthesis() { await TestMissingAsync( @"class C { void M() { int x = $$(1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestArithmeticRequiredForClarity1() { await TestMissingAsync( @"class C { void M() { int x = 1 + $$(2 * 3); } }", new TestParameters(options: RequireArithmeticBinaryParenthesesForClarity)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] [WorkItem(44629, "https://github.com/dotnet/roslyn/issues/44629")] public async Task TestStackAlloc() { await TestMissingAsync( @"class C { void M() { var span = $$(stackalloc byte[8]); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] [WorkItem(47365, "https://github.com/dotnet/roslyn/issues/47365")] public async Task TestDynamic() { await TestMissingAsync( @"class C { void M() { dynamic i = 1; dynamic s = ""s""; Console.WriteLine(s + $$(1 + i)); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestArithmeticRequiredForClarity2() { await TestInRegularAndScript1Async( @"class C { void M() { int x = a || $$(b && c); } }", @"class C { void M() { int x = a || b && c; } }", parameters: new TestParameters(options: RequireArithmeticBinaryParenthesesForClarity)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestLogicalRequiredForClarity1() { await TestMissingAsync( @"class C { void M() { int x = a || $$(b && c); } }", new TestParameters(options: RequireOtherBinaryParenthesesForClarity)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestLogicalRequiredForClarity2() { await TestInRegularAndScript1Async( @"class C { void M() { int x = a + $$(b * c); } }", @"class C { void M() { int x = a + b * c; } }", parameters: new TestParameters(options: RequireOtherBinaryParenthesesForClarity)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestArithmeticNotRequiredForClarityWhenPrecedenceStaysTheSame_Integral1() { await TestAsync( @"class C { void M() { int x = 1 + $$(2 + 3); } }", @"class C { void M() { int x = 1 + 2 + 3; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestArithmeticNotRequiredForClarityWhenPrecedenceStaysTheSame_Integral2() { await TestAsync( @"class C { void M() { int x = $$(1 + 2) + 3; } }", @"class C { void M() { int x = 1 + 2 + 3; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestArithmeticRequiredForCorrectnessWhenPrecedenceStaysTheSameIfFloatingPoint() { await TestMissingAsync( @"class C { void M() { int x = 1.0 + $$(2.0 + 3.0); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestArithmeticNotRequiredForClarityWhenPrecedenceStaysTheSame_Floating2() { await TestAsync( @"class C { void M() { int x = $$(1.0 + 2.0) + 3.0; } }", @"class C { void M() { int x = 1.0 + 2.0 + 3.0; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestLogicalNotRequiredForClarityWhenPrecedenceStaysTheSame1() { await TestAsync( @"class C { void M() { int x = a || $$(b || c); } }", @"class C { void M() { int x = a || b || c; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestLogicalNotRequiredForClarityWhenPrecedenceStaysTheSame2() { await TestAsync( @"class C { void M() { int x = $$(a || b) || c; } }", @"class C { void M() { int x = a || b || c; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestVariableInitializer_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { int x = $$(1); } }", @"class C { void M() { int x = 1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestReturnStatement_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { return $$(1 + 2); } }", @"class C { void M() { return 1 + 2; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestExpressionBody_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { int M() => $$(1 + 2); }", @"class C { int M() => 1 + 2; }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestCheckedExpression_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { int i = checked($$(1 + 2)); } }", @"class C { void M() { int i = checked(1 + 2); } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestAssignment_TestAvailableWithAlwaysRemove_And_TestNotAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { i = $$(1 + 2); } }", @"class C { void M() { i = 1 + 2; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestCompoundAssignment_TestAvailableWithAlwaysRemove_And_TestNotAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { i *= $$(1 + 2); } }", @"class C { void M() { i *= 1 + 2; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestPimaryAssignment_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { i = $$(s.Length); } }", @"class C { void M() { i = s.Length; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestNestedParenthesizedExpression_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { int i = ( $$(1 + 2) ); } }", @"class C { void M() { int i = ( 1 + 2 ); } }", offeredWhenRequireForClarityIsEnabled: true, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestIncrementExpression_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { int i = $$(x++); } }", @"class C { void M() { int i = x++; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestLambdaBody_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { Func<int> i = () => $$(1); } }", @"class C { void M() { Func<int> i = () => 1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestArrayElement_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { int[] i = new int[] { $$(1) }; } }", @"class C { void M() { int[] i = new int[] { 1 }; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestWhereClause_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { var q = from c in customer where $$(c.Age > 21) select c; } }", @"class C { void M() { var q = from c in customer where c.Age > 21 select c; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestCastExpression_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { int i = (int)$$(1); } }", @"class C { void M() { int i = (int)1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestMissingForConditionalAccess1() { await TestMissingAsync( @"class C { void M(string s) { var v = $$(s?.Length).ToString(); } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(37046, "https://github.com/dotnet/roslyn/issues/37046")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestMissingForConditionalAccess2() { await TestMissingAsync( @"class C { void M(string s) { var v = $$(s?.Length)?.ToString(); } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestForConditionalAccessNotInExpression() { await TestInRegularAndScriptAsync( @"class C { void M(string s) { var v = $$(s?.Length); } }", @"class C { void M(string s) { var v = s?.Length; } }", options: RemoveAllUnnecessaryParentheses); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestMissingForConditionalIndex() { await TestMissingAsync( @"class C { void M(string s) { var v = $$(s?[0]).ToString(); } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestBinaryInCastExpression() { await TestMissingAsync( @"class C { void M() { int i = (int)$$(1 + 2); } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestAroundCastExpression_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { int i = $$((int)1); } }", @"class C { void M() { int i = (int)1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestConditionalInInterpolation() { await TestMissingAsync( @"class C { void M() { var s = $""{ $$(a ? b : c) }""; } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestConditionalInInterpolation_FixAll_1() { await TestAsync( @"class C { void M() { var s1 = $""{ {|FixAllInDocument:(|}(a ? b : c)) }""; var s2 = $""{ ((a ? b : c)) }""; } }", @"class C { void M() { var s1 = $""{ (a ? b : c) }""; var s2 = $""{ (a ? b : c) }""; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestConditionalInInterpolation_FixAll_2() { await TestAsync( @"class C { void M() { var s1 = $""{ ({|FixAllInDocument:(|}a ? b : c)) }""; var s2 = $""{ ((a ? b : c)) }""; } }", @"class C { void M() { var s1 = $""{ (a ? b : c) }""; var s2 = $""{ (a ? b : c) }""; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestNonConditionalInInterpolation_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { var s = $""{ $$(true) }""; } }", @"class C { void M() { var s = $""{ true }""; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestBinaryExpression_TestAvailableWithAlwaysRemove_And_NotAvailableWhenRequiredForClarity_1() { await TestAsync( @"class C { void M() { var q = $$(a * b) + c; } }", @"class C { void M() { var q = a * b + c; } }", offeredWhenRequireForClarityIsEnabled: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestBinaryExpression_TestAvailableWithAlwaysRemove_And_NotAvailableWhenRequiredForClarity_2() { await TestAsync( @"class C { void M() { var q = c + $$(a * b); } }", @"class C { void M() { var q = c + a * b; } }", offeredWhenRequireForClarityIsEnabled: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestConditionalExpression_TestNotAvailableForComplexChildren1() { await TestMissingAsync( @"class C { void M() { var q = $$(a * b) ? (1 + 2) : (3 + 4); } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestConditionalExpression_TestNotAvailableForComplexChildren2() { await TestMissingAsync( @"class C { void M() { var q = (a * b) ? $$(1 + 2) : (3 + 4); } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestConditionalExpression_TestNotAvailableForComplexChildren3() { await TestMissingAsync( @"class C { void M() { var q = (a * b) ? (1 + 2) : $$(3 + 4); } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestConditionalExpression_TestAvailableForPrimaryChildren1() { await TestAsync( @"class C { void M() { var q = $$(a.X()) ? (1 + 2) : (3 + 4); } }", @"class C { void M() { var q = a.X() ? (1 + 2) : (3 + 4); } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestConditionalExpression_TestAvailableForPrimaryChildren2() { await TestAsync( @"class C { void M() { var q = (a.X()) ? $$(x.Length) : (3 + 4); } }", @"class C { void M() { var q = (a.X()) ? x.Length : (3 + 4); } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestConditionalExpression_TestAvailableForPrimaryChildren3() { await TestAsync( @"class C { void M() { var q = (a.X()) ? (1 + 2) : $$(a[0]); } }", @"class C { void M() { var q = (a.X()) ? (1 + 2) : a[0]; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestIsPattern_TestAvailableWithAlwaysRemove_And_NotAvailableWhenRequiredForClarity_1() { await TestAsync( @"class C { void M() { if ( $$(a[0]) is string s) { } } }", @"class C { void M() { if ( a[0] is string s) { } } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestIsPattern_TestAvailableWithAlwaysRemove_And_NotAvailableWhenRequiredForClarity_2() { await TestAsync( @"class C { void M() { if ( $$(a * b) is int i) { } } }", @"class C { void M() { if ( a * b is int i) { } } }", offeredWhenRequireForClarityIsEnabled: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestForOverloadedOperatorOnLeft() { await TestInRegularAndScript1Async( @"class C { void M(C c1, C c2, C c3) { var x = $$(c1 + c2) + c3; } public static C operator +(C c1, C c2) => null; }", @"class C { void M(C c1, C c2, C c3) { var x = c1 + c2 + c3; } public static C operator +(C c1, C c2) => null; }", parameters: new TestParameters(options: RequireAllParenthesesForClarity)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestMissingForOverloadedOperatorOnRight() { await TestMissingAsync( @"class C { void M(C c1, C c2, C c3) { var x = c1 + $$(c2 + c3); } public static C operator +(C c1, C c2) => null; }", parameters: new TestParameters(options: RequireAllParenthesesForClarity)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestShiftRequiredForClarity1() { await TestMissingAsync( @"class C { void M() { int x = $$(1 + 2) << 3; } }", parameters: new TestParameters(options: RequireArithmeticBinaryParenthesesForClarity)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestShiftRequiredForClarity2() { await TestMissingAsync( @"class C { void M() { int x = $$(1 + 2) << 3; } }", parameters: new TestParameters(options: RequireAllParenthesesForClarity)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestDoNotRemoveShiftAcrossPrecedence() { await TestMissingAsync( @"class C { void M() { int x = $$(1 + 2) << 3; } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestRemoveShiftIfNotNecessary2() { await TestInRegularAndScript1Async( @"class C { void M() { int x = $$(1 << 2) << 3; } }", @"class C { void M() { int x = 1 << 2 << 3; } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestDoNotRemoveShiftAcrossSamePrecedenceIfValueWouldChange() { await TestMissingAsync( @"class C { void M() { int x = 1 << $$(2 << 3); } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestDoNotRemoveShiftIfShiftKindDiffers() { await TestMissingAsync( @"class C { void M() { int x = $$(1 >> 2) << 3; } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestRemoveCoalesceIfNotNecessary1() { await TestMissingAsync( @"class C { void M() { int x = $$(a ?? b) ?? c; } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestRemoveCoalesceIfNotNecessary2() { await TestInRegularAndScript1Async( @"class C { void M() { int x = a ?? $$(b ?? c); } }", @"class C { void M() { int x = a ?? b ?? c; } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestBitwiseExpression_TestMissingWithDifferencePrecedence1() { await TestMissingAsync( @"class C { void M() { var q = $$(a + b) & c; } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestBitwiseExpression_TestMissingWithDifferencePrecedence2() { await TestMissingAsync( @"class C { void M() { var q = $$(a | b) & c; } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestBitwiseExpression_TestAvailableWithSamePrecedenceMissingWithDifferencePrecedence2() { await TestAsync( @"class C { void M() { var q = $$(a & b) & c; } }", @"class C { void M() { var q = a & b & c; } }", offeredWhenRequireForClarityIsEnabled: true); } [WorkItem(25554, "https://github.com/dotnet/roslyn/issues/25554")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestSwitchCase_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { switch (true) { case $$(default(bool)): } } }", @"class C { void M() { switch (true) { case default(bool): } } }", offeredWhenRequireForClarityIsEnabled: true); } [WorkItem(25554, "https://github.com/dotnet/roslyn/issues/25554")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestSwitchCase_WithWhenClause_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { switch (true) { case $$(default(bool)) when true: } } }", @"class C { void M() { switch (true) { case default(bool) when true: } } }", offeredWhenRequireForClarityIsEnabled: true); } [WorkItem(25554, "https://github.com/dotnet/roslyn/issues/25554")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestWhenClause_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { switch (true) { case true when $$(default(bool)): } } }", @"class C { void M() { switch (true) { case true when default(bool): } } }", offeredWhenRequireForClarityIsEnabled: true); } [WorkItem(25554, "https://github.com/dotnet/roslyn/issues/25554")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestConstantPatternExpression_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { if (true is $$(default(bool))) { } } }", @"class C { void M() { if (true is default(bool)) { } } }", offeredWhenRequireForClarityIsEnabled: true); } [WorkItem(25554, "https://github.com/dotnet/roslyn/issues/25554")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestConstantPatternExpression_RequiredForPrecedence() { await TestMissingAsync( @"class C { void M(string s) { if (true is $$(true == true)) { } } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestCastAmbiguity1() { await TestMissingAsync( @"class C { void M() { int x = (X)$$(-1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestCastAmbiguity2() { await TestMissingAsync( @"class C { void M() { int x = (X)$$(+1); } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestCastAmbiguity3() { await TestMissingAsync( @"class C { void M() { int x = (X)$$(&1); } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestCastAmbiguity4() { await TestMissingAsync( @"class C { void M() { int x = (X)$$(*1); } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestPrimitiveCastNoAmbiguity1() { await TestAsync( @"class C { void M() { int x = (int)$$(-1); } }", @"class C { void M() { int x = (int)-1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestPrimitiveCastNoAmbiguity2() { await TestAsync( @"class C { void M() { int x = (int)$$(+1); } }", @"class C { void M() { int x = (int)+1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestPrimitiveCastNoAmbiguity3() { await TestAsync( @"class C { void M() { int x = (int)$$(&x); } }", @"class C { void M() { int x = (int)&x; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestPrimitiveCastNoAmbiguity4() { await TestAsync( @"class C { void M() { int x = (int)$$(*x); } }", @"class C { void M() { int x = (int)*x; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestArrayCastNoAmbiguity1() { await TestAsync( @"class C { void M() { int x = (T[])$$(-1); } }", @"class C { void M() { int x = (T[])-1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestArrayCastNoAmbiguity2() { await TestAsync( @"class C { void M() { int x = (T[])$$(+1); } }", @"class C { void M() { int x = (T[])+1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestArrayCastNoAmbiguity3() { await TestAsync( @"class C { void M() { int x = (T[])$$(&x); } }", @"class C { void M() { int x = (T[])&x; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestArrayCastNoAmbiguity4() { await TestAsync( @"class C { void M() { int x = (T[])$$(*x); } }", @"class C { void M() { int x = (T[])*x; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestPointerCastNoAmbiguity1() { await TestAsync( @"class C { void M() { int x = (T*)$$(-1); } }", @"class C { void M() { int x = (T*)-1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestPointerCastNoAmbiguity2() { await TestAsync( @"class C { void M() { int x = (T*)$$(+1); } }", @"class C { void M() { int x = (T*)+1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestPointerCastNoAmbiguity3() { await TestAsync( @"class C { void M() { int x = (T*)$$(&x); } }", @"class C { void M() { int x = (T*)&x; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestPointerCastNoAmbiguity4() { await TestAsync( @"class C { void M() { int x = (T*)$$(*x); } }", @"class C { void M() { int x = (T*)*x; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestNullableCastNoAmbiguity1() { await TestAsync( @"class C { void M() { int x = (T?)$$(-1); } }", @"class C { void M() { int x = (T?)-1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestNullableCastNoAmbiguity2() { await TestAsync( @"class C { void M() { int x = (T?)$$(+1); } }", @"class C { void M() { int x = (T?)+1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestNullableCastNoAmbiguity3() { await TestAsync( @"class C { void M() { int x = (T?)$$(&x); } }", @"class C { void M() { int x = (T?)&x; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestNullableCastNoAmbiguity4() { await TestAsync( @"class C { void M() { int x = (T?)$$(*x); } }", @"class C { void M() { int x = (T?)*x; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestAliasCastNoAmbiguity1() { await TestAsync( @"class C { void M() { int x = (e::N.T)$$(-1); } }", @"class C { void M() { int x = (e::N.T)-1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestAliasCastNoAmbiguity2() { await TestAsync( @"class C { void M() { int x = (e::N.T)$$(+1); } }", @"class C { void M() { int x = (e::N.T)+1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestAliasCastNoAmbiguity3() { await TestAsync( @"class C { void M() { int x = (e::N.T)$$(&x); } }", @"class C { void M() { int x = (e::N.T)&x; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestAliasCastNoAmbiguity4() { await TestAsync( @"class C { void M() { int x = (e::N.T)$$(*x); } }", @"class C { void M() { int x = (e::N.T)*x; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestCastOfPrimary() { await TestAsync( @"class C { void M() { int x = (X)$$(a); } }", @"class C { void M() { int x = (X)a; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestCastOfMemberAccess() { await TestAsync( @"class C { void M() { int x = (X)$$(a.b); } }", @"class C { void M() { int x = (X)a.b; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestCastOfNonAmbiguousUnary() { await TestAsync( @"class C { void M() { int x = (X)$$(!a); } }", @"class C { void M() { int x = (X)!a; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestCastOfCast() { await TestAsync( @"class C { void M() { int x = (X)$$((Y)a); } }", @"class C { void M() { int x = (X)(Y)a; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestIsPatternAndLogical_TestWithAllOptionsSetToIgnore() { await TestAsync( @"class C { void M(object expression) { if ($$(expression is bool b) && b) { } } }", @"class C { void M(object expression) { if (expression is bool b && b) { } } }", offeredWhenRequireForClarityIsEnabled: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestGuardPatternMissing() { await TestMissingAsync( @"class C { void M(object expression) { if (!$$(expression is bool b)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundLValueMemberAccess() { await TestAsync( @"class C { void M() { $$(this.Property) = Property; } }", @"class C { void M() { this.Property = Property; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundMultiplicationInAddEquals() { await TestAsync( @"class C { void M() { x += $$(y * z) } }", @"class C { void M() { x += y * z } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundAddInMultipleEquals() { await TestAsync( @"class C { void M() { x *= $$(y + z) } }", @"class C { void M() { x *= y + z } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestNecessaryCast() { await TestMissingAsync( @"class C { void M() { $$((short)3).ToString(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundChecked() { await TestAsync( @"class C { void M() { int x = 3 * $$(checked(5)); } }", @"class C { void M() { int x = 3 * checked(5); } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundUnchecked() { await TestAsync( @"class C { void M() { int x = 3 * $$(unchecked(5)); } }", @"class C { void M() { int x = 3 * unchecked(5); } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundNameof() { await TestAsync( @"class C { void M() { string property = ""My "" + $$(nameof(property)); } }", @"class C { void M() { string property = ""My "" + nameof(property); } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensIsCheck() { await TestAsync( @"class C { void M() { bool x = $$("""" is string); } }", @"class C { void M() { bool x = """" is string; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestNecessaryParensAroundIs() { await TestMissingAsync( @"class C { void M() { string x = $$("""" is string).ToString(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundAssignmentInInitialization() { await TestAsync( @"class C { void M() { string y; string x = $$(y = ""text""); } }", @"class C { void M() { string y; string x = y = ""text""; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundLambda1() { await TestAsync( @"class C { void M() { Func<string, string> y2 = $$(v => v); } }", @"class C { void M() { Func<string, string> y2 = v => v; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundLambda2() { await TestAsync( @"class C { void M() { Func<string, string> y2 = $$((v) => v); } }", @"class C { void M() { Func<string, string> y2 = (v) => v; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundCastedLambda1() { await TestMissingAsync( @"class C { void M() { string y = ((Func<string, string>)$$((v) => v))(""text""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundCastedLambda2() { await TestMissingAsync( @"class C { void M() { string y = ($$(Func<string, string>)((v) => v))(""text""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundCastedLambda3() { await TestMissingAsync( @"class C { void M() { string y = $$((Func<string, string>)((v) => v))(""text""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundReturnValue1() { await TestAsync( @"class C { void M() { return$$(value); } }", @"class C { void M() { return value; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundReturnValue2() { await TestAsync( @"class C { void M() { return $$(value); } }", @"class C { void M() { return value; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundPPDirective1() { await TestAsync( @"class C { void M() { #if$$(A || B) #endif } }", @"class C { void M() { #ifA || B #endif } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundPPDirective2() { // Currently producing broken code. await TestAsync( @"class C { void M() { #if( $$(A || B) || C) #endif } }", @"class C { void M() { #if( A || B || C) #endif } }", offeredWhenRequireForClarityIsEnabled: true, index: 1); } [WorkItem(29454, "https://github.com/dotnet/roslyn/issues/29454")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestMissingForPreIncrement() { await TestMissingAsync( @"class C { void M(int x) { var v = (byte)$$(++x); } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(29454, "https://github.com/dotnet/roslyn/issues/29454")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestMissingForPreDecrement() { await TestMissingAsync( @"class C { void M(int x) { var v = (byte)$$(--x); } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(29454, "https://github.com/dotnet/roslyn/issues/29454")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestForPostIncrement() { await TestInRegularAndScript1Async( @"class C { void M(int x) { var v = (byte)$$(x++); } }", @"class C { void M(int x) { var v = (byte)x++; } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(29454, "https://github.com/dotnet/roslyn/issues/29454")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestForPostDecrement() { await TestInRegularAndScript1Async( @"class C { void M(int x) { var v = (byte)$$(x--); } }", @"class C { void M(int x) { var v = (byte)x--; } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(29454, "https://github.com/dotnet/roslyn/issues/29454")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestForPreIncrementInLocalDeclaration() { await TestInRegularAndScript1Async( @"class C { void M(int x) { var v = $$(++x); } }", @"class C { void M(int x) { var v = ++x; } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(29454, "https://github.com/dotnet/roslyn/issues/29454")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestForPreIncrementInSimpleAssignment() { await TestInRegularAndScript1Async( @"class C { void M(int x, int v) { v = $$(++x); } }", @"class C { void M(int x, int v) { v = ++x; } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(29454, "https://github.com/dotnet/roslyn/issues/29454")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestForPreIncrementInArgument() { await TestInRegularAndScript1Async( @"class C { void M(int x) { M($$(++x)); } }", @"class C { void M(int x) { M(++x); } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(29454, "https://github.com/dotnet/roslyn/issues/29454")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestMissingForPreIncrementAfterAdd() { await TestMissingAsync( @"class C { void M(int x) { var v = x+$$(++x); } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(29454, "https://github.com/dotnet/roslyn/issues/29454")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestMissingForUnaryPlusAfterAdd() { await TestMissingAsync( @"class C { void M(int x) { var v = x+$$(+x); } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(31103, "https://github.com/dotnet/roslyn/issues/31103")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestMissingForConditionalRefAsLeftHandSideValue() { await TestMissingAsync( @"class Bar { void Foo(bool cond, double a, double b) { [||](cond ? ref a : ref b) = 6.67e-11; } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(31103, "https://github.com/dotnet/roslyn/issues/31103")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestConditionalExpressionAsRightHandSideValue() { await TestInRegularAndScript1Async( @"class Bar { void Foo(bool cond, double a, double b) { double c = $$(cond ? a : b); } }", @"class Bar { void Foo(bool cond, double a, double b) { double c = cond ? a : b; } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(32085, "https://github.com/dotnet/roslyn/issues/32085")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestMissingForNestedConditionalExpressionInLambda() { await TestMissingAsync( @"class Bar { void Test(bool a) { Func<int, string> lambda = number => number + $""{ ($$a ? ""foo"" : ""bar"") }""; } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(27925, "https://github.com/dotnet/roslyn/issues/27925")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestUnnecessaryParenthesisDiagnosticSingleLineExpression() { var parentheticalExpressionDiagnostic = GetRemoveUnnecessaryParenthesesDiagnostic("(1 + 2)", 4, 16); await TestDiagnosticsAsync( @"class C { void M() { int x = [|(1 + 2)|]; } }", new TestParameters(options: RemoveAllUnnecessaryParentheses), parentheticalExpressionDiagnostic); } [WorkItem(27925, "https://github.com/dotnet/roslyn/issues/27925")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestUnnecessaryParenthesisDiagnosticInMultiLineExpression() { var firstLineParentheticalExpressionDiagnostic = GetRemoveUnnecessaryParenthesesDiagnostic("(1 +", 4, 16); await TestDiagnosticsAsync( @"class C { void M() { int x = [|(1 + 2)|]; } }", new TestParameters(options: RemoveAllUnnecessaryParentheses), firstLineParentheticalExpressionDiagnostic); } [WorkItem(27925, "https://github.com/dotnet/roslyn/issues/27925")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestUnnecessaryParenthesisDiagnosticInNestedExpression() { var outerParentheticalExpressionDiagnostic = GetRemoveUnnecessaryParenthesesDiagnostic("(1 + (2 + 3) + 4)", 4, 16); var innerParentheticalExpressionDiagnostic = GetRemoveUnnecessaryParenthesesDiagnostic("(2 + 3)", 4, 21); var expectedDiagnostics = new DiagnosticDescription[] { outerParentheticalExpressionDiagnostic, innerParentheticalExpressionDiagnostic }; await TestDiagnosticsAsync( @"class C { void M() { int x = [|(1 + (2 + 3) + 4)|]; } }", new TestParameters(options: RemoveAllUnnecessaryParentheses), expectedDiagnostics); } [WorkItem(27925, "https://github.com/dotnet/roslyn/issues/27925")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestUnnecessaryParenthesisDiagnosticInNestedMultiLineExpression() { var outerFirstLineParentheticalExpressionDiagnostic = GetRemoveUnnecessaryParenthesesDiagnostic("(1 + 2 +", 4, 16); var innerParentheticalExpressionDiagnostic = GetRemoveUnnecessaryParenthesesDiagnostic("(3 + 4)", 5, 12); var expectedDiagnostics = new DiagnosticDescription[] { outerFirstLineParentheticalExpressionDiagnostic, innerParentheticalExpressionDiagnostic }; await TestDiagnosticsAsync( @"class C { void M() { int x = [|(1 + 2 + (3 + 4) + 5 + 6)|]; } }", new TestParameters(options: RemoveAllUnnecessaryParentheses), expectedDiagnostics); } [WorkItem(39529, "https://github.com/dotnet/roslyn/issues/39529")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestUnnecessaryParenthesisIncludesFadeLocations() { var input = @"class C { void M() { int x = [|{|expression:{|fade:(|}1 + 2{|fade:)|}|}|]; } }"; var parameters = new TestParameters(options: RemoveAllUnnecessaryParentheses); using var workspace = CreateWorkspaceFromOptions(input, parameters); var expectedSpans = workspace.Documents.First().AnnotatedSpans; var diagnostics = await GetDiagnosticsAsync(workspace, parameters).ConfigureAwait(false); var diagnostic = diagnostics.Single(); Assert.Equal(3, diagnostic.AdditionalLocations.Count); Assert.Equal(expectedSpans["expression"].Single(), diagnostic.AdditionalLocations[0].SourceSpan); Assert.Equal(expectedSpans["fade"][0], diagnostic.AdditionalLocations[1].SourceSpan); Assert.Equal(expectedSpans["fade"][1], diagnostic.AdditionalLocations[2].SourceSpan); Assert.Equal("[1,2]", diagnostic.Properties[WellKnownDiagnosticTags.Unnecessary]); } [WorkItem(27925, "https://github.com/dotnet/roslyn/issues/39363")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestUnnecessaryParenthesesInSwitchExpression() { await TestAsync( @"class C { void M(int x) { var result = x switch { 1 => $$(5), 2 => 10 + 5, _ => 100, } }; }", @"class C { void M(int x) { var result = x switch { 1 => 5, 2 => 10 + 5, _ => 100, } }; }", offeredWhenRequireForClarityIsEnabled: true); } [WorkItem(26311, "https://github.com/dotnet/roslyn/issues/26311")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestUnnecessaryParenthesesAroundDefaultLiteral() { await TestAsync( @"class C { void M() { bool f = false; string s2 = f ? """" : $$(default); } }", @"class C { void M() { bool f = false; string s2 = f ? """" : default; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestRangeWithConstantExpression() { await TestAsync( @"class C { void M(string s) { _ = s[$$(1)..]; } }", @"class C { void M(string s) { _ = s[1..]; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestRangeWithMemberAccessExpression() { await TestAsync( @"class C { void M(string s) { _ = s[$$(s.Length)..]; } }", @"class C { void M(string s) { _ = s[s.Length..]; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestRangeWithElementAccessExpression() { await TestAsync( @"class C { void M(string s, int[] indices) { _ = s[$$(indices[0])..]; } }", @"class C { void M(string s, int[] indices) { _ = s[indices[0]..]; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestRangeWithBinaryExpression() { await TestMissingAsync( @"class C { void M(string s) { _ = s[$$(s.Length - 5)..]; } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestAlwaysUnnecessaryForPrimaryPattern1() { await TestAsync( @"class C { void M(object o) { bool x = o is 1 or $$(2); } }", @"class C { void M(object o) { bool x = o is 1 or 2; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestAlwaysUnnecessaryForPrimaryPattern2() { await TestAsync( @"class C { void M(object o) { bool x = o is $$(1) or 2; } }", @"class C { void M(object o) { bool x = o is 1 or 2; } }", offeredWhenRequireForClarityIsEnabled: true); } [WorkItem(50025, "https://github.com/dotnet/roslyn/issues/50025")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestDoNotRemoveWithConstantAndTypeAmbiguity() { await TestMissingAsync( @" public class C { public const int Goo = 1; public void M(Goo o) { if (o is $$(Goo)) M(1); } } public class Goo { }"); } [WorkItem(50025, "https://github.com/dotnet/roslyn/issues/50025")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestDoRemoveWithNoConstantAndTypeAmbiguity() { await TestAsync( @" public class C { public const int Goo = 1; public void M(object o) { if (o is $$(Goo)) M(1); } } ", @" public class C { public const int Goo = 1; public void M(object o) { if (o is Goo) M(1); } } ", offeredWhenRequireForClarityIsEnabled: true); } } }
-1
dotnet/roslyn
56,095
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-02T00:01:28Z"
"2021-09-02T01:47:21Z"
212ca8da034e484813ea99027c29cc3f6405fe1f
fe389d485fb73f8186b32636bfc747a39a70b028
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Core/Impl/Options/OptionStore.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 Microsoft.CodeAnalysis.Options; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { /// <summary> /// This class is intended to be used by Option pages. It will provide access to an options /// from an optionset but will not persist changes automatically. /// </summary> public class OptionStore { public event EventHandler<OptionKey> OptionChanged; private OptionSet _optionSet; private IEnumerable<IOption> _registeredOptions; public OptionStore(OptionSet optionSet, IEnumerable<IOption> registeredOptions) { _optionSet = optionSet; _registeredOptions = registeredOptions; } public object GetOption(OptionKey optionKey) => _optionSet.GetOption(optionKey); public T GetOption<T>(OptionKey optionKey) => _optionSet.GetOption<T>(optionKey); public T GetOption<T>(Option<T> option) => _optionSet.GetOption(option); internal T GetOption<T>(Option2<T> option) => _optionSet.GetOption(option); public T GetOption<T>(PerLanguageOption<T> option, string language) => _optionSet.GetOption(option, language); internal T GetOption<T>(PerLanguageOption2<T> option, string language) => _optionSet.GetOption(option, language); public OptionSet GetOptions() => _optionSet; public void SetOption(OptionKey optionKey, object value) { _optionSet = _optionSet.WithChangedOption(optionKey, value); OnOptionChanged(optionKey); } public void SetOption<T>(Option<T> option, T value) { _optionSet = _optionSet.WithChangedOption(option, value); OnOptionChanged(new OptionKey(option)); } internal void SetOption<T>(Option2<T> option, T value) { _optionSet = _optionSet.WithChangedOption(option, value); OnOptionChanged(new OptionKey(option)); } public void SetOption<T>(PerLanguageOption<T> option, string language, T value) { _optionSet = _optionSet.WithChangedOption(option, language, value); OnOptionChanged(new OptionKey(option, language)); } internal void SetOption<T>(PerLanguageOption2<T> option, string language, T value) { _optionSet = _optionSet.WithChangedOption(option, language, value); OnOptionChanged(new OptionKey(option, language)); } public IEnumerable<IOption> GetRegisteredOptions() => _registeredOptions; public void SetOptions(OptionSet optionSet) => _optionSet = optionSet; public void SetRegisteredOptions(IEnumerable<IOption> registeredOptions) => _registeredOptions = registeredOptions; private void OnOptionChanged(OptionKey optionKey) => OptionChanged?.Invoke(this, optionKey); } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.Options; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { /// <summary> /// This class is intended to be used by Option pages. It will provide access to an options /// from an optionset but will not persist changes automatically. /// </summary> public class OptionStore { public event EventHandler<OptionKey> OptionChanged; private OptionSet _optionSet; private IEnumerable<IOption> _registeredOptions; public OptionStore(OptionSet optionSet, IEnumerable<IOption> registeredOptions) { _optionSet = optionSet; _registeredOptions = registeredOptions; } public object GetOption(OptionKey optionKey) => _optionSet.GetOption(optionKey); public T GetOption<T>(OptionKey optionKey) => _optionSet.GetOption<T>(optionKey); public T GetOption<T>(Option<T> option) => _optionSet.GetOption(option); internal T GetOption<T>(Option2<T> option) => _optionSet.GetOption(option); public T GetOption<T>(PerLanguageOption<T> option, string language) => _optionSet.GetOption(option, language); internal T GetOption<T>(PerLanguageOption2<T> option, string language) => _optionSet.GetOption(option, language); public OptionSet GetOptions() => _optionSet; public void SetOption(OptionKey optionKey, object value) { _optionSet = _optionSet.WithChangedOption(optionKey, value); OnOptionChanged(optionKey); } public void SetOption<T>(Option<T> option, T value) { _optionSet = _optionSet.WithChangedOption(option, value); OnOptionChanged(new OptionKey(option)); } internal void SetOption<T>(Option2<T> option, T value) { _optionSet = _optionSet.WithChangedOption(option, value); OnOptionChanged(new OptionKey(option)); } public void SetOption<T>(PerLanguageOption<T> option, string language, T value) { _optionSet = _optionSet.WithChangedOption(option, language, value); OnOptionChanged(new OptionKey(option, language)); } internal void SetOption<T>(PerLanguageOption2<T> option, string language, T value) { _optionSet = _optionSet.WithChangedOption(option, language, value); OnOptionChanged(new OptionKey(option, language)); } public IEnumerable<IOption> GetRegisteredOptions() => _registeredOptions; public void SetOptions(OptionSet optionSet) => _optionSet = optionSet; public void SetRegisteredOptions(IEnumerable<IOption> registeredOptions) => _registeredOptions = registeredOptions; private void OnOptionChanged(OptionKey optionKey) => OptionChanged?.Invoke(this, optionKey); } }
-1
dotnet/roslyn
56,095
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-02T00:01:28Z"
"2021-09-02T01:47:21Z"
212ca8da034e484813ea99027c29cc3f6405fe1f
fe389d485fb73f8186b32636bfc747a39a70b028
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Analyzers/Core/Analyzers/PopulateSwitch/PopulateSwitchExpressionHelpers.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.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.PopulateSwitch { internal static class PopulateSwitchExpressionHelpers { public static ICollection<ISymbol> GetMissingEnumMembers(ISwitchExpressionOperation operation) { var switchExpression = operation.Value; var switchExpressionType = switchExpression?.Type; // Check if the type of the expression is a nullable INamedTypeSymbol // if the type is both nullable and an INamedTypeSymbol extract the type argument from the nullable // and check if it is of enum type if (switchExpressionType != null) switchExpressionType = switchExpressionType.IsNullable(out var underlyingType) ? underlyingType : switchExpressionType; if (switchExpressionType?.TypeKind == TypeKind.Enum) { var enumMembers = new Dictionary<long, ISymbol>(); if (PopulateSwitchStatementHelpers.TryGetAllEnumMembers(switchExpressionType, enumMembers)) { RemoveExistingEnumMembers(operation, enumMembers); return enumMembers.Values; } } return SpecializedCollections.EmptyCollection<ISymbol>(); } private static void RemoveExistingEnumMembers( ISwitchExpressionOperation operation, Dictionary<long, ISymbol> enumMembers) { foreach (var arm in operation.Arms) { RemoveIfConstantPatternHasValue(arm.Pattern, enumMembers); if (arm.Pattern is IBinaryPatternOperation binaryPattern) { HandleBinaryPattern(binaryPattern, enumMembers); } } } private static void HandleBinaryPattern(IBinaryPatternOperation? binaryPattern, Dictionary<long, ISymbol> enumMembers) { if (binaryPattern?.OperatorKind == BinaryOperatorKind.Or) { RemoveIfConstantPatternHasValue(binaryPattern.LeftPattern, enumMembers); RemoveIfConstantPatternHasValue(binaryPattern.RightPattern, enumMembers); HandleBinaryPattern(binaryPattern.LeftPattern as IBinaryPatternOperation, enumMembers); HandleBinaryPattern(binaryPattern.RightPattern as IBinaryPatternOperation, enumMembers); } } private static void RemoveIfConstantPatternHasValue(IOperation operation, Dictionary<long, ISymbol> enumMembers) { if (operation is IConstantPatternOperation { Value: { ConstantValue: { HasValue: true, Value: var value } } }) enumMembers.Remove(IntegerUtilities.ToInt64(value)); } public static bool HasDefaultCase(ISwitchExpressionOperation operation) => operation.Arms.Any(a => IsDefault(a)); public static bool IsDefault(ISwitchExpressionArmOperation arm) { if (arm.Pattern.Kind == OperationKind.DiscardPattern) return true; if (arm.Pattern is IDeclarationPatternOperation declarationPattern) return declarationPattern.MatchesNull; 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.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.PopulateSwitch { internal static class PopulateSwitchExpressionHelpers { public static ICollection<ISymbol> GetMissingEnumMembers(ISwitchExpressionOperation operation) { var switchExpression = operation.Value; var switchExpressionType = switchExpression?.Type; // Check if the type of the expression is a nullable INamedTypeSymbol // if the type is both nullable and an INamedTypeSymbol extract the type argument from the nullable // and check if it is of enum type if (switchExpressionType != null) switchExpressionType = switchExpressionType.IsNullable(out var underlyingType) ? underlyingType : switchExpressionType; if (switchExpressionType?.TypeKind == TypeKind.Enum) { var enumMembers = new Dictionary<long, ISymbol>(); if (PopulateSwitchStatementHelpers.TryGetAllEnumMembers(switchExpressionType, enumMembers)) { RemoveExistingEnumMembers(operation, enumMembers); return enumMembers.Values; } } return SpecializedCollections.EmptyCollection<ISymbol>(); } private static void RemoveExistingEnumMembers( ISwitchExpressionOperation operation, Dictionary<long, ISymbol> enumMembers) { foreach (var arm in operation.Arms) { RemoveIfConstantPatternHasValue(arm.Pattern, enumMembers); if (arm.Pattern is IBinaryPatternOperation binaryPattern) { HandleBinaryPattern(binaryPattern, enumMembers); } } } private static void HandleBinaryPattern(IBinaryPatternOperation? binaryPattern, Dictionary<long, ISymbol> enumMembers) { if (binaryPattern?.OperatorKind == BinaryOperatorKind.Or) { RemoveIfConstantPatternHasValue(binaryPattern.LeftPattern, enumMembers); RemoveIfConstantPatternHasValue(binaryPattern.RightPattern, enumMembers); HandleBinaryPattern(binaryPattern.LeftPattern as IBinaryPatternOperation, enumMembers); HandleBinaryPattern(binaryPattern.RightPattern as IBinaryPatternOperation, enumMembers); } } private static void RemoveIfConstantPatternHasValue(IOperation operation, Dictionary<long, ISymbol> enumMembers) { if (operation is IConstantPatternOperation { Value: { ConstantValue: { HasValue: true, Value: var value } } }) enumMembers.Remove(IntegerUtilities.ToInt64(value)); } public static bool HasDefaultCase(ISwitchExpressionOperation operation) => operation.Arms.Any(a => IsDefault(a)); public static bool IsDefault(ISwitchExpressionArmOperation arm) { if (arm.Pattern.Kind == OperationKind.DiscardPattern) return true; if (arm.Pattern is IDeclarationPatternOperation declarationPattern) return declarationPattern.MatchesNull; return false; } } }
-1
dotnet/roslyn
56,095
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-02T00:01:28Z"
"2021-09-02T01:47:21Z"
212ca8da034e484813ea99027c29cc3f6405fe1f
fe389d485fb73f8186b32636bfc747a39a70b028
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/Core/IOptionPageService.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.Host; namespace Microsoft.CodeAnalysis.Editor { internal interface IOptionPageService : ILanguageService { void ShowFormattingOptionPage(); } }
// Licensed to the .NET Foundation under one or more 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.Host; namespace Microsoft.CodeAnalysis.Editor { internal interface IOptionPageService : ILanguageService { void ShowFormattingOptionPage(); } }
-1
dotnet/roslyn
56,095
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-02T00:01:28Z"
"2021-09-02T01:47:21Z"
212ca8da034e484813ea99027c29cc3f6405fe1f
fe389d485fb73f8186b32636bfc747a39a70b028
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/Remote/Core/ExternalAccess/Pythia/Api/PythiaRemoteServiceCallbackIdWrapper.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.Runtime.Serialization; using Microsoft.CodeAnalysis.Remote; namespace Microsoft.CodeAnalysis.ExternalAccess.Pythia.Api { [DataContract] internal readonly struct PythiaRemoteServiceCallbackIdWrapper { [DataMember(Order = 0)] internal RemoteServiceCallbackId UnderlyingObject { get; } public PythiaRemoteServiceCallbackIdWrapper(RemoteServiceCallbackId underlyingObject) => UnderlyingObject = underlyingObject; public static implicit operator PythiaRemoteServiceCallbackIdWrapper(RemoteServiceCallbackId id) => new(id); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.Serialization; using Microsoft.CodeAnalysis.Remote; namespace Microsoft.CodeAnalysis.ExternalAccess.Pythia.Api { [DataContract] internal readonly struct PythiaRemoteServiceCallbackIdWrapper { [DataMember(Order = 0)] internal RemoteServiceCallbackId UnderlyingObject { get; } public PythiaRemoteServiceCallbackIdWrapper(RemoteServiceCallbackId underlyingObject) => UnderlyingObject = underlyingObject; public static implicit operator PythiaRemoteServiceCallbackIdWrapper(RemoteServiceCallbackId id) => new(id); } }
-1
dotnet/roslyn
56,095
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-02T00:01:28Z"
"2021-09-02T01:47:21Z"
212ca8da034e484813ea99027c29cc3f6405fe1f
fe389d485fb73f8186b32636bfc747a39a70b028
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/Core/Portable/Collections/CachingFactory.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; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { // Implements simple cache of limited size that could hold // a number of previously created/mapped items. // // These caches do not grow or shrink and need no rehashing // Maximum size of a cache is set at construction. // Items are inserted at locations that correspond to the hash code of the item // New item displaces anything that previously used the same slot. // // Cache needs to know 3 functions: // keyHash - maps a key to a hashcode. // // keyValueEquality - compares key and a value and figures if the value could have been created using same key. // NOTE: it does not compare two keys. // The assumption is that value's key could be inferred from the value so we do not want to store it. // We also do not want to pass in the new value as the whole purpose of the cache is to avoid creating // a new instance if cached one can be used. // // valueFactory - creates a new value from a key. Needed only in GetOrMakeValue. // in a case where it is not possible to create a static valueFactory, it is advisable // to set valueFactory to null and use TryGetValue/Add pattern instead of GetOrMakeValue. // internal class CachingFactory<TKey, TValue> : CachingBase<CachingFactory<TKey, TValue>.Entry> where TKey : notnull { internal struct Entry { internal int hash; internal TValue value; } private readonly int _size; private readonly Func<TKey, TValue> _valueFactory; private readonly Func<TKey, int> _keyHash; private readonly Func<TKey, TValue, bool> _keyValueEquality; public CachingFactory(int size, Func<TKey, TValue> valueFactory, Func<TKey, int> keyHash, Func<TKey, TValue, bool> keyValueEquality) : base(size) { _size = size; _valueFactory = valueFactory; _keyHash = keyHash; _keyValueEquality = keyValueEquality; } public void Add(TKey key, TValue value) { var hash = GetKeyHash(key); var idx = hash & mask; entries[idx].hash = hash; entries[idx].value = value; } public bool TryGetValue(TKey key, [MaybeNullWhen(returnValue: false)] out TValue value) { int hash = GetKeyHash(key); int idx = hash & mask; var entries = this.entries; if (entries[idx].hash == hash) { var candidate = entries[idx].value; if (_keyValueEquality(key, candidate)) { value = candidate; return true; } } value = default!; return false; } public TValue GetOrMakeValue(TKey key) { int hash = GetKeyHash(key); int idx = hash & mask; var entries = this.entries; if (entries[idx].hash == hash) { var candidate = entries[idx].value; if (_keyValueEquality(key, candidate)) { return candidate; } } var value = _valueFactory(key); entries[idx].hash = hash; entries[idx].value = value; return value; } private int GetKeyHash(TKey key) { // Ensure result is non-zero to avoid // treating an empty entry as valid. int result = _keyHash(key) | _size; Debug.Assert(result != 0); return result; } } // special case for a situation where the key is a reference type with object identity // in this case: // keyHash is assumed to be RuntimeHelpers.GetHashCode // keyValueEquality is an object == for the new and old keys // NOTE: we do store the key in this case // reference comparison of keys is as cheap as comparing hash codes. internal class CachingIdentityFactory<TKey, TValue> : CachingBase<CachingIdentityFactory<TKey, TValue>.Entry> where TKey : class { private readonly Func<TKey, TValue> _valueFactory; private readonly ObjectPool<CachingIdentityFactory<TKey, TValue>>? _pool; internal struct Entry { internal TKey key; internal TValue value; } public CachingIdentityFactory(int size, Func<TKey, TValue> valueFactory) : base(size) { _valueFactory = valueFactory; } public CachingIdentityFactory(int size, Func<TKey, TValue> valueFactory, ObjectPool<CachingIdentityFactory<TKey, TValue>> pool) : this(size, valueFactory) { _pool = pool; } public void Add(TKey key, TValue value) { var hash = RuntimeHelpers.GetHashCode(key); var idx = hash & mask; entries[idx].key = key; entries[idx].value = value; } public bool TryGetValue(TKey key, [MaybeNullWhen(returnValue: false)] out TValue value) { int hash = RuntimeHelpers.GetHashCode(key); int idx = hash & mask; var entries = this.entries; if ((object)entries[idx].key == (object)key) { value = entries[idx].value; return true; } value = default!; return false; } public TValue GetOrMakeValue(TKey key) { int hash = RuntimeHelpers.GetHashCode(key); int idx = hash & mask; var entries = this.entries; if ((object)entries[idx].key == (object)key) { return entries[idx].value; } var value = _valueFactory(key); entries[idx].key = key; entries[idx].value = value; return value; } // if someone needs to create a pool; public static ObjectPool<CachingIdentityFactory<TKey, TValue>> CreatePool(int size, Func<TKey, TValue> valueFactory) { var pool = new ObjectPool<CachingIdentityFactory<TKey, TValue>>( pool => new CachingIdentityFactory<TKey, TValue>(size, valueFactory, pool), Environment.ProcessorCount * 2); return pool; } public void Free() { var pool = _pool; // Array.Clear(this.entries, 0, this.entries.Length); pool?.Free(this); } } // Just holds the data for the derived caches. internal abstract class CachingBase<TEntry> { // cache size is always ^2. // items are placed at [hash ^ mask] // new item will displace previous one at the same location. protected readonly int mask; protected readonly TEntry[] entries; internal CachingBase(int size) { var alignedSize = AlignSize(size); this.mask = alignedSize - 1; this.entries = new TEntry[alignedSize]; } private static int AlignSize(int size) { Debug.Assert(size > 0); size--; size |= size >> 1; size |= size >> 2; size |= size >> 4; size |= size >> 8; size |= size >> 16; return size + 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. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { // Implements simple cache of limited size that could hold // a number of previously created/mapped items. // // These caches do not grow or shrink and need no rehashing // Maximum size of a cache is set at construction. // Items are inserted at locations that correspond to the hash code of the item // New item displaces anything that previously used the same slot. // // Cache needs to know 3 functions: // keyHash - maps a key to a hashcode. // // keyValueEquality - compares key and a value and figures if the value could have been created using same key. // NOTE: it does not compare two keys. // The assumption is that value's key could be inferred from the value so we do not want to store it. // We also do not want to pass in the new value as the whole purpose of the cache is to avoid creating // a new instance if cached one can be used. // // valueFactory - creates a new value from a key. Needed only in GetOrMakeValue. // in a case where it is not possible to create a static valueFactory, it is advisable // to set valueFactory to null and use TryGetValue/Add pattern instead of GetOrMakeValue. // internal class CachingFactory<TKey, TValue> : CachingBase<CachingFactory<TKey, TValue>.Entry> where TKey : notnull { internal struct Entry { internal int hash; internal TValue value; } private readonly int _size; private readonly Func<TKey, TValue> _valueFactory; private readonly Func<TKey, int> _keyHash; private readonly Func<TKey, TValue, bool> _keyValueEquality; public CachingFactory(int size, Func<TKey, TValue> valueFactory, Func<TKey, int> keyHash, Func<TKey, TValue, bool> keyValueEquality) : base(size) { _size = size; _valueFactory = valueFactory; _keyHash = keyHash; _keyValueEquality = keyValueEquality; } public void Add(TKey key, TValue value) { var hash = GetKeyHash(key); var idx = hash & mask; entries[idx].hash = hash; entries[idx].value = value; } public bool TryGetValue(TKey key, [MaybeNullWhen(returnValue: false)] out TValue value) { int hash = GetKeyHash(key); int idx = hash & mask; var entries = this.entries; if (entries[idx].hash == hash) { var candidate = entries[idx].value; if (_keyValueEquality(key, candidate)) { value = candidate; return true; } } value = default!; return false; } public TValue GetOrMakeValue(TKey key) { int hash = GetKeyHash(key); int idx = hash & mask; var entries = this.entries; if (entries[idx].hash == hash) { var candidate = entries[idx].value; if (_keyValueEquality(key, candidate)) { return candidate; } } var value = _valueFactory(key); entries[idx].hash = hash; entries[idx].value = value; return value; } private int GetKeyHash(TKey key) { // Ensure result is non-zero to avoid // treating an empty entry as valid. int result = _keyHash(key) | _size; Debug.Assert(result != 0); return result; } } // special case for a situation where the key is a reference type with object identity // in this case: // keyHash is assumed to be RuntimeHelpers.GetHashCode // keyValueEquality is an object == for the new and old keys // NOTE: we do store the key in this case // reference comparison of keys is as cheap as comparing hash codes. internal class CachingIdentityFactory<TKey, TValue> : CachingBase<CachingIdentityFactory<TKey, TValue>.Entry> where TKey : class { private readonly Func<TKey, TValue> _valueFactory; private readonly ObjectPool<CachingIdentityFactory<TKey, TValue>>? _pool; internal struct Entry { internal TKey key; internal TValue value; } public CachingIdentityFactory(int size, Func<TKey, TValue> valueFactory) : base(size) { _valueFactory = valueFactory; } public CachingIdentityFactory(int size, Func<TKey, TValue> valueFactory, ObjectPool<CachingIdentityFactory<TKey, TValue>> pool) : this(size, valueFactory) { _pool = pool; } public void Add(TKey key, TValue value) { var hash = RuntimeHelpers.GetHashCode(key); var idx = hash & mask; entries[idx].key = key; entries[idx].value = value; } public bool TryGetValue(TKey key, [MaybeNullWhen(returnValue: false)] out TValue value) { int hash = RuntimeHelpers.GetHashCode(key); int idx = hash & mask; var entries = this.entries; if ((object)entries[idx].key == (object)key) { value = entries[idx].value; return true; } value = default!; return false; } public TValue GetOrMakeValue(TKey key) { int hash = RuntimeHelpers.GetHashCode(key); int idx = hash & mask; var entries = this.entries; if ((object)entries[idx].key == (object)key) { return entries[idx].value; } var value = _valueFactory(key); entries[idx].key = key; entries[idx].value = value; return value; } // if someone needs to create a pool; public static ObjectPool<CachingIdentityFactory<TKey, TValue>> CreatePool(int size, Func<TKey, TValue> valueFactory) { var pool = new ObjectPool<CachingIdentityFactory<TKey, TValue>>( pool => new CachingIdentityFactory<TKey, TValue>(size, valueFactory, pool), Environment.ProcessorCount * 2); return pool; } public void Free() { var pool = _pool; // Array.Clear(this.entries, 0, this.entries.Length); pool?.Free(this); } } // Just holds the data for the derived caches. internal abstract class CachingBase<TEntry> { // cache size is always ^2. // items are placed at [hash ^ mask] // new item will displace previous one at the same location. protected readonly int mask; protected readonly TEntry[] entries; internal CachingBase(int size) { var alignedSize = AlignSize(size); this.mask = alignedSize - 1; this.entries = new TEntry[alignedSize]; } private static int AlignSize(int size) { Debug.Assert(size > 0); size--; size |= size >> 1; size |= size >> 2; size |= size >> 4; size |= size >> 8; size |= size >> 16; return size + 1; } } }
-1
dotnet/roslyn
56,095
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-02T00:01:28Z"
"2021-09-02T01:47:21Z"
212ca8da034e484813ea99027c29cc3f6405fe1f
fe389d485fb73f8186b32636bfc747a39a70b028
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/VisualBasic/Portable/Symbols/Source/SourceLabelSymbol.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 Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Diagnostics Imports System.Linq Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend NotInheritable Class SourceLabelSymbol Inherits LabelSymbol Private ReadOnly _labelName As SyntaxToken ' the label name token, this can be an identifier or an integer literal. This is used as its location. Private ReadOnly _containingMethod As MethodSymbol Private ReadOnly _binder As Binder Public Sub New(labelNameToken As SyntaxToken, containingMethod As MethodSymbol, binder As Binder) ' Note: use the same method here to get the name as in Binder.BindLabelStatement when looking up the label ' Explanation: some methods do not add the type character and return e.g. C for C$ (e.g. GetIdentifierText()) MyBase.New(labelNameToken.ValueText) Debug.Assert(labelNameToken.Kind = SyntaxKind.IdentifierToken OrElse labelNameToken.Kind = SyntaxKind.IntegerLiteralToken) _labelName = labelNameToken _containingMethod = containingMethod _binder = binder End Sub ' Get the token that defined this label symbol. This is useful for robustly checking ' if a label symbol actually matches a particular definition, even in the presence of duplicates. Friend Overrides ReadOnly Property LabelName As SyntaxToken Get Return _labelName End Get End Property Public Overrides ReadOnly Property ContainingMethod As MethodSymbol Get Return _containingMethod End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _containingMethod End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return ImmutableArray.Create(Of Location)(_labelName.GetLocation()) End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Dim parentNode = _labelName.Parent Debug.Assert(TypeOf parentNode Is LabelStatementSyntax) Return ImmutableArray.Create(Of SyntaxReference)(DirectCast(parentNode.GetReference(), SyntaxReference)) End Get End Property Public Overrides Function Equals(obj As Object) As Boolean If obj Is Me Then Return True End If Dim symbol = TryCast(obj, SourceLabelSymbol) Return symbol IsNot Nothing AndAlso symbol._labelName.Equals(Me._labelName) AndAlso Equals(symbol._containingMethod, Me._containingMethod) End Function Public Overrides Function GetHashCode() As Integer Return Me._labelName.GetHashCode() 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 Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Diagnostics Imports System.Linq Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend NotInheritable Class SourceLabelSymbol Inherits LabelSymbol Private ReadOnly _labelName As SyntaxToken ' the label name token, this can be an identifier or an integer literal. This is used as its location. Private ReadOnly _containingMethod As MethodSymbol Private ReadOnly _binder As Binder Public Sub New(labelNameToken As SyntaxToken, containingMethod As MethodSymbol, binder As Binder) ' Note: use the same method here to get the name as in Binder.BindLabelStatement when looking up the label ' Explanation: some methods do not add the type character and return e.g. C for C$ (e.g. GetIdentifierText()) MyBase.New(labelNameToken.ValueText) Debug.Assert(labelNameToken.Kind = SyntaxKind.IdentifierToken OrElse labelNameToken.Kind = SyntaxKind.IntegerLiteralToken) _labelName = labelNameToken _containingMethod = containingMethod _binder = binder End Sub ' Get the token that defined this label symbol. This is useful for robustly checking ' if a label symbol actually matches a particular definition, even in the presence of duplicates. Friend Overrides ReadOnly Property LabelName As SyntaxToken Get Return _labelName End Get End Property Public Overrides ReadOnly Property ContainingMethod As MethodSymbol Get Return _containingMethod End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _containingMethod End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return ImmutableArray.Create(Of Location)(_labelName.GetLocation()) End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Dim parentNode = _labelName.Parent Debug.Assert(TypeOf parentNode Is LabelStatementSyntax) Return ImmutableArray.Create(Of SyntaxReference)(DirectCast(parentNode.GetReference(), SyntaxReference)) End Get End Property Public Overrides Function Equals(obj As Object) As Boolean If obj Is Me Then Return True End If Dim symbol = TryCast(obj, SourceLabelSymbol) Return symbol IsNot Nothing AndAlso symbol._labelName.Equals(Me._labelName) AndAlso Equals(symbol._containingMethod, Me._containingMethod) End Function Public Overrides Function GetHashCode() As Integer Return Me._labelName.GetHashCode() End Function End Class End Namespace
-1
dotnet/roslyn
56,095
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-02T00:01:28Z"
"2021-09-02T01:47:21Z"
212ca8da034e484813ea99027c29cc3f6405fe1f
fe389d485fb73f8186b32636bfc747a39a70b028
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/Core/Portable/Diagnostics/DiagnosticService.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.Composition; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Common; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.TestHooks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { [Export(typeof(IDiagnosticService)), Shared] internal partial class DiagnosticService : IDiagnosticService { private const string DiagnosticsUpdatedEventName = "DiagnosticsUpdated"; private readonly EventMap _eventMap; private readonly TaskQueue _eventQueue; private readonly object _gate; private readonly Dictionary<IDiagnosticUpdateSource, Dictionary<Workspace, Dictionary<object, Data>>> _map; private readonly EventListenerTracker<IDiagnosticService> _eventListenerTracker; private ImmutableHashSet<IDiagnosticUpdateSource> _updateSources; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DiagnosticService( IAsynchronousOperationListenerProvider listenerProvider, [ImportMany] IEnumerable<Lazy<IEventListener, EventListenerMetadata>> eventListeners) { // we use registry service rather than doing MEF import since MEF import method can have race issue where // update source gets created before aggregator - diagnostic service - is created and we will lose events fired before // the aggregator is created. _updateSources = ImmutableHashSet<IDiagnosticUpdateSource>.Empty; // queue to serialize events. _eventMap = new EventMap(); _eventQueue = new TaskQueue(listenerProvider.GetListener(FeatureAttribute.DiagnosticService), TaskScheduler.Default); _gate = new object(); _map = new Dictionary<IDiagnosticUpdateSource, Dictionary<Workspace, Dictionary<object, Data>>>(); _eventListenerTracker = new EventListenerTracker<IDiagnosticService>(eventListeners, WellKnownEventListeners.DiagnosticService); } public event EventHandler<DiagnosticsUpdatedArgs> DiagnosticsUpdated { add { _eventMap.AddEventHandler(DiagnosticsUpdatedEventName, value); } remove { _eventMap.RemoveEventHandler(DiagnosticsUpdatedEventName, value); } } private void RaiseDiagnosticsUpdated(IDiagnosticUpdateSource source, DiagnosticsUpdatedArgs args) { _eventListenerTracker.EnsureEventListener(args.Workspace, this); var ev = _eventMap.GetEventHandlers<EventHandler<DiagnosticsUpdatedArgs>>(DiagnosticsUpdatedEventName); _eventQueue.ScheduleTask(DiagnosticsUpdatedEventName, () => { if (!UpdateDataMap(source, args)) { // there is no change, nothing to raise events for. return; } ev.RaiseEvent(handler => handler(source, args)); }, CancellationToken.None); } private void RaiseDiagnosticsCleared(IDiagnosticUpdateSource source) { var ev = _eventMap.GetEventHandlers<EventHandler<DiagnosticsUpdatedArgs>>(DiagnosticsUpdatedEventName); _eventQueue.ScheduleTask(DiagnosticsUpdatedEventName, () => { using var pooledObject = SharedPools.Default<List<DiagnosticsUpdatedArgs>>().GetPooledObject(); var removed = pooledObject.Object; if (!ClearDiagnosticsReportedBySource(source, removed)) { // there is no change, nothing to raise events for. return; } // don't create event listener if it haven't created yet. if there is a diagnostic to remove // listener should have already created since all events are done in the serialized queue foreach (var args in removed) { ev.RaiseEvent(handler => handler(source, args)); } }, CancellationToken.None); } private bool UpdateDataMap(IDiagnosticUpdateSource source, DiagnosticsUpdatedArgs args) { // we expect source who uses this ability to have small number of diagnostics. lock (_gate) { Debug.Assert(_updateSources.Contains(source)); // The diagnostic service itself caches all diagnostics produced by the IDiagnosticUpdateSource's. As // such, we want to grab all the diagnostics (regardless of push/pull setting) and cache inside // ourselves. Later, when anyone calls GetDiagnostics or GetDiagnosticBuckets we will check if their // push/pull request matches the current user setting and return these if appropriate. var diagnostics = args.GetAllDiagnosticsRegardlessOfPushPullSetting(); // check cheap early bail out if (diagnostics.Length == 0 && !_map.ContainsKey(source)) { // no new diagnostic, and we don't have update source for it. return false; } // 2 different workspaces (ex, PreviewWorkspaces) can return same Args.Id, we need to // distinguish them. so we separate diagnostics per workspace map. var workspaceMap = _map.GetOrAdd(source, _ => new Dictionary<Workspace, Dictionary<object, Data>>()); if (diagnostics.Length == 0 && !workspaceMap.ContainsKey(args.Workspace)) { // no new diagnostic, and we don't have workspace for it. return false; } var diagnosticDataMap = workspaceMap.GetOrAdd(args.Workspace, _ => new Dictionary<object, Data>()); diagnosticDataMap.Remove(args.Id); if (diagnosticDataMap.Count == 0 && diagnostics.Length == 0) { workspaceMap.Remove(args.Workspace); if (workspaceMap.Count == 0) { _map.Remove(source); } return true; } if (diagnostics.Length > 0) { // save data only if there is a diagnostic var data = source.SupportGetDiagnostics ? new Data(args) : new Data(args, diagnostics); diagnosticDataMap.Add(args.Id, data); } return true; } } private bool ClearDiagnosticsReportedBySource(IDiagnosticUpdateSource source, List<DiagnosticsUpdatedArgs> removed) { // we expect source who uses this ability to have small number of diagnostics. lock (_gate) { Debug.Assert(_updateSources.Contains(source)); // 2 different workspaces (ex, PreviewWorkspaces) can return same Args.Id, we need to // distinguish them. so we separate diagnostics per workspace map. if (!_map.TryGetValue(source, out var workspaceMap)) { return false; } foreach (var (workspace, map) in workspaceMap) { foreach (var (id, data) in map) { removed.Add(DiagnosticsUpdatedArgs.DiagnosticsRemoved(id, data.Workspace, solution: null, data.ProjectId, data.DocumentId)); } } // all diagnostics from the source is cleared _map.Remove(source); return true; } } private void OnDiagnosticsUpdated(object sender, DiagnosticsUpdatedArgs e) { AssertIfNull(e.GetAllDiagnosticsRegardlessOfPushPullSetting()); // all events are serialized by async event handler RaiseDiagnosticsUpdated((IDiagnosticUpdateSource)sender, e); } private void OnCleared(object sender, EventArgs e) { // all events are serialized by async event handler RaiseDiagnosticsCleared((IDiagnosticUpdateSource)sender); } [Obsolete] ImmutableArray<DiagnosticData> IDiagnosticService.GetDiagnostics(Workspace workspace, ProjectId projectId, DocumentId documentId, object id, bool includeSuppressedDiagnostics, CancellationToken cancellationToken) => GetPushDiagnosticsAsync(workspace, projectId, documentId, id, includeSuppressedDiagnostics, InternalDiagnosticsOptions.NormalDiagnosticMode, cancellationToken).AsTask().WaitAndGetResult_CanCallOnBackground(cancellationToken); public ValueTask<ImmutableArray<DiagnosticData>> GetPullDiagnosticsAsync(Workspace workspace, ProjectId projectId, DocumentId documentId, object id, bool includeSuppressedDiagnostics, Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken) => GetDiagnosticsAsync(workspace, projectId, documentId, id, includeSuppressedDiagnostics, forPullDiagnostics: true, diagnosticMode, cancellationToken); public ValueTask<ImmutableArray<DiagnosticData>> GetPushDiagnosticsAsync(Workspace workspace, ProjectId projectId, DocumentId documentId, object id, bool includeSuppressedDiagnostics, Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken) => GetDiagnosticsAsync(workspace, projectId, documentId, id, includeSuppressedDiagnostics, forPullDiagnostics: false, diagnosticMode, cancellationToken); private ValueTask<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync( Workspace workspace, ProjectId projectId, DocumentId documentId, object id, bool includeSuppressedDiagnostics, bool forPullDiagnostics, Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken) { // If this is a pull client, but pull diagnostics is not on, then they get nothing. Similarly, if this is a // push client and pull diagnostics are on, they get nothing. var isPull = workspace.IsPullDiagnostics(diagnosticMode); if (forPullDiagnostics != isPull) return new ValueTask<ImmutableArray<DiagnosticData>>(ImmutableArray<DiagnosticData>.Empty); if (id != null) { // get specific one return GetSpecificDiagnosticsAsync(workspace, projectId, documentId, id, includeSuppressedDiagnostics, cancellationToken); } // get aggregated ones return GetDiagnosticsAsync(workspace, projectId, documentId, includeSuppressedDiagnostics, cancellationToken); } private async ValueTask<ImmutableArray<DiagnosticData>> GetSpecificDiagnosticsAsync(Workspace workspace, ProjectId projectId, DocumentId documentId, object id, bool includeSuppressedDiagnostics, CancellationToken cancellationToken) { using var _ = ArrayBuilder<Data>.GetInstance(out var buffer); foreach (var source in _updateSources) { cancellationToken.ThrowIfCancellationRequested(); buffer.Clear(); if (source.SupportGetDiagnostics) { var diagnostics = await source.GetDiagnosticsAsync(workspace, projectId, documentId, id, includeSuppressedDiagnostics, cancellationToken).ConfigureAwait(false); if (diagnostics.Length > 0) return diagnostics; } else { AppendMatchingData(source, workspace, projectId, documentId, id, buffer); Debug.Assert(buffer.Count is 0 or 1); if (buffer.Count == 1) { var diagnostics = buffer[0].Diagnostics; return includeSuppressedDiagnostics ? diagnostics : diagnostics.NullToEmpty().WhereAsArray(d => !d.IsSuppressed); } } } return ImmutableArray<DiagnosticData>.Empty; } private async ValueTask<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync( Workspace workspace, ProjectId projectId, DocumentId documentId, bool includeSuppressedDiagnostics, CancellationToken cancellationToken) { using var _1 = ArrayBuilder<DiagnosticData>.GetInstance(out var result); using var _2 = ArrayBuilder<Data>.GetInstance(out var buffer); foreach (var source in _updateSources) { cancellationToken.ThrowIfCancellationRequested(); buffer.Clear(); if (source.SupportGetDiagnostics) { result.AddRange(await source.GetDiagnosticsAsync(workspace, projectId, documentId, id: null, includeSuppressedDiagnostics, cancellationToken).ConfigureAwait(false)); } else { AppendMatchingData(source, workspace, projectId, documentId, id: null, buffer); foreach (var data in buffer) { foreach (var diagnostic in data.Diagnostics) { AssertIfNull(diagnostic); if (includeSuppressedDiagnostics || !diagnostic.IsSuppressed) result.Add(diagnostic); } } } } return result.ToImmutable(); } public ImmutableArray<DiagnosticBucket> GetPullDiagnosticBuckets(Workspace workspace, ProjectId projectId, DocumentId documentId, Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken) => GetDiagnosticBuckets(workspace, projectId, documentId, forPullDiagnostics: true, diagnosticMode, cancellationToken); public ImmutableArray<DiagnosticBucket> GetPushDiagnosticBuckets(Workspace workspace, ProjectId projectId, DocumentId documentId, Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken) => GetDiagnosticBuckets(workspace, projectId, documentId, forPullDiagnostics: false, diagnosticMode, cancellationToken); private ImmutableArray<DiagnosticBucket> GetDiagnosticBuckets( Workspace workspace, ProjectId projectId, DocumentId documentId, bool forPullDiagnostics, Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken) { // If this is a pull client, but pull diagnostics is not on, then they get nothing. Similarly, if this is a // push client and pull diagnostics are on, they get nothing. var isPull = workspace.IsPullDiagnostics(diagnosticMode); if (forPullDiagnostics != isPull) return ImmutableArray<DiagnosticBucket>.Empty; using var _1 = ArrayBuilder<DiagnosticBucket>.GetInstance(out var result); using var _2 = ArrayBuilder<Data>.GetInstance(out var buffer); foreach (var source in _updateSources) { buffer.Clear(); cancellationToken.ThrowIfCancellationRequested(); AppendMatchingData(source, workspace, projectId, documentId, id: null, buffer); foreach (var data in buffer) result.Add(new DiagnosticBucket(data.Id, data.Workspace, data.ProjectId, data.DocumentId)); } return result.ToImmutable(); } private void AppendMatchingData( IDiagnosticUpdateSource source, Workspace workspace, ProjectId projectId, DocumentId documentId, object id, ArrayBuilder<Data> list) { Contract.ThrowIfNull(workspace); lock (_gate) { if (!_map.TryGetValue(source, out var workspaceMap) || !workspaceMap.TryGetValue(workspace, out var current)) { return; } if (id != null) { if (current.TryGetValue(id, out var data)) { list.Add(data); } return; } foreach (var data in current.Values) { if (TryAddData(workspace, documentId, data, d => d.DocumentId, list) || TryAddData(workspace, projectId, data, d => d.ProjectId, list) || TryAddData(workspace, workspace, data, d => d.Workspace, list)) { continue; } } } } private static bool TryAddData<T>(Workspace workspace, T key, Data data, Func<Data, T> keyGetter, ArrayBuilder<Data> result) where T : class { if (key == null) { return false; } // make sure data is from same workspace. project/documentId can be shared between 2 different workspace if (workspace != data.Workspace) { return false; } if (key == keyGetter(data)) { result.Add(data); } return true; } [Conditional("DEBUG")] private static void AssertIfNull(ImmutableArray<DiagnosticData> diagnostics) { for (var i = 0; i < diagnostics.Length; i++) { AssertIfNull(diagnostics[i]); } } [Conditional("DEBUG")] private static void AssertIfNull<T>(T obj) where T : class { if (obj == null) { Debug.Assert(false, "who returns invalid data?"); } } private readonly struct Data { public readonly Workspace Workspace; public readonly ProjectId ProjectId; public readonly DocumentId DocumentId; public readonly object Id; public readonly ImmutableArray<DiagnosticData> Diagnostics; public Data(UpdatedEventArgs args) : this(args, ImmutableArray<DiagnosticData>.Empty) { } public Data(UpdatedEventArgs args, ImmutableArray<DiagnosticData> diagnostics) { Workspace = args.Workspace; ProjectId = args.ProjectId; DocumentId = args.DocumentId; Id = args.Id; Diagnostics = diagnostics; } } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly DiagnosticService _diagnosticService; internal TestAccessor(DiagnosticService diagnosticService) => _diagnosticService = diagnosticService; internal ref readonly EventListenerTracker<IDiagnosticService> EventListenerTracker => ref _diagnosticService._eventListenerTracker; } } }
// Licensed to the .NET Foundation under one or more 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.Composition; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Common; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.TestHooks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { [Export(typeof(IDiagnosticService)), Shared] internal partial class DiagnosticService : IDiagnosticService { private const string DiagnosticsUpdatedEventName = "DiagnosticsUpdated"; private readonly EventMap _eventMap; private readonly TaskQueue _eventQueue; private readonly object _gate; private readonly Dictionary<IDiagnosticUpdateSource, Dictionary<Workspace, Dictionary<object, Data>>> _map; private readonly EventListenerTracker<IDiagnosticService> _eventListenerTracker; private ImmutableHashSet<IDiagnosticUpdateSource> _updateSources; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DiagnosticService( IAsynchronousOperationListenerProvider listenerProvider, [ImportMany] IEnumerable<Lazy<IEventListener, EventListenerMetadata>> eventListeners) { // we use registry service rather than doing MEF import since MEF import method can have race issue where // update source gets created before aggregator - diagnostic service - is created and we will lose events fired before // the aggregator is created. _updateSources = ImmutableHashSet<IDiagnosticUpdateSource>.Empty; // queue to serialize events. _eventMap = new EventMap(); _eventQueue = new TaskQueue(listenerProvider.GetListener(FeatureAttribute.DiagnosticService), TaskScheduler.Default); _gate = new object(); _map = new Dictionary<IDiagnosticUpdateSource, Dictionary<Workspace, Dictionary<object, Data>>>(); _eventListenerTracker = new EventListenerTracker<IDiagnosticService>(eventListeners, WellKnownEventListeners.DiagnosticService); } public event EventHandler<DiagnosticsUpdatedArgs> DiagnosticsUpdated { add { _eventMap.AddEventHandler(DiagnosticsUpdatedEventName, value); } remove { _eventMap.RemoveEventHandler(DiagnosticsUpdatedEventName, value); } } private void RaiseDiagnosticsUpdated(IDiagnosticUpdateSource source, DiagnosticsUpdatedArgs args) { _eventListenerTracker.EnsureEventListener(args.Workspace, this); var ev = _eventMap.GetEventHandlers<EventHandler<DiagnosticsUpdatedArgs>>(DiagnosticsUpdatedEventName); _eventQueue.ScheduleTask(DiagnosticsUpdatedEventName, () => { if (!UpdateDataMap(source, args)) { // there is no change, nothing to raise events for. return; } ev.RaiseEvent(handler => handler(source, args)); }, CancellationToken.None); } private void RaiseDiagnosticsCleared(IDiagnosticUpdateSource source) { var ev = _eventMap.GetEventHandlers<EventHandler<DiagnosticsUpdatedArgs>>(DiagnosticsUpdatedEventName); _eventQueue.ScheduleTask(DiagnosticsUpdatedEventName, () => { using var pooledObject = SharedPools.Default<List<DiagnosticsUpdatedArgs>>().GetPooledObject(); var removed = pooledObject.Object; if (!ClearDiagnosticsReportedBySource(source, removed)) { // there is no change, nothing to raise events for. return; } // don't create event listener if it haven't created yet. if there is a diagnostic to remove // listener should have already created since all events are done in the serialized queue foreach (var args in removed) { ev.RaiseEvent(handler => handler(source, args)); } }, CancellationToken.None); } private bool UpdateDataMap(IDiagnosticUpdateSource source, DiagnosticsUpdatedArgs args) { // we expect source who uses this ability to have small number of diagnostics. lock (_gate) { Debug.Assert(_updateSources.Contains(source)); // The diagnostic service itself caches all diagnostics produced by the IDiagnosticUpdateSource's. As // such, we want to grab all the diagnostics (regardless of push/pull setting) and cache inside // ourselves. Later, when anyone calls GetDiagnostics or GetDiagnosticBuckets we will check if their // push/pull request matches the current user setting and return these if appropriate. var diagnostics = args.GetAllDiagnosticsRegardlessOfPushPullSetting(); // check cheap early bail out if (diagnostics.Length == 0 && !_map.ContainsKey(source)) { // no new diagnostic, and we don't have update source for it. return false; } // 2 different workspaces (ex, PreviewWorkspaces) can return same Args.Id, we need to // distinguish them. so we separate diagnostics per workspace map. var workspaceMap = _map.GetOrAdd(source, _ => new Dictionary<Workspace, Dictionary<object, Data>>()); if (diagnostics.Length == 0 && !workspaceMap.ContainsKey(args.Workspace)) { // no new diagnostic, and we don't have workspace for it. return false; } var diagnosticDataMap = workspaceMap.GetOrAdd(args.Workspace, _ => new Dictionary<object, Data>()); diagnosticDataMap.Remove(args.Id); if (diagnosticDataMap.Count == 0 && diagnostics.Length == 0) { workspaceMap.Remove(args.Workspace); if (workspaceMap.Count == 0) { _map.Remove(source); } return true; } if (diagnostics.Length > 0) { // save data only if there is a diagnostic var data = source.SupportGetDiagnostics ? new Data(args) : new Data(args, diagnostics); diagnosticDataMap.Add(args.Id, data); } return true; } } private bool ClearDiagnosticsReportedBySource(IDiagnosticUpdateSource source, List<DiagnosticsUpdatedArgs> removed) { // we expect source who uses this ability to have small number of diagnostics. lock (_gate) { Debug.Assert(_updateSources.Contains(source)); // 2 different workspaces (ex, PreviewWorkspaces) can return same Args.Id, we need to // distinguish them. so we separate diagnostics per workspace map. if (!_map.TryGetValue(source, out var workspaceMap)) { return false; } foreach (var (workspace, map) in workspaceMap) { foreach (var (id, data) in map) { removed.Add(DiagnosticsUpdatedArgs.DiagnosticsRemoved(id, data.Workspace, solution: null, data.ProjectId, data.DocumentId)); } } // all diagnostics from the source is cleared _map.Remove(source); return true; } } private void OnDiagnosticsUpdated(object sender, DiagnosticsUpdatedArgs e) { AssertIfNull(e.GetAllDiagnosticsRegardlessOfPushPullSetting()); // all events are serialized by async event handler RaiseDiagnosticsUpdated((IDiagnosticUpdateSource)sender, e); } private void OnCleared(object sender, EventArgs e) { // all events are serialized by async event handler RaiseDiagnosticsCleared((IDiagnosticUpdateSource)sender); } [Obsolete] ImmutableArray<DiagnosticData> IDiagnosticService.GetDiagnostics(Workspace workspace, ProjectId projectId, DocumentId documentId, object id, bool includeSuppressedDiagnostics, CancellationToken cancellationToken) => GetPushDiagnosticsAsync(workspace, projectId, documentId, id, includeSuppressedDiagnostics, InternalDiagnosticsOptions.NormalDiagnosticMode, cancellationToken).AsTask().WaitAndGetResult_CanCallOnBackground(cancellationToken); public ValueTask<ImmutableArray<DiagnosticData>> GetPullDiagnosticsAsync(Workspace workspace, ProjectId projectId, DocumentId documentId, object id, bool includeSuppressedDiagnostics, Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken) => GetDiagnosticsAsync(workspace, projectId, documentId, id, includeSuppressedDiagnostics, forPullDiagnostics: true, diagnosticMode, cancellationToken); public ValueTask<ImmutableArray<DiagnosticData>> GetPushDiagnosticsAsync(Workspace workspace, ProjectId projectId, DocumentId documentId, object id, bool includeSuppressedDiagnostics, Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken) => GetDiagnosticsAsync(workspace, projectId, documentId, id, includeSuppressedDiagnostics, forPullDiagnostics: false, diagnosticMode, cancellationToken); private ValueTask<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync( Workspace workspace, ProjectId projectId, DocumentId documentId, object id, bool includeSuppressedDiagnostics, bool forPullDiagnostics, Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken) { // If this is a pull client, but pull diagnostics is not on, then they get nothing. Similarly, if this is a // push client and pull diagnostics are on, they get nothing. var isPull = workspace.IsPullDiagnostics(diagnosticMode); if (forPullDiagnostics != isPull) return new ValueTask<ImmutableArray<DiagnosticData>>(ImmutableArray<DiagnosticData>.Empty); if (id != null) { // get specific one return GetSpecificDiagnosticsAsync(workspace, projectId, documentId, id, includeSuppressedDiagnostics, cancellationToken); } // get aggregated ones return GetDiagnosticsAsync(workspace, projectId, documentId, includeSuppressedDiagnostics, cancellationToken); } private async ValueTask<ImmutableArray<DiagnosticData>> GetSpecificDiagnosticsAsync(Workspace workspace, ProjectId projectId, DocumentId documentId, object id, bool includeSuppressedDiagnostics, CancellationToken cancellationToken) { using var _ = ArrayBuilder<Data>.GetInstance(out var buffer); foreach (var source in _updateSources) { cancellationToken.ThrowIfCancellationRequested(); buffer.Clear(); if (source.SupportGetDiagnostics) { var diagnostics = await source.GetDiagnosticsAsync(workspace, projectId, documentId, id, includeSuppressedDiagnostics, cancellationToken).ConfigureAwait(false); if (diagnostics.Length > 0) return diagnostics; } else { AppendMatchingData(source, workspace, projectId, documentId, id, buffer); Debug.Assert(buffer.Count is 0 or 1); if (buffer.Count == 1) { var diagnostics = buffer[0].Diagnostics; return includeSuppressedDiagnostics ? diagnostics : diagnostics.NullToEmpty().WhereAsArray(d => !d.IsSuppressed); } } } return ImmutableArray<DiagnosticData>.Empty; } private async ValueTask<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync( Workspace workspace, ProjectId projectId, DocumentId documentId, bool includeSuppressedDiagnostics, CancellationToken cancellationToken) { using var _1 = ArrayBuilder<DiagnosticData>.GetInstance(out var result); using var _2 = ArrayBuilder<Data>.GetInstance(out var buffer); foreach (var source in _updateSources) { cancellationToken.ThrowIfCancellationRequested(); buffer.Clear(); if (source.SupportGetDiagnostics) { result.AddRange(await source.GetDiagnosticsAsync(workspace, projectId, documentId, id: null, includeSuppressedDiagnostics, cancellationToken).ConfigureAwait(false)); } else { AppendMatchingData(source, workspace, projectId, documentId, id: null, buffer); foreach (var data in buffer) { foreach (var diagnostic in data.Diagnostics) { AssertIfNull(diagnostic); if (includeSuppressedDiagnostics || !diagnostic.IsSuppressed) result.Add(diagnostic); } } } } return result.ToImmutable(); } public ImmutableArray<DiagnosticBucket> GetPullDiagnosticBuckets(Workspace workspace, ProjectId projectId, DocumentId documentId, Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken) => GetDiagnosticBuckets(workspace, projectId, documentId, forPullDiagnostics: true, diagnosticMode, cancellationToken); public ImmutableArray<DiagnosticBucket> GetPushDiagnosticBuckets(Workspace workspace, ProjectId projectId, DocumentId documentId, Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken) => GetDiagnosticBuckets(workspace, projectId, documentId, forPullDiagnostics: false, diagnosticMode, cancellationToken); private ImmutableArray<DiagnosticBucket> GetDiagnosticBuckets( Workspace workspace, ProjectId projectId, DocumentId documentId, bool forPullDiagnostics, Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken) { // If this is a pull client, but pull diagnostics is not on, then they get nothing. Similarly, if this is a // push client and pull diagnostics are on, they get nothing. var isPull = workspace.IsPullDiagnostics(diagnosticMode); if (forPullDiagnostics != isPull) return ImmutableArray<DiagnosticBucket>.Empty; using var _1 = ArrayBuilder<DiagnosticBucket>.GetInstance(out var result); using var _2 = ArrayBuilder<Data>.GetInstance(out var buffer); foreach (var source in _updateSources) { buffer.Clear(); cancellationToken.ThrowIfCancellationRequested(); AppendMatchingData(source, workspace, projectId, documentId, id: null, buffer); foreach (var data in buffer) result.Add(new DiagnosticBucket(data.Id, data.Workspace, data.ProjectId, data.DocumentId)); } return result.ToImmutable(); } private void AppendMatchingData( IDiagnosticUpdateSource source, Workspace workspace, ProjectId projectId, DocumentId documentId, object id, ArrayBuilder<Data> list) { Contract.ThrowIfNull(workspace); lock (_gate) { if (!_map.TryGetValue(source, out var workspaceMap) || !workspaceMap.TryGetValue(workspace, out var current)) { return; } if (id != null) { if (current.TryGetValue(id, out var data)) { list.Add(data); } return; } foreach (var data in current.Values) { if (TryAddData(workspace, documentId, data, d => d.DocumentId, list) || TryAddData(workspace, projectId, data, d => d.ProjectId, list) || TryAddData(workspace, workspace, data, d => d.Workspace, list)) { continue; } } } } private static bool TryAddData<T>(Workspace workspace, T key, Data data, Func<Data, T> keyGetter, ArrayBuilder<Data> result) where T : class { if (key == null) { return false; } // make sure data is from same workspace. project/documentId can be shared between 2 different workspace if (workspace != data.Workspace) { return false; } if (key == keyGetter(data)) { result.Add(data); } return true; } [Conditional("DEBUG")] private static void AssertIfNull(ImmutableArray<DiagnosticData> diagnostics) { for (var i = 0; i < diagnostics.Length; i++) { AssertIfNull(diagnostics[i]); } } [Conditional("DEBUG")] private static void AssertIfNull<T>(T obj) where T : class { if (obj == null) { Debug.Assert(false, "who returns invalid data?"); } } private readonly struct Data { public readonly Workspace Workspace; public readonly ProjectId ProjectId; public readonly DocumentId DocumentId; public readonly object Id; public readonly ImmutableArray<DiagnosticData> Diagnostics; public Data(UpdatedEventArgs args) : this(args, ImmutableArray<DiagnosticData>.Empty) { } public Data(UpdatedEventArgs args, ImmutableArray<DiagnosticData> diagnostics) { Workspace = args.Workspace; ProjectId = args.ProjectId; DocumentId = args.DocumentId; Id = args.Id; Diagnostics = diagnostics; } } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly DiagnosticService _diagnosticService; internal TestAccessor(DiagnosticService diagnosticService) => _diagnosticService = diagnosticService; internal ref readonly EventListenerTracker<IDiagnosticService> EventListenerTracker => ref _diagnosticService._eventListenerTracker; } } }
-1
dotnet/roslyn
56,095
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-02T00:01:28Z"
"2021-09-02T01:47:21Z"
212ca8da034e484813ea99027c29cc3f6405fe1f
fe389d485fb73f8186b32636bfc747a39a70b028
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Core/Def/Implementation/Utilities/GlyphExtensions.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.Windows.Media; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.Language.Intellisense; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Utilities { internal static class GlyphExtensions { public static StandardGlyphGroup GetStandardGlyphGroup(this Glyph glyph) { switch (glyph) { case Glyph.Assembly: return StandardGlyphGroup.GlyphAssembly; case Glyph.BasicFile: case Glyph.BasicProject: return StandardGlyphGroup.GlyphVBProject; case Glyph.ClassPublic: case Glyph.ClassProtected: case Glyph.ClassPrivate: case Glyph.ClassInternal: return StandardGlyphGroup.GlyphGroupClass; case Glyph.ConstantPublic: case Glyph.ConstantProtected: case Glyph.ConstantPrivate: case Glyph.ConstantInternal: return StandardGlyphGroup.GlyphGroupConstant; case Glyph.CSharpFile: return StandardGlyphGroup.GlyphCSharpFile; case Glyph.CSharpProject: return StandardGlyphGroup.GlyphCoolProject; case Glyph.DelegatePublic: case Glyph.DelegateProtected: case Glyph.DelegatePrivate: case Glyph.DelegateInternal: return StandardGlyphGroup.GlyphGroupDelegate; case Glyph.EnumPublic: case Glyph.EnumProtected: case Glyph.EnumPrivate: case Glyph.EnumInternal: return StandardGlyphGroup.GlyphGroupEnum; case Glyph.EnumMemberPublic: case Glyph.EnumMemberProtected: case Glyph.EnumMemberPrivate: case Glyph.EnumMemberInternal: return StandardGlyphGroup.GlyphGroupEnumMember; case Glyph.Error: return StandardGlyphGroup.GlyphGroupError; case Glyph.ExtensionMethodPublic: return StandardGlyphGroup.GlyphExtensionMethod; case Glyph.ExtensionMethodProtected: return StandardGlyphGroup.GlyphExtensionMethodProtected; case Glyph.ExtensionMethodPrivate: return StandardGlyphGroup.GlyphExtensionMethodPrivate; case Glyph.ExtensionMethodInternal: return StandardGlyphGroup.GlyphExtensionMethodInternal; case Glyph.EventPublic: case Glyph.EventProtected: case Glyph.EventPrivate: case Glyph.EventInternal: return StandardGlyphGroup.GlyphGroupEvent; case Glyph.FieldPublic: case Glyph.FieldProtected: case Glyph.FieldPrivate: case Glyph.FieldInternal: return StandardGlyphGroup.GlyphGroupField; case Glyph.InterfacePublic: case Glyph.InterfaceProtected: case Glyph.InterfacePrivate: case Glyph.InterfaceInternal: return StandardGlyphGroup.GlyphGroupInterface; case Glyph.Intrinsic: return StandardGlyphGroup.GlyphGroupIntrinsic; case Glyph.Keyword: return StandardGlyphGroup.GlyphKeyword; case Glyph.Label: return StandardGlyphGroup.GlyphGroupIntrinsic; case Glyph.Local: return StandardGlyphGroup.GlyphGroupVariable; case Glyph.Namespace: return StandardGlyphGroup.GlyphGroupNamespace; case Glyph.MethodPublic: case Glyph.MethodProtected: case Glyph.MethodPrivate: case Glyph.MethodInternal: return StandardGlyphGroup.GlyphGroupMethod; case Glyph.ModulePublic: case Glyph.ModuleProtected: case Glyph.ModulePrivate: case Glyph.ModuleInternal: return StandardGlyphGroup.GlyphGroupModule; case Glyph.OpenFolder: return StandardGlyphGroup.GlyphOpenFolder; case Glyph.Operator: return StandardGlyphGroup.GlyphGroupOperator; case Glyph.Parameter: return StandardGlyphGroup.GlyphGroupVariable; case Glyph.PropertyPublic: case Glyph.PropertyProtected: case Glyph.PropertyPrivate: case Glyph.PropertyInternal: return StandardGlyphGroup.GlyphGroupProperty; case Glyph.RangeVariable: return StandardGlyphGroup.GlyphGroupVariable; case Glyph.Reference: return StandardGlyphGroup.GlyphReference; case Glyph.StructurePublic: case Glyph.StructureProtected: case Glyph.StructurePrivate: case Glyph.StructureInternal: return StandardGlyphGroup.GlyphGroupStruct; case Glyph.TypeParameter: return StandardGlyphGroup.GlyphGroupType; case Glyph.Snippet: return StandardGlyphGroup.GlyphCSharpExpansion; case Glyph.CompletionWarning: return StandardGlyphGroup.GlyphCompletionWarning; default: throw new ArgumentException("glyph"); } } public static StandardGlyphItem GetStandardGlyphItem(this Glyph icon) { switch (icon) { case Glyph.ClassProtected: case Glyph.ConstantProtected: case Glyph.DelegateProtected: case Glyph.EnumProtected: case Glyph.EventProtected: case Glyph.FieldProtected: case Glyph.InterfaceProtected: case Glyph.MethodProtected: case Glyph.ModuleProtected: case Glyph.PropertyProtected: case Glyph.StructureProtected: return StandardGlyphItem.GlyphItemProtected; case Glyph.ClassPrivate: case Glyph.ConstantPrivate: case Glyph.DelegatePrivate: case Glyph.EnumPrivate: case Glyph.EventPrivate: case Glyph.FieldPrivate: case Glyph.InterfacePrivate: case Glyph.MethodPrivate: case Glyph.ModulePrivate: case Glyph.PropertyPrivate: case Glyph.StructurePrivate: return StandardGlyphItem.GlyphItemPrivate; case Glyph.ClassInternal: case Glyph.ConstantInternal: case Glyph.DelegateInternal: case Glyph.EnumInternal: case Glyph.EventInternal: case Glyph.FieldInternal: case Glyph.InterfaceInternal: case Glyph.MethodInternal: case Glyph.ModuleInternal: case Glyph.PropertyInternal: case Glyph.StructureInternal: return StandardGlyphItem.GlyphItemFriend; default: // We don't want any overlays return StandardGlyphItem.GlyphItemPublic; } } public static ImageSource GetImageSource(this Glyph glyph, IGlyphService glyphService) => glyphService.GetGlyph(glyph.GetStandardGlyphGroup(), glyph.GetStandardGlyphItem()); public static ushort GetGlyphIndex(this Glyph glyph) { var glyphGroup = glyph.GetStandardGlyphGroup(); var glyphItem = glyph.GetStandardGlyphItem(); return glyphGroup < StandardGlyphGroup.GlyphGroupError ? (ushort)((int)glyphGroup + (int)glyphItem) : (ushort)glyphGroup; } } }
// Licensed to the .NET Foundation under one or more 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.Windows.Media; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.Language.Intellisense; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Utilities { internal static class GlyphExtensions { public static StandardGlyphGroup GetStandardGlyphGroup(this Glyph glyph) { switch (glyph) { case Glyph.Assembly: return StandardGlyphGroup.GlyphAssembly; case Glyph.BasicFile: case Glyph.BasicProject: return StandardGlyphGroup.GlyphVBProject; case Glyph.ClassPublic: case Glyph.ClassProtected: case Glyph.ClassPrivate: case Glyph.ClassInternal: return StandardGlyphGroup.GlyphGroupClass; case Glyph.ConstantPublic: case Glyph.ConstantProtected: case Glyph.ConstantPrivate: case Glyph.ConstantInternal: return StandardGlyphGroup.GlyphGroupConstant; case Glyph.CSharpFile: return StandardGlyphGroup.GlyphCSharpFile; case Glyph.CSharpProject: return StandardGlyphGroup.GlyphCoolProject; case Glyph.DelegatePublic: case Glyph.DelegateProtected: case Glyph.DelegatePrivate: case Glyph.DelegateInternal: return StandardGlyphGroup.GlyphGroupDelegate; case Glyph.EnumPublic: case Glyph.EnumProtected: case Glyph.EnumPrivate: case Glyph.EnumInternal: return StandardGlyphGroup.GlyphGroupEnum; case Glyph.EnumMemberPublic: case Glyph.EnumMemberProtected: case Glyph.EnumMemberPrivate: case Glyph.EnumMemberInternal: return StandardGlyphGroup.GlyphGroupEnumMember; case Glyph.Error: return StandardGlyphGroup.GlyphGroupError; case Glyph.ExtensionMethodPublic: return StandardGlyphGroup.GlyphExtensionMethod; case Glyph.ExtensionMethodProtected: return StandardGlyphGroup.GlyphExtensionMethodProtected; case Glyph.ExtensionMethodPrivate: return StandardGlyphGroup.GlyphExtensionMethodPrivate; case Glyph.ExtensionMethodInternal: return StandardGlyphGroup.GlyphExtensionMethodInternal; case Glyph.EventPublic: case Glyph.EventProtected: case Glyph.EventPrivate: case Glyph.EventInternal: return StandardGlyphGroup.GlyphGroupEvent; case Glyph.FieldPublic: case Glyph.FieldProtected: case Glyph.FieldPrivate: case Glyph.FieldInternal: return StandardGlyphGroup.GlyphGroupField; case Glyph.InterfacePublic: case Glyph.InterfaceProtected: case Glyph.InterfacePrivate: case Glyph.InterfaceInternal: return StandardGlyphGroup.GlyphGroupInterface; case Glyph.Intrinsic: return StandardGlyphGroup.GlyphGroupIntrinsic; case Glyph.Keyword: return StandardGlyphGroup.GlyphKeyword; case Glyph.Label: return StandardGlyphGroup.GlyphGroupIntrinsic; case Glyph.Local: return StandardGlyphGroup.GlyphGroupVariable; case Glyph.Namespace: return StandardGlyphGroup.GlyphGroupNamespace; case Glyph.MethodPublic: case Glyph.MethodProtected: case Glyph.MethodPrivate: case Glyph.MethodInternal: return StandardGlyphGroup.GlyphGroupMethod; case Glyph.ModulePublic: case Glyph.ModuleProtected: case Glyph.ModulePrivate: case Glyph.ModuleInternal: return StandardGlyphGroup.GlyphGroupModule; case Glyph.OpenFolder: return StandardGlyphGroup.GlyphOpenFolder; case Glyph.Operator: return StandardGlyphGroup.GlyphGroupOperator; case Glyph.Parameter: return StandardGlyphGroup.GlyphGroupVariable; case Glyph.PropertyPublic: case Glyph.PropertyProtected: case Glyph.PropertyPrivate: case Glyph.PropertyInternal: return StandardGlyphGroup.GlyphGroupProperty; case Glyph.RangeVariable: return StandardGlyphGroup.GlyphGroupVariable; case Glyph.Reference: return StandardGlyphGroup.GlyphReference; case Glyph.StructurePublic: case Glyph.StructureProtected: case Glyph.StructurePrivate: case Glyph.StructureInternal: return StandardGlyphGroup.GlyphGroupStruct; case Glyph.TypeParameter: return StandardGlyphGroup.GlyphGroupType; case Glyph.Snippet: return StandardGlyphGroup.GlyphCSharpExpansion; case Glyph.CompletionWarning: return StandardGlyphGroup.GlyphCompletionWarning; default: throw new ArgumentException("glyph"); } } public static StandardGlyphItem GetStandardGlyphItem(this Glyph icon) { switch (icon) { case Glyph.ClassProtected: case Glyph.ConstantProtected: case Glyph.DelegateProtected: case Glyph.EnumProtected: case Glyph.EventProtected: case Glyph.FieldProtected: case Glyph.InterfaceProtected: case Glyph.MethodProtected: case Glyph.ModuleProtected: case Glyph.PropertyProtected: case Glyph.StructureProtected: return StandardGlyphItem.GlyphItemProtected; case Glyph.ClassPrivate: case Glyph.ConstantPrivate: case Glyph.DelegatePrivate: case Glyph.EnumPrivate: case Glyph.EventPrivate: case Glyph.FieldPrivate: case Glyph.InterfacePrivate: case Glyph.MethodPrivate: case Glyph.ModulePrivate: case Glyph.PropertyPrivate: case Glyph.StructurePrivate: return StandardGlyphItem.GlyphItemPrivate; case Glyph.ClassInternal: case Glyph.ConstantInternal: case Glyph.DelegateInternal: case Glyph.EnumInternal: case Glyph.EventInternal: case Glyph.FieldInternal: case Glyph.InterfaceInternal: case Glyph.MethodInternal: case Glyph.ModuleInternal: case Glyph.PropertyInternal: case Glyph.StructureInternal: return StandardGlyphItem.GlyphItemFriend; default: // We don't want any overlays return StandardGlyphItem.GlyphItemPublic; } } public static ImageSource GetImageSource(this Glyph glyph, IGlyphService glyphService) => glyphService.GetGlyph(glyph.GetStandardGlyphGroup(), glyph.GetStandardGlyphItem()); public static ushort GetGlyphIndex(this Glyph glyph) { var glyphGroup = glyph.GetStandardGlyphGroup(); var glyphItem = glyph.GetStandardGlyphItem(); return glyphGroup < StandardGlyphGroup.GlyphGroupError ? (ushort)((int)glyphGroup + (int)glyphItem) : (ushort)glyphGroup; } } }
-1
dotnet/roslyn
56,095
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-02T00:01:28Z"
"2021-09-02T01:47:21Z"
212ca8da034e484813ea99027c29cc3f6405fe1f
fe389d485fb73f8186b32636bfc747a39a70b028
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Test/Symbol/Compilation/SymbolSearchTests.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 Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class SymbolSearchTests : CSharpTestBase { [Fact] public void TestSymbolFilterNone() { Assert.Throws<ArgumentException>(() => { var compilation = GetTestCompilation(); compilation.ContainsSymbolsWithName(n => true, SymbolFilter.None); }); Assert.Throws<ArgumentException>(() => { var compilation = GetTestCompilation(); compilation.GetSymbolsWithName(n => true, SymbolFilter.None); }); Assert.Throws<ArgumentException>(() => { var compilation = GetTestCompilation(); compilation.ContainsSymbolsWithName("", SymbolFilter.None); }); Assert.Throws<ArgumentException>(() => { var compilation = GetTestCompilation(); compilation.GetSymbolsWithName("", SymbolFilter.None); }); } [Fact] public void TestPredicateNull() { Assert.Throws<ArgumentNullException>(() => { var compilation = GetTestCompilation(); compilation.ContainsSymbolsWithName(predicate: null); }); Assert.Throws<ArgumentNullException>(() => { var compilation = GetTestCompilation(); compilation.GetSymbolsWithName(predicate: null); }); } [Fact] public void TestNameNull() { Assert.Throws<ArgumentNullException>(() => { var compilation = GetTestCompilation(); compilation.ContainsSymbolsWithName(name: null); }); Assert.Throws<ArgumentNullException>(() => { var compilation = GetTestCompilation(); compilation.GetSymbolsWithName(name: null); }); } [Fact] public void TestMergedNamespace() { var compilation = GetTestCompilation(); TestNameAndPredicate(compilation, "System", includeNamespace: true, includeType: false, includeMember: false, count: 1); TestNameAndPredicate(compilation, "System", includeNamespace: true, includeType: true, includeMember: false, count: 1); TestNameAndPredicate(compilation, "System", includeNamespace: true, includeType: false, includeMember: true, count: 1); TestNameAndPredicate(compilation, "System", includeNamespace: true, includeType: true, includeMember: true, count: 1); TestNameAndPredicate(compilation, "System", includeNamespace: false, includeType: false, includeMember: true, count: 0); TestNameAndPredicate(compilation, "System", includeNamespace: false, includeType: true, includeMember: false, count: 0); TestNameAndPredicate(compilation, "System", includeNamespace: false, includeType: true, includeMember: true, count: 0); } [Fact] public void TestSourceNamespace() { var compilation = GetTestCompilation(); TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: true, includeType: false, includeMember: false, count: 1); TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: true, includeType: true, includeMember: false, count: 1); TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: true, includeType: false, includeMember: true, count: 1); TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: true, includeType: true, includeMember: true, count: 1); TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: false, includeType: false, includeMember: true, count: 0); TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: false, includeType: true, includeMember: false, count: 0); TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: false, includeType: true, includeMember: true, count: 0); } [Fact] public void TestClassInMergedNamespace() { var compilation = GetTestCompilation(); TestNameAndPredicate(compilation, "Test", includeNamespace: false, includeType: true, includeMember: false, count: 1); TestNameAndPredicate(compilation, "Test", includeNamespace: false, includeType: true, includeMember: true, count: 1); TestNameAndPredicate(compilation, "Test", includeNamespace: true, includeType: true, includeMember: false, count: 1); TestNameAndPredicate(compilation, "Test", includeNamespace: true, includeType: true, includeMember: true, count: 1); TestNameAndPredicate(compilation, "Test", includeNamespace: false, includeType: false, includeMember: true, count: 0); TestNameAndPredicate(compilation, "Test", includeNamespace: true, includeType: false, includeMember: false, count: 0); TestNameAndPredicate(compilation, "Test", includeNamespace: true, includeType: false, includeMember: true, count: 0); } [Fact] public void TestClassInSourceNamespace() { var compilation = GetTestCompilation(); TestNameAndPredicate(compilation, "Test1", includeNamespace: false, includeType: true, includeMember: false, count: 1); TestNameAndPredicate(compilation, "Test1", includeNamespace: false, includeType: true, includeMember: true, count: 1); TestNameAndPredicate(compilation, "Test1", includeNamespace: true, includeType: true, includeMember: false, count: 1); TestNameAndPredicate(compilation, "Test1", includeNamespace: true, includeType: true, includeMember: true, count: 1); TestNameAndPredicate(compilation, "Test1", includeNamespace: false, includeType: false, includeMember: true, count: 0); TestNameAndPredicate(compilation, "Test1", includeNamespace: true, includeType: false, includeMember: false, count: 0); TestNameAndPredicate(compilation, "Test1", includeNamespace: true, includeType: false, includeMember: true, count: 0); } [Fact] public void TestMembers() { var compilation = GetTestCompilation(); TestNameAndPredicate(compilation, "myField", includeNamespace: false, includeType: false, includeMember: true, count: 1); TestNameAndPredicate(compilation, "myField", includeNamespace: false, includeType: true, includeMember: true, count: 1); TestNameAndPredicate(compilation, "myField", includeNamespace: true, includeType: false, includeMember: true, count: 1); TestNameAndPredicate(compilation, "myField", includeNamespace: true, includeType: true, includeMember: true, count: 1); TestNameAndPredicate(compilation, "myField", includeNamespace: false, includeType: true, includeMember: false, count: 0); TestNameAndPredicate(compilation, "myField", includeNamespace: true, includeType: false, includeMember: false, count: 0); TestNameAndPredicate(compilation, "myField", includeNamespace: true, includeType: true, includeMember: false, count: 0); } [Fact] public void TestPartialSearch() { var compilation = GetTestCompilation(); Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: false, includeType: false, includeMember: true, count: 4); Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: false, includeType: true, includeMember: false, count: 4); Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: false, includeType: true, includeMember: true, count: 8); Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: true, includeType: false, includeMember: false, count: 1); Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: true, includeType: false, includeMember: true, count: 5); Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: true, includeType: true, includeMember: false, count: 5); Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: true, includeType: true, includeMember: true, count: 9); Test(compilation, n => n.IndexOf("enum", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: true, includeType: true, includeMember: true, count: 2); } [WorkItem(876191, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/876191")] [Fact] public void TestExplicitInterfaceSearch() { const string source = @" interface I { void M(); } class Explicit : I { void I.M() { } } class Implicit : I { public void M() { } } "; var compilation = CreateCompilation(new[] { source }); Test(compilation, n => n.IndexOf("M", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: false, includeType: false, includeMember: true, count: 3); } private static CSharpCompilation GetTestCompilation() { const string source = @" namespace System { public class Test { } } namespace MyNamespace { public class Test1 { } } public class MyClass { private int myField; internal int MyProperty { get; set; } void MyMethod() { } public event EventHandler MyEvent; delegate string MyDelegate(int i); } struct MyStruct { } interface MyInterface { } enum Enum { EnumValue } "; return CreateCompilation(source: new string[] { source }); } private static void TestNameAndPredicate(CSharpCompilation compilation, string name, bool includeNamespace, bool includeType, bool includeMember, int count) { Test(compilation, name, includeNamespace, includeType, includeMember, count); Test(compilation, n => n == name, includeNamespace, includeType, includeMember, count); } private static void Test(CSharpCompilation compilation, string name, bool includeNamespace, bool includeType, bool includeMember, int count) { SymbolFilter filter = ComputeFilter(includeNamespace, includeType, includeMember); Assert.Equal(count > 0, compilation.ContainsSymbolsWithName(name, filter)); Assert.Equal(count, compilation.GetSymbolsWithName(name, filter).Count()); } private static void Test(CSharpCompilation compilation, Func<string, bool> predicate, bool includeNamespace, bool includeType, bool includeMember, int count) { SymbolFilter filter = ComputeFilter(includeNamespace, includeType, includeMember); Assert.Equal(count > 0, compilation.ContainsSymbolsWithName(predicate, filter)); Assert.Equal(count, compilation.GetSymbolsWithName(predicate, filter).Count()); } private static SymbolFilter ComputeFilter(bool includeNamespace, bool includeType, bool includeMember) { var filter = SymbolFilter.None; filter = includeNamespace ? (filter | SymbolFilter.Namespace) : filter; filter = includeType ? (filter | SymbolFilter.Type) : filter; filter = includeMember ? (filter | SymbolFilter.Member) : filter; return filter; } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class SymbolSearchTests : CSharpTestBase { [Fact] public void TestSymbolFilterNone() { Assert.Throws<ArgumentException>(() => { var compilation = GetTestCompilation(); compilation.ContainsSymbolsWithName(n => true, SymbolFilter.None); }); Assert.Throws<ArgumentException>(() => { var compilation = GetTestCompilation(); compilation.GetSymbolsWithName(n => true, SymbolFilter.None); }); Assert.Throws<ArgumentException>(() => { var compilation = GetTestCompilation(); compilation.ContainsSymbolsWithName("", SymbolFilter.None); }); Assert.Throws<ArgumentException>(() => { var compilation = GetTestCompilation(); compilation.GetSymbolsWithName("", SymbolFilter.None); }); } [Fact] public void TestPredicateNull() { Assert.Throws<ArgumentNullException>(() => { var compilation = GetTestCompilation(); compilation.ContainsSymbolsWithName(predicate: null); }); Assert.Throws<ArgumentNullException>(() => { var compilation = GetTestCompilation(); compilation.GetSymbolsWithName(predicate: null); }); } [Fact] public void TestNameNull() { Assert.Throws<ArgumentNullException>(() => { var compilation = GetTestCompilation(); compilation.ContainsSymbolsWithName(name: null); }); Assert.Throws<ArgumentNullException>(() => { var compilation = GetTestCompilation(); compilation.GetSymbolsWithName(name: null); }); } [Fact] public void TestMergedNamespace() { var compilation = GetTestCompilation(); TestNameAndPredicate(compilation, "System", includeNamespace: true, includeType: false, includeMember: false, count: 1); TestNameAndPredicate(compilation, "System", includeNamespace: true, includeType: true, includeMember: false, count: 1); TestNameAndPredicate(compilation, "System", includeNamespace: true, includeType: false, includeMember: true, count: 1); TestNameAndPredicate(compilation, "System", includeNamespace: true, includeType: true, includeMember: true, count: 1); TestNameAndPredicate(compilation, "System", includeNamespace: false, includeType: false, includeMember: true, count: 0); TestNameAndPredicate(compilation, "System", includeNamespace: false, includeType: true, includeMember: false, count: 0); TestNameAndPredicate(compilation, "System", includeNamespace: false, includeType: true, includeMember: true, count: 0); } [Fact] public void TestSourceNamespace() { var compilation = GetTestCompilation(); TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: true, includeType: false, includeMember: false, count: 1); TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: true, includeType: true, includeMember: false, count: 1); TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: true, includeType: false, includeMember: true, count: 1); TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: true, includeType: true, includeMember: true, count: 1); TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: false, includeType: false, includeMember: true, count: 0); TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: false, includeType: true, includeMember: false, count: 0); TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: false, includeType: true, includeMember: true, count: 0); } [Fact] public void TestClassInMergedNamespace() { var compilation = GetTestCompilation(); TestNameAndPredicate(compilation, "Test", includeNamespace: false, includeType: true, includeMember: false, count: 1); TestNameAndPredicate(compilation, "Test", includeNamespace: false, includeType: true, includeMember: true, count: 1); TestNameAndPredicate(compilation, "Test", includeNamespace: true, includeType: true, includeMember: false, count: 1); TestNameAndPredicate(compilation, "Test", includeNamespace: true, includeType: true, includeMember: true, count: 1); TestNameAndPredicate(compilation, "Test", includeNamespace: false, includeType: false, includeMember: true, count: 0); TestNameAndPredicate(compilation, "Test", includeNamespace: true, includeType: false, includeMember: false, count: 0); TestNameAndPredicate(compilation, "Test", includeNamespace: true, includeType: false, includeMember: true, count: 0); } [Fact] public void TestClassInSourceNamespace() { var compilation = GetTestCompilation(); TestNameAndPredicate(compilation, "Test1", includeNamespace: false, includeType: true, includeMember: false, count: 1); TestNameAndPredicate(compilation, "Test1", includeNamespace: false, includeType: true, includeMember: true, count: 1); TestNameAndPredicate(compilation, "Test1", includeNamespace: true, includeType: true, includeMember: false, count: 1); TestNameAndPredicate(compilation, "Test1", includeNamespace: true, includeType: true, includeMember: true, count: 1); TestNameAndPredicate(compilation, "Test1", includeNamespace: false, includeType: false, includeMember: true, count: 0); TestNameAndPredicate(compilation, "Test1", includeNamespace: true, includeType: false, includeMember: false, count: 0); TestNameAndPredicate(compilation, "Test1", includeNamespace: true, includeType: false, includeMember: true, count: 0); } [Fact] public void TestMembers() { var compilation = GetTestCompilation(); TestNameAndPredicate(compilation, "myField", includeNamespace: false, includeType: false, includeMember: true, count: 1); TestNameAndPredicate(compilation, "myField", includeNamespace: false, includeType: true, includeMember: true, count: 1); TestNameAndPredicate(compilation, "myField", includeNamespace: true, includeType: false, includeMember: true, count: 1); TestNameAndPredicate(compilation, "myField", includeNamespace: true, includeType: true, includeMember: true, count: 1); TestNameAndPredicate(compilation, "myField", includeNamespace: false, includeType: true, includeMember: false, count: 0); TestNameAndPredicate(compilation, "myField", includeNamespace: true, includeType: false, includeMember: false, count: 0); TestNameAndPredicate(compilation, "myField", includeNamespace: true, includeType: true, includeMember: false, count: 0); } [Fact] public void TestPartialSearch() { var compilation = GetTestCompilation(); Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: false, includeType: false, includeMember: true, count: 4); Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: false, includeType: true, includeMember: false, count: 4); Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: false, includeType: true, includeMember: true, count: 8); Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: true, includeType: false, includeMember: false, count: 1); Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: true, includeType: false, includeMember: true, count: 5); Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: true, includeType: true, includeMember: false, count: 5); Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: true, includeType: true, includeMember: true, count: 9); Test(compilation, n => n.IndexOf("enum", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: true, includeType: true, includeMember: true, count: 2); } [WorkItem(876191, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/876191")] [Fact] public void TestExplicitInterfaceSearch() { const string source = @" interface I { void M(); } class Explicit : I { void I.M() { } } class Implicit : I { public void M() { } } "; var compilation = CreateCompilation(new[] { source }); Test(compilation, n => n.IndexOf("M", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: false, includeType: false, includeMember: true, count: 3); } private static CSharpCompilation GetTestCompilation() { const string source = @" namespace System { public class Test { } } namespace MyNamespace { public class Test1 { } } public class MyClass { private int myField; internal int MyProperty { get; set; } void MyMethod() { } public event EventHandler MyEvent; delegate string MyDelegate(int i); } struct MyStruct { } interface MyInterface { } enum Enum { EnumValue } "; return CreateCompilation(source: new string[] { source }); } private static void TestNameAndPredicate(CSharpCompilation compilation, string name, bool includeNamespace, bool includeType, bool includeMember, int count) { Test(compilation, name, includeNamespace, includeType, includeMember, count); Test(compilation, n => n == name, includeNamespace, includeType, includeMember, count); } private static void Test(CSharpCompilation compilation, string name, bool includeNamespace, bool includeType, bool includeMember, int count) { SymbolFilter filter = ComputeFilter(includeNamespace, includeType, includeMember); Assert.Equal(count > 0, compilation.ContainsSymbolsWithName(name, filter)); Assert.Equal(count, compilation.GetSymbolsWithName(name, filter).Count()); } private static void Test(CSharpCompilation compilation, Func<string, bool> predicate, bool includeNamespace, bool includeType, bool includeMember, int count) { SymbolFilter filter = ComputeFilter(includeNamespace, includeType, includeMember); Assert.Equal(count > 0, compilation.ContainsSymbolsWithName(predicate, filter)); Assert.Equal(count, compilation.GetSymbolsWithName(predicate, filter).Count()); } private static SymbolFilter ComputeFilter(bool includeNamespace, bool includeType, bool includeMember) { var filter = SymbolFilter.None; filter = includeNamespace ? (filter | SymbolFilter.Namespace) : filter; filter = includeType ? (filter | SymbolFilter.Type) : filter; filter = includeMember ? (filter | SymbolFilter.Member) : filter; return filter; } } }
-1
dotnet/roslyn
56,095
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-02T00:01:28Z"
"2021-09-02T01:47:21Z"
212ca8da034e484813ea99027c29cc3f6405fe1f
fe389d485fb73f8186b32636bfc747a39a70b028
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_FieldAccess.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.Diagnostics Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter Public Overrides Function VisitFieldAccess(node As BoundFieldAccess) As BoundNode Dim rewrittenReceiver As BoundExpression = If(node.FieldSymbol.IsShared, Nothing, Me.VisitExpressionNode(node.ReceiverOpt)) If node.FieldSymbol.IsTupleField Then Return MakeTupleFieldAccess(node.Syntax, node.FieldSymbol, rewrittenReceiver, node.ConstantValueOpt, node.IsLValue) End If Return node.Update(rewrittenReceiver, node.FieldSymbol, node.IsLValue, node.SuppressVirtualCalls, constantsInProgressOpt:=Nothing, node.Type) End Function ''' <summary> ''' Converts access to a tuple instance into access into the underlying ValueTuple(s). ''' ''' For instance, tuple.Item8 ''' produces fieldAccess(field=Item1, receiver=fieldAccess(field=Rest, receiver=ValueTuple for tuple)) ''' </summary> Private Function MakeTupleFieldAccess( syntax As SyntaxNode, tupleField As FieldSymbol, rewrittenReceiver As BoundExpression, constantValueOpt As ConstantValue, isLValue As Boolean) As BoundExpression Dim tupleType = tupleField.ContainingType Dim currentLinkType As NamedTypeSymbol = tupleType.TupleUnderlyingType Dim underlyingField As FieldSymbol = tupleField.TupleUnderlyingField If underlyingField Is Nothing Then ' Use-site error must have been reported elsewhere. Return MakeBadFieldAccess(syntax, tupleField, rewrittenReceiver) End If If Not TypeSymbol.Equals(underlyingField.ContainingType, currentLinkType, TypeCompareKind.ConsiderEverything) Then Dim wellKnownTupleRest As WellKnownMember = TupleTypeSymbol.GetTupleTypeMember(TupleTypeSymbol.RestPosition, TupleTypeSymbol.RestPosition) Dim tupleRestField = DirectCast(TupleTypeSymbol.GetWellKnownMemberInType(currentLinkType.OriginalDefinition, wellKnownTupleRest, _diagnostics, syntax), FieldSymbol) If tupleRestField Is Nothing Then ' error tolerance for cases when Rest is missing Return MakeBadFieldAccess(syntax, tupleField, rewrittenReceiver) End If ' make nested field accesses to Rest Do Dim nestedFieldSymbol As FieldSymbol = tupleRestField.AsMember(currentLinkType) rewrittenReceiver = New BoundFieldAccess(syntax, rewrittenReceiver, nestedFieldSymbol, isLValue, nestedFieldSymbol.Type) currentLinkType = currentLinkType.TypeArgumentsNoUseSiteDiagnostics(TupleTypeSymbol.RestPosition - 1).TupleUnderlyingType Loop While Not TypeSymbol.Equals(underlyingField.ContainingType, currentLinkType, TypeCompareKind.ConsiderEverything) End If ' make a field access for the most local access Return New BoundFieldAccess(syntax, rewrittenReceiver, underlyingField, isLValue, underlyingField.Type) End Function Private Shared Function MakeBadFieldAccess(syntax As SyntaxNode, tupleField As FieldSymbol, rewrittenReceiver As BoundExpression) As BoundBadExpression Return New BoundBadExpression( syntax, LookupResultKind.Empty, ImmutableArray.Create(Of Symbol)(tupleField), ImmutableArray.Create(rewrittenReceiver), tupleField.Type, hasErrors:=True) 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.Diagnostics Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter Public Overrides Function VisitFieldAccess(node As BoundFieldAccess) As BoundNode Dim rewrittenReceiver As BoundExpression = If(node.FieldSymbol.IsShared, Nothing, Me.VisitExpressionNode(node.ReceiverOpt)) If node.FieldSymbol.IsTupleField Then Return MakeTupleFieldAccess(node.Syntax, node.FieldSymbol, rewrittenReceiver, node.ConstantValueOpt, node.IsLValue) End If Return node.Update(rewrittenReceiver, node.FieldSymbol, node.IsLValue, node.SuppressVirtualCalls, constantsInProgressOpt:=Nothing, node.Type) End Function ''' <summary> ''' Converts access to a tuple instance into access into the underlying ValueTuple(s). ''' ''' For instance, tuple.Item8 ''' produces fieldAccess(field=Item1, receiver=fieldAccess(field=Rest, receiver=ValueTuple for tuple)) ''' </summary> Private Function MakeTupleFieldAccess( syntax As SyntaxNode, tupleField As FieldSymbol, rewrittenReceiver As BoundExpression, constantValueOpt As ConstantValue, isLValue As Boolean) As BoundExpression Dim tupleType = tupleField.ContainingType Dim currentLinkType As NamedTypeSymbol = tupleType.TupleUnderlyingType Dim underlyingField As FieldSymbol = tupleField.TupleUnderlyingField If underlyingField Is Nothing Then ' Use-site error must have been reported elsewhere. Return MakeBadFieldAccess(syntax, tupleField, rewrittenReceiver) End If If Not TypeSymbol.Equals(underlyingField.ContainingType, currentLinkType, TypeCompareKind.ConsiderEverything) Then Dim wellKnownTupleRest As WellKnownMember = TupleTypeSymbol.GetTupleTypeMember(TupleTypeSymbol.RestPosition, TupleTypeSymbol.RestPosition) Dim tupleRestField = DirectCast(TupleTypeSymbol.GetWellKnownMemberInType(currentLinkType.OriginalDefinition, wellKnownTupleRest, _diagnostics, syntax), FieldSymbol) If tupleRestField Is Nothing Then ' error tolerance for cases when Rest is missing Return MakeBadFieldAccess(syntax, tupleField, rewrittenReceiver) End If ' make nested field accesses to Rest Do Dim nestedFieldSymbol As FieldSymbol = tupleRestField.AsMember(currentLinkType) rewrittenReceiver = New BoundFieldAccess(syntax, rewrittenReceiver, nestedFieldSymbol, isLValue, nestedFieldSymbol.Type) currentLinkType = currentLinkType.TypeArgumentsNoUseSiteDiagnostics(TupleTypeSymbol.RestPosition - 1).TupleUnderlyingType Loop While Not TypeSymbol.Equals(underlyingField.ContainingType, currentLinkType, TypeCompareKind.ConsiderEverything) End If ' make a field access for the most local access Return New BoundFieldAccess(syntax, rewrittenReceiver, underlyingField, isLValue, underlyingField.Type) End Function Private Shared Function MakeBadFieldAccess(syntax As SyntaxNode, tupleField As FieldSymbol, rewrittenReceiver As BoundExpression) As BoundBadExpression Return New BoundBadExpression( syntax, LookupResultKind.Empty, ImmutableArray.Create(Of Symbol)(tupleField), ImmutableArray.Create(rewrittenReceiver), tupleField.Type, hasErrors:=True) End Function End Class End Namespace
-1
dotnet/roslyn
56,095
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-02T00:01:28Z"
"2021-09-02T01:47:21Z"
212ca8da034e484813ea99027c29cc3f6405fe1f
fe389d485fb73f8186b32636bfc747a39a70b028
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/MemberInfo/TypeImpl.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.Globalization; using System.Linq; using Microsoft.VisualStudio.Debugger.Metadata; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; using TypeCode = Microsoft.VisualStudio.Debugger.Metadata.TypeCode; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal class TypeImpl : Type { internal readonly System.Type Type; internal TypeImpl(System.Type type) { Debug.Assert(type != null); this.Type = type; } public static explicit operator TypeImpl(System.Type type) { return type == null ? null : new TypeImpl(type); } public override Assembly Assembly { get { return new AssemblyImpl(this.Type.Assembly); } } public override string AssemblyQualifiedName { get { throw new NotImplementedException(); } } public override Type BaseType { get { return (TypeImpl)this.Type.BaseType; } } public override bool ContainsGenericParameters { get { throw new NotImplementedException(); } } public override Type DeclaringType { get { return (TypeImpl)this.Type.DeclaringType; } } public override bool IsEquivalentTo(MemberInfo other) { throw new NotImplementedException(); } public override string FullName { get { return this.Type.FullName; } } public override Guid GUID { get { throw new NotImplementedException(); } } public override MemberTypes MemberType { get { return (MemberTypes)this.Type.MemberType; } } public override int MetadataToken { get { throw new NotImplementedException(); } } public override Module Module { get { return new ModuleImpl(this.Type.Module); } } public override string Name { get { return Type.Name; } } public override string Namespace { get { return Type.Namespace; } } public override Type ReflectedType { get { throw new NotImplementedException(); } } public override Type UnderlyingSystemType { get { return (TypeImpl)Type.UnderlyingSystemType; } } public override bool Equals(Type o) { return o != null && o.GetType() == this.GetType() && ((TypeImpl)o).Type == this.Type; } public override bool Equals(object objOther) { return Equals(objOther as Type); } public override int GetHashCode() { return Type.GetHashCode(); } public override int GetArrayRank() { return Type.GetArrayRank(); } public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { return Type.GetConstructors((System.Reflection.BindingFlags)bindingAttr).Select(c => new ConstructorInfoImpl(c)).ToArray(); } public override object[] GetCustomAttributes(bool inherit) { throw new NotImplementedException(); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotImplementedException(); } public override IList<CustomAttributeData> GetCustomAttributesData() { return Type.GetCustomAttributesData().Select(a => new CustomAttributeDataImpl(a)).ToArray(); } public override Type GetElementType() { return (TypeImpl)(Type.GetElementType()); } public override EventInfo GetEvent(string name, BindingFlags flags) { throw new NotImplementedException(); } public override EventInfo[] GetEvents(BindingFlags flags) { throw new NotImplementedException(); } public override FieldInfo GetField(string name, BindingFlags bindingAttr) { var field = Type.GetField(name, (System.Reflection.BindingFlags)bindingAttr); return (field == null) ? null : new FieldInfoImpl(field); } public override FieldInfo[] GetFields(BindingFlags flags) { return Type.GetFields((System.Reflection.BindingFlags)flags).Select(f => new FieldInfoImpl(f)).ToArray(); } public override Type GetGenericTypeDefinition() { return (TypeImpl)this.Type.GetGenericTypeDefinition(); } public override Type[] GetGenericArguments() { return Type.GetGenericArguments().Select(t => new TypeImpl(t)).ToArray(); } public override Type GetInterface(string name, bool ignoreCase) { throw new NotImplementedException(); } public override Type[] GetInterfaces() { return Type.GetInterfaces().Select(i => new TypeImpl(i)).ToArray(); } public override System.Reflection.InterfaceMapping GetInterfaceMap(Type interfaceType) { throw new NotImplementedException(); } public override MemberInfo[] GetMember(string name, BindingFlags bindingAttr) { return Type.GetMember(name, (System.Reflection.BindingFlags)bindingAttr).Select(GetMember).ToArray(); } public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { return Type.GetMembers((System.Reflection.BindingFlags)bindingAttr).Select(GetMember).ToArray(); } private static MemberInfo GetMember(System.Reflection.MemberInfo member) { switch (member.MemberType) { case System.Reflection.MemberTypes.Constructor: return new ConstructorInfoImpl((System.Reflection.ConstructorInfo)member); case System.Reflection.MemberTypes.Event: return new EventInfoImpl((System.Reflection.EventInfo)member); case System.Reflection.MemberTypes.Field: return new FieldInfoImpl((System.Reflection.FieldInfo)member); case System.Reflection.MemberTypes.Method: return new MethodInfoImpl((System.Reflection.MethodInfo)member); case System.Reflection.MemberTypes.NestedType: return new TypeImpl((System.Reflection.TypeInfo)member); case System.Reflection.MemberTypes.Property: return new PropertyInfoImpl((System.Reflection.PropertyInfo)member); default: throw new NotImplementedException(member.MemberType.ToString()); } } public override MethodInfo[] GetMethods(BindingFlags flags) { return this.Type.GetMethods((System.Reflection.BindingFlags)flags).Select(m => new MethodInfoImpl(m)).ToArray(); } public override Type GetNestedType(string name, BindingFlags bindingAttr) { throw new NotImplementedException(); } public override Type[] GetNestedTypes(BindingFlags bindingAttr) { throw new NotImplementedException(); } public override PropertyInfo[] GetProperties(BindingFlags flags) { throw new NotImplementedException(); } public override object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) { throw new NotImplementedException(); } public override bool IsAssignableFrom(Type c) { throw new NotImplementedException(); } public override bool IsDefined(Type attributeType, bool inherit) { throw new NotImplementedException(); } public override bool IsEnum { get { return this.Type.IsEnum; } } public override bool IsGenericParameter { get { return Type.IsGenericParameter; } } public override bool IsGenericType { get { return Type.IsGenericType; } } public override bool IsGenericTypeDefinition { get { return Type.IsGenericTypeDefinition; } } public override int GenericParameterPosition { get { return Type.GenericParameterPosition; } } public override ExplicitInterfaceInfo[] GetExplicitInterfaceImplementations() { var interfaceMaps = Type.GetInterfaces().Select(i => Type.GetInterfaceMap(i)); // A dot is neither necessary nor sufficient for determining whether a member explicitly // implements an interface member, but it does characterize the set of members we're // interested in displaying differently. For example, if the property is from VB, it will // be an explicit interface implementation, but will not have a dot. Therefore, this is // good enough for our mock implementation. var infos = interfaceMaps.SelectMany(map => map.InterfaceMethods.Zip(map.TargetMethods, (interfaceMethod, implementingMethod) => implementingMethod.Name.Contains(".") ? MakeExplicitInterfaceInfo(interfaceMethod, implementingMethod) : null)); return infos.Where(i => i != null).ToArray(); } private static ExplicitInterfaceInfo MakeExplicitInterfaceInfo(System.Reflection.MethodInfo interfaceMethod, System.Reflection.MethodInfo implementingMethod) { return (ExplicitInterfaceInfo)typeof(ExplicitInterfaceInfo).Instantiate( new MethodInfoImpl(interfaceMethod), new MethodInfoImpl(implementingMethod)); } public override bool IsInstanceOfType(object o) { throw new NotImplementedException(); } public override bool IsSubclassOf(Type c) { throw new NotImplementedException(); } public override Type MakeArrayType() { return (TypeImpl)this.Type.MakeArrayType(); } public override Type MakeArrayType(int rank) { return (TypeImpl)this.Type.MakeArrayType(rank); } public override Type MakeByRefType() { throw new NotImplementedException(); } public override Type MakeGenericType(params Type[] argTypes) { return (TypeImpl)this.Type.MakeGenericType(argTypes.Select(t => ((TypeImpl)t).Type).ToArray()); } public override Type MakePointerType() { return (TypeImpl)this.Type.MakePointerType(); } protected override System.Reflection.TypeAttributes GetAttributeFlagsImpl() { System.Reflection.TypeAttributes result = 0; if (this.Type.IsClass) { result |= System.Reflection.TypeAttributes.Class; } if (this.Type.IsInterface) { result |= System.Reflection.TypeAttributes.Interface; } if (this.Type.IsAbstract) { result |= System.Reflection.TypeAttributes.Abstract; } if (this.Type.IsSealed) { result |= System.Reflection.TypeAttributes.Sealed; } return result; } protected override bool IsValueTypeImpl() { return this.Type.IsValueType; } protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotImplementedException(); } protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotImplementedException(); } protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { Debug.Assert(binder == null, "NYI"); Debug.Assert(returnType == null, "NYI"); Debug.Assert(types == null, "NYI"); Debug.Assert(modifiers == null, "NYI"); return new PropertyInfoImpl(Type.GetProperty(name, (System.Reflection.BindingFlags)bindingAttr, binder: null, returnType: null, types: new System.Type[0], modifiers: new System.Reflection.ParameterModifier[0])); } protected override TypeCode GetTypeCodeImpl() { return (TypeCode)System.Type.GetTypeCode(this.Type); } protected override bool HasElementTypeImpl() { return this.Type.HasElementType; } protected override bool IsArrayImpl() { return Type.IsArray; } protected override bool IsByRefImpl() { return Type.IsByRef; } protected override bool IsCOMObjectImpl() { throw new NotImplementedException(); } protected override bool IsContextfulImpl() { throw new NotImplementedException(); } protected override bool IsMarshalByRefImpl() { throw new NotImplementedException(); } protected override bool IsPointerImpl() { return Type.IsPointer; } protected override bool IsPrimitiveImpl() { throw new NotImplementedException(); } public override bool IsAssignableTo(Type c) { throw new NotImplementedException(); } public override string ToString() { return this.Type.ToString(); } public override Type[] GetInterfacesOnType() { var t = this.Type; var builder = ArrayBuilder<Type>.GetInstance(); foreach (var @interface in t.GetInterfaces()) { var map = t.GetInterfaceMap(@interface); if (map.TargetMethods.Any(m => m.DeclaringType == t)) { builder.Add((TypeImpl)@interface); } } return builder.ToArrayAndFree(); } } }
// Licensed to the .NET Foundation under one or more 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.Globalization; using System.Linq; using Microsoft.VisualStudio.Debugger.Metadata; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; using TypeCode = Microsoft.VisualStudio.Debugger.Metadata.TypeCode; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal class TypeImpl : Type { internal readonly System.Type Type; internal TypeImpl(System.Type type) { Debug.Assert(type != null); this.Type = type; } public static explicit operator TypeImpl(System.Type type) { return type == null ? null : new TypeImpl(type); } public override Assembly Assembly { get { return new AssemblyImpl(this.Type.Assembly); } } public override string AssemblyQualifiedName { get { throw new NotImplementedException(); } } public override Type BaseType { get { return (TypeImpl)this.Type.BaseType; } } public override bool ContainsGenericParameters { get { throw new NotImplementedException(); } } public override Type DeclaringType { get { return (TypeImpl)this.Type.DeclaringType; } } public override bool IsEquivalentTo(MemberInfo other) { throw new NotImplementedException(); } public override string FullName { get { return this.Type.FullName; } } public override Guid GUID { get { throw new NotImplementedException(); } } public override MemberTypes MemberType { get { return (MemberTypes)this.Type.MemberType; } } public override int MetadataToken { get { throw new NotImplementedException(); } } public override Module Module { get { return new ModuleImpl(this.Type.Module); } } public override string Name { get { return Type.Name; } } public override string Namespace { get { return Type.Namespace; } } public override Type ReflectedType { get { throw new NotImplementedException(); } } public override Type UnderlyingSystemType { get { return (TypeImpl)Type.UnderlyingSystemType; } } public override bool Equals(Type o) { return o != null && o.GetType() == this.GetType() && ((TypeImpl)o).Type == this.Type; } public override bool Equals(object objOther) { return Equals(objOther as Type); } public override int GetHashCode() { return Type.GetHashCode(); } public override int GetArrayRank() { return Type.GetArrayRank(); } public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { return Type.GetConstructors((System.Reflection.BindingFlags)bindingAttr).Select(c => new ConstructorInfoImpl(c)).ToArray(); } public override object[] GetCustomAttributes(bool inherit) { throw new NotImplementedException(); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotImplementedException(); } public override IList<CustomAttributeData> GetCustomAttributesData() { return Type.GetCustomAttributesData().Select(a => new CustomAttributeDataImpl(a)).ToArray(); } public override Type GetElementType() { return (TypeImpl)(Type.GetElementType()); } public override EventInfo GetEvent(string name, BindingFlags flags) { throw new NotImplementedException(); } public override EventInfo[] GetEvents(BindingFlags flags) { throw new NotImplementedException(); } public override FieldInfo GetField(string name, BindingFlags bindingAttr) { var field = Type.GetField(name, (System.Reflection.BindingFlags)bindingAttr); return (field == null) ? null : new FieldInfoImpl(field); } public override FieldInfo[] GetFields(BindingFlags flags) { return Type.GetFields((System.Reflection.BindingFlags)flags).Select(f => new FieldInfoImpl(f)).ToArray(); } public override Type GetGenericTypeDefinition() { return (TypeImpl)this.Type.GetGenericTypeDefinition(); } public override Type[] GetGenericArguments() { return Type.GetGenericArguments().Select(t => new TypeImpl(t)).ToArray(); } public override Type GetInterface(string name, bool ignoreCase) { throw new NotImplementedException(); } public override Type[] GetInterfaces() { return Type.GetInterfaces().Select(i => new TypeImpl(i)).ToArray(); } public override System.Reflection.InterfaceMapping GetInterfaceMap(Type interfaceType) { throw new NotImplementedException(); } public override MemberInfo[] GetMember(string name, BindingFlags bindingAttr) { return Type.GetMember(name, (System.Reflection.BindingFlags)bindingAttr).Select(GetMember).ToArray(); } public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { return Type.GetMembers((System.Reflection.BindingFlags)bindingAttr).Select(GetMember).ToArray(); } private static MemberInfo GetMember(System.Reflection.MemberInfo member) { switch (member.MemberType) { case System.Reflection.MemberTypes.Constructor: return new ConstructorInfoImpl((System.Reflection.ConstructorInfo)member); case System.Reflection.MemberTypes.Event: return new EventInfoImpl((System.Reflection.EventInfo)member); case System.Reflection.MemberTypes.Field: return new FieldInfoImpl((System.Reflection.FieldInfo)member); case System.Reflection.MemberTypes.Method: return new MethodInfoImpl((System.Reflection.MethodInfo)member); case System.Reflection.MemberTypes.NestedType: return new TypeImpl((System.Reflection.TypeInfo)member); case System.Reflection.MemberTypes.Property: return new PropertyInfoImpl((System.Reflection.PropertyInfo)member); default: throw new NotImplementedException(member.MemberType.ToString()); } } public override MethodInfo[] GetMethods(BindingFlags flags) { return this.Type.GetMethods((System.Reflection.BindingFlags)flags).Select(m => new MethodInfoImpl(m)).ToArray(); } public override Type GetNestedType(string name, BindingFlags bindingAttr) { throw new NotImplementedException(); } public override Type[] GetNestedTypes(BindingFlags bindingAttr) { throw new NotImplementedException(); } public override PropertyInfo[] GetProperties(BindingFlags flags) { throw new NotImplementedException(); } public override object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) { throw new NotImplementedException(); } public override bool IsAssignableFrom(Type c) { throw new NotImplementedException(); } public override bool IsDefined(Type attributeType, bool inherit) { throw new NotImplementedException(); } public override bool IsEnum { get { return this.Type.IsEnum; } } public override bool IsGenericParameter { get { return Type.IsGenericParameter; } } public override bool IsGenericType { get { return Type.IsGenericType; } } public override bool IsGenericTypeDefinition { get { return Type.IsGenericTypeDefinition; } } public override int GenericParameterPosition { get { return Type.GenericParameterPosition; } } public override ExplicitInterfaceInfo[] GetExplicitInterfaceImplementations() { var interfaceMaps = Type.GetInterfaces().Select(i => Type.GetInterfaceMap(i)); // A dot is neither necessary nor sufficient for determining whether a member explicitly // implements an interface member, but it does characterize the set of members we're // interested in displaying differently. For example, if the property is from VB, it will // be an explicit interface implementation, but will not have a dot. Therefore, this is // good enough for our mock implementation. var infos = interfaceMaps.SelectMany(map => map.InterfaceMethods.Zip(map.TargetMethods, (interfaceMethod, implementingMethod) => implementingMethod.Name.Contains(".") ? MakeExplicitInterfaceInfo(interfaceMethod, implementingMethod) : null)); return infos.Where(i => i != null).ToArray(); } private static ExplicitInterfaceInfo MakeExplicitInterfaceInfo(System.Reflection.MethodInfo interfaceMethod, System.Reflection.MethodInfo implementingMethod) { return (ExplicitInterfaceInfo)typeof(ExplicitInterfaceInfo).Instantiate( new MethodInfoImpl(interfaceMethod), new MethodInfoImpl(implementingMethod)); } public override bool IsInstanceOfType(object o) { throw new NotImplementedException(); } public override bool IsSubclassOf(Type c) { throw new NotImplementedException(); } public override Type MakeArrayType() { return (TypeImpl)this.Type.MakeArrayType(); } public override Type MakeArrayType(int rank) { return (TypeImpl)this.Type.MakeArrayType(rank); } public override Type MakeByRefType() { throw new NotImplementedException(); } public override Type MakeGenericType(params Type[] argTypes) { return (TypeImpl)this.Type.MakeGenericType(argTypes.Select(t => ((TypeImpl)t).Type).ToArray()); } public override Type MakePointerType() { return (TypeImpl)this.Type.MakePointerType(); } protected override System.Reflection.TypeAttributes GetAttributeFlagsImpl() { System.Reflection.TypeAttributes result = 0; if (this.Type.IsClass) { result |= System.Reflection.TypeAttributes.Class; } if (this.Type.IsInterface) { result |= System.Reflection.TypeAttributes.Interface; } if (this.Type.IsAbstract) { result |= System.Reflection.TypeAttributes.Abstract; } if (this.Type.IsSealed) { result |= System.Reflection.TypeAttributes.Sealed; } return result; } protected override bool IsValueTypeImpl() { return this.Type.IsValueType; } protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotImplementedException(); } protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotImplementedException(); } protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { Debug.Assert(binder == null, "NYI"); Debug.Assert(returnType == null, "NYI"); Debug.Assert(types == null, "NYI"); Debug.Assert(modifiers == null, "NYI"); return new PropertyInfoImpl(Type.GetProperty(name, (System.Reflection.BindingFlags)bindingAttr, binder: null, returnType: null, types: new System.Type[0], modifiers: new System.Reflection.ParameterModifier[0])); } protected override TypeCode GetTypeCodeImpl() { return (TypeCode)System.Type.GetTypeCode(this.Type); } protected override bool HasElementTypeImpl() { return this.Type.HasElementType; } protected override bool IsArrayImpl() { return Type.IsArray; } protected override bool IsByRefImpl() { return Type.IsByRef; } protected override bool IsCOMObjectImpl() { throw new NotImplementedException(); } protected override bool IsContextfulImpl() { throw new NotImplementedException(); } protected override bool IsMarshalByRefImpl() { throw new NotImplementedException(); } protected override bool IsPointerImpl() { return Type.IsPointer; } protected override bool IsPrimitiveImpl() { throw new NotImplementedException(); } public override bool IsAssignableTo(Type c) { throw new NotImplementedException(); } public override string ToString() { return this.Type.ToString(); } public override Type[] GetInterfacesOnType() { var t = this.Type; var builder = ArrayBuilder<Type>.GetInstance(); foreach (var @interface in t.GetInterfaces()) { var map = t.GetInterfaceMap(@interface); if (map.TargetMethods.Any(m => m.DeclaringType == t)) { builder.Add((TypeImpl)@interface); } } return builder.ToArrayAndFree(); } } }
-1
dotnet/roslyn
56,095
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-02T00:01:28Z"
"2021-09-02T01:47:21Z"
212ca8da034e484813ea99027c29cc3f6405fe1f
fe389d485fb73f8186b32636bfc747a39a70b028
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/CSharpTest/Completion/CompletionProviders/TypeImportCompletionProviderTests.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.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders { [UseExportProvider] public class TypeImportCompletionProviderTests : AbstractCSharpCompletionProviderTests { internal override Type GetCompletionProviderType() => typeof(TypeImportCompletionProvider); private bool? ShowImportCompletionItemsOptionValue { get; set; } = true; private bool IsExpandedCompletion { get; set; } = true; private bool HideAdvancedMembers { get; set; } protected override OptionSet WithChangedOptions(OptionSet options) { return base.WithChangedOptions(options) .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, ShowImportCompletionItemsOptionValue) .WithChangedOption(CompletionServiceOptions.IsExpandedCompletion, IsExpandedCompletion) .WithChangedOption(CompletionOptions.HideAdvancedMembers, LanguageNames.CSharp, HideAdvancedMembers); } #region "Option tests" [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OptionSetToNull_ExpEnabled() { TypeImportCompletionFeatureFlag = true; ShowImportCompletionItemsOptionValue = null; var markup = @" class Bar { $$ }"; await VerifyAnyItemExistsAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OptionSetToNull_ExpDisabled() { ShowImportCompletionItemsOptionValue = null; IsExpandedCompletion = false; var markup = @" class Bar { $$ }"; await VerifyNoItemsExistAsync(markup); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OptionSetToFalse(bool isExperimentEnabled) { TypeImportCompletionFeatureFlag = isExperimentEnabled; ShowImportCompletionItemsOptionValue = false; IsExpandedCompletion = false; var markup = @" class Bar { $$ }"; await VerifyNoItemsExistAsync(markup); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OptionSetToTrue(bool isExperimentEnabled) { TypeImportCompletionFeatureFlag = isExperimentEnabled; ShowImportCompletionItemsOptionValue = true; var markup = @" class Bar { $$ }"; await VerifyAnyItemExistsAsync(markup); } #endregion #region "CompletionItem tests" [InlineData("class", (int)Glyph.ClassPublic)] [InlineData("record", (int)Glyph.ClassPublic)] [InlineData("struct", (int)Glyph.StructurePublic)] [InlineData("enum", (int)Glyph.EnumPublic)] [InlineData("interface", (int)Glyph.InterfacePublic)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Show_TopLevel_NoImport_InProject(string typeKind, int glyph) { var file1 = $@" namespace Foo {{ public {typeKind} Bar {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; await VerifyTypeImportItemExistsAsync( CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp), "Bar", glyph: glyph, inlineDescription: "Foo"); } [InlineData("class", (int)Glyph.ClassPublic)] [InlineData("record", (int)Glyph.ClassPublic)] [InlineData("struct", (int)Glyph.StructurePublic)] [InlineData("enum", (int)Glyph.EnumPublic)] [InlineData("interface", (int)Glyph.InterfacePublic)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Show_TopLevelStatement_NoImport_InProject(string typeKind, int glyph) { var file1 = $@" namespace Foo {{ public {typeKind} Bar {{}} }}"; var file2 = @" $$ "; await VerifyTypeImportItemExistsAsync( CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp), "Bar", glyph: glyph, inlineDescription: "Foo"); } [InlineData("class")] [InlineData("record")] [InlineData("struct")] [InlineData("enum")] [InlineData("interface")] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_SameNamespace_InProject(string typeKind) { var file1 = $@" namespace Foo {{ public {typeKind} Bar {{}} }}"; var file2 = @" namespace Foo { class Bat { $$ } }"; await VerifyTypeImportItemIsAbsentAsync( CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp), "Bar", inlineDescription: "Foo"); } [InlineData("class", (int)Glyph.ClassPublic)] [InlineData("record", (int)Glyph.ClassPublic)] [InlineData("struct", (int)Glyph.StructurePublic)] [InlineData("interface", (int)Glyph.InterfacePublic)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Show_TopLevel_MutipleOverrides_NoImport_InProject(string typeKind, int glyph) { var file1 = $@" namespace Foo {{ public {typeKind} Bar {{}} public {typeKind} Bar<T> {{}} public {typeKind} Bar<T1, T2> {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: glyph, inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar", displayTextSuffix: "<>", glyph: glyph, inlineDescription: "Foo"); } [InlineData("class")] [InlineData("record")] [InlineData("struct")] [InlineData("enum")] [InlineData("interface")] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_NestedType_NoImport_InProject(string typeKind) { var file1 = $@" namespace Foo {{ public class Bar {{ public {typeKind} Faz {{}} }} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemIsAbsentAsync(markup, "Faz", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Faz", inlineDescription: "Foo.Bar"); } [InlineData("class")] [InlineData("record")] [InlineData("struct")] [InlineData("enum")] [InlineData("interface")] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_WithImport_InProject(string typeKind) { var file1 = $@" namespace Foo {{ public {typeKind} Bar {{}} }}"; var file2 = @" namespace Baz { using Foo; class Bat { $$ } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Show_TopLevel_Public_NoImport_InReference(bool isProjectReference) { var file1 = $@" namespace Foo {{ public class Bar {{}} public record Bar2 {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar2", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_Public_WithImport_InReference(bool isProjectReference) { var file1 = $@" namespace Foo {{ public class Bar {{}} public record Bar2 {{}} }}"; var file2 = @" using Foo; namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar2", inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_Internal_NoImport_InReference(bool isProjectReference) { var file1 = $@" namespace Foo {{ internal class Bar {{}} internal record Bar2 {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar2", inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TopLevel_OverloadsWithMixedAccessibility_Internal_NoImport_InReference1(bool isProjectReference) { var file1 = $@" namespace Foo {{ internal class Bar {{}} public class Bar<T> {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", displayTextSuffix: "", inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar", displayTextSuffix: "<>", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_OverloadsWithMixedAccessibility_Internal_WithImport_InReference1(bool isProjectReference) { var file1 = $@" namespace Foo {{ internal class Bar {{}} public class Bar<T> {{}} }}"; var file2 = @" using Foo; namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", displayTextSuffix: "", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", displayTextSuffix: "<>", inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TopLevel_OverloadsWithMixedAccessibility_InternalWithIVT_NoImport_InReference1(bool isProjectReference) { var file1 = $@" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Project1"")] namespace Foo {{ internal class Bar {{}} public class Bar<T> {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassInternal, inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar", displayTextSuffix: "<>", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_OverloadsWithMixedAccessibility_InternalWithIVT_WithImport_InReference1(bool isProjectReference) { var file1 = $@" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Project1"")] namespace Foo {{ internal class Bar {{}} public class Bar<T> {{}} }}"; var file2 = @" using Foo; namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", displayTextSuffix: "<>", inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TopLevel_OverloadsWithMixedAccessibility_Internal_NoImport_InReference2(bool isProjectReference) { var file1 = $@" namespace Foo {{ public class Bar {{}} public class Bar<T> {{}} internal class Bar<T1, T2> {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar", displayTextSuffix: "<>", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_OverloadsWithMixedAccessibility_Internal_SameNamespace_InReference2(bool isProjectReference) { var file1 = $@" namespace Foo {{ public class Bar {{}} public class Bar<T> {{}} internal class Bar<T1, T2> {{}} }}"; var file2 = @" namespace Foo.Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", displayTextSuffix: "<>", inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TopLevel_OverloadsWithMixedAccessibility_InternalWithIVT_NoImport_InReference2(bool isProjectReference) { var file1 = $@" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Project1"")] namespace Foo {{ internal class Bar {{}} internal class Bar<T> {{}} internal class Bar<T1, T2> {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassInternal, inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar", displayTextSuffix: "<>", glyph: (int)Glyph.ClassInternal, inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Show_TopLevel_Internal_WithIVT_NoImport_InReference(bool isProjectReference) { var file1 = $@" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Project1"")] namespace Foo {{ internal class Bar {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassInternal, inlineDescription: "Foo"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Show_TopLevel_NoImport_InVBReference() { var file1 = $@" Namespace Bar Public Class Barr End CLass End Namespace"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForProjecWithVBProjectReference(file2, file1, sourceLanguage: LanguageNames.CSharp, rootNamespace: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Barr", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo.Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task VB_MixedCapitalization_Test() { var file1 = $@" Namespace Na Public Class Foo End Class End Namespace Namespace na Public Class Bar End Class End Namespace "; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForProjecWithVBProjectReference(file2, file1, sourceLanguage: LanguageNames.CSharp, rootNamespace: ""); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassPublic, inlineDescription: "Na"); await VerifyTypeImportItemExistsAsync(markup, "Foo", glyph: (int)Glyph.ClassPublic, inlineDescription: "Na"); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "na"); await VerifyTypeImportItemIsAbsentAsync(markup, "Foo", inlineDescription: "na"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task VB_MixedCapitalization_WithImport_Test() { var file1 = $@" Namespace Na Public Class Foo End Class End Namespace Namespace na Public Class Bar End Class End Namespace "; var file2 = @" using Na; namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForProjecWithVBProjectReference(file2, file1, sourceLanguage: LanguageNames.CSharp, rootNamespace: ""); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Na"); await VerifyTypeImportItemIsAbsentAsync(markup, "Foo", inlineDescription: "Na"); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "na"); await VerifyTypeImportItemIsAbsentAsync(markup, "Foo", inlineDescription: "na"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_Internal_NoImport_InVBReference() { var file1 = $@" Namespace Bar Friend Class Barr End CLass End Namespace"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForProjecWithVBProjectReference(file2, file1, sourceLanguage: LanguageNames.CSharp, rootNamespace: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Barr", inlineDescription: "Foo.Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_WithImport_InVBReference() { var file1 = $@" Namespace Bar Public Class Barr End CLass End Namespace"; var file2 = @" using Foo.Bar; namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForProjecWithVBProjectReference(file2, file1, sourceLanguage: LanguageNames.CSharp, rootNamespace: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Barr", inlineDescription: "Foo.Bar"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypesWithIdenticalNameButDifferentNamespaces(bool isProjectReference) { var file1 = $@" namespace Foo {{ public class Bar {{}} public class Bar<T> {{}} }} namespace Baz {{ public class Bar<T> {{}} public class Bar {{}} }}"; var file2 = @" namespace NS { class C { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar", displayTextSuffix: "<>", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassPublic, inlineDescription: "Baz"); await VerifyTypeImportItemExistsAsync(markup, "Bar", displayTextSuffix: "<>", glyph: (int)Glyph.ClassPublic, inlineDescription: "Baz"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestNoCompletionItemWhenThereIsAlias(bool isProjectReference) { var file1 = @" using AliasFoo1 = Foo1.Foo2.Foo3.Foo4; using AliasFoo2 = Foo1.Foo2.Foo3.Foo4.Foo6; namespace Bar { using AliasFoo3 = Foo1.Foo2.Foo3.Foo5; using AliasFoo4 = Foo1.Foo2.Foo3.Foo5.Foo7; public class CC { public static void Main() { F$$ } } }"; var file2 = @" namespace Foo1 { namespace Foo2 { namespace Foo3 { public class Foo4 { public class Foo6 { } } public class Foo5 { public class Foo7 { } } } } }"; var markup = GetMarkupWithReference(file1, file2, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Foo4", "Foo1.Foo2.Foo3"); await VerifyTypeImportItemIsAbsentAsync(markup, "Foo6", "Foo1.Foo2.Foo3"); await VerifyTypeImportItemIsAbsentAsync(markup, "Foo5", "Foo1.Foo2.Foo3"); await VerifyTypeImportItemIsAbsentAsync(markup, "Foo7", "Foo1.Foo2.Foo3"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestAttributesAlias(bool isProjectReference) { var file1 = @" using myAlias = Foo.BarAttribute; using myAlia2 = Foo.BarAttributeDifferentEnding; namespace Foo2 { public class Main { $$ } }"; var file2 = @" namespace Foo { public class BarAttribute: System.Attribute { } public class BarAttributeDifferentEnding: System.Attribute { } }"; var markup = GetMarkupWithReference(file1, file2, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "BarAttribute", "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "BarAttributeDifferentEnding", "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestGenericsAliasHasNoEffect(bool isProjectReference) { var file1 = @" using AliasFoo1 = Foo1.Foo2.Foo3.Foo4<int>; namespace Bar { using AliasFoo2 = Foo1.Foo2.Foo3.Foo5<string>; public class CC { public static void Main() { F$$ } } }"; var file2 = @" namespace Foo1 { namespace Foo2 { namespace Foo3 { public class Foo4<T> { } public class Foo5<U> { } } } }"; var markup = GetMarkupWithReference(file1, file2, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemExistsAsync(markup, "Foo4", (int)Glyph.ClassPublic, "Foo1.Foo2.Foo3", displayTextSuffix: "<>"); await VerifyTypeImportItemExistsAsync(markup, "Foo5", (int)Glyph.ClassPublic, "Foo1.Foo2.Foo3", displayTextSuffix: "<>"); } #endregion #region "Commit Change Tests" [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Commit_NoImport_InProject(SourceCodeKind kind) { var file1 = $@" namespace Foo {{ public class Bar {{ }} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var expectedCodeAfterCommit = @" using Foo; namespace Baz { class Bat { Bar$$ } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "Bar", expectedCodeAfterCommit, sourceCodeKind: kind); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Commit_TopLevelStatement_NoImport_InProject(SourceCodeKind kind) { var file1 = $@" namespace Foo {{ public class Bar {{ }} }}"; var file2 = @" $$ "; var expectedCodeAfterCommit = @"using Foo; Bar$$ "; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "Bar", expectedCodeAfterCommit, sourceCodeKind: kind); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Commit_TopLevelStatement_UnrelatedImport_InProject(SourceCodeKind kind) { var file1 = $@" namespace Foo {{ public class Bar {{ }} }}"; var file2 = @" using System; $$ "; var expectedCodeAfterCommit = @" using System; using Foo; Bar$$ "; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "Bar", expectedCodeAfterCommit, sourceCodeKind: kind); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Commit_NoImport_InVBReference(SourceCodeKind kind) { var file1 = $@" Namespace Bar Public Class Barr End CLass End Namespace"; var file2 = @" namespace Baz { class Bat { $$ } }"; var expectedCodeAfterCommit = @" using Foo.Bar; namespace Baz { class Bat { Barr$$ } }"; var markup = CreateMarkupForProjecWithVBProjectReference(file2, file1, sourceLanguage: LanguageNames.CSharp, rootNamespace: "Foo"); await VerifyCustomCommitProviderAsync(markup, "Barr", expectedCodeAfterCommit, sourceCodeKind: kind); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Commit_NoImport_InPEReference(SourceCodeKind kind) { var markup = $@"<Workspace> <Project Language=""{LanguageNames.CSharp}"" CommonReferences=""true""> <Document FilePath=""CSharpDocument""> class Bar {{ $$ }}</Document> </Project> </Workspace>"; var expectedCodeAfterCommit = @" using System; class Bar { Console$$ }"; await VerifyCustomCommitProviderAsync(markup, "Console", expectedCodeAfterCommit, sourceCodeKind: kind); } #endregion [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_Public_NoImport_InNonGlobalAliasedMetadataReference() { var file1 = $@" namespace Foo {{ public class Bar {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForProjectWithAliasedMetadataReference(file2, "alias1", file1, LanguageNames.CSharp, LanguageNames.CSharp, hasGlobalAlias: false); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Show_TopLevel_Public_NoImport_InGlobalAliasedMetadataReference() { var file1 = $@" namespace Foo {{ public class Bar {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForProjectWithAliasedMetadataReference(file2, "alias1", file1, LanguageNames.CSharp, LanguageNames.CSharp, hasGlobalAlias: true); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_Public_NoImport_InNonGlobalAliasedProjectReference() { var file1 = $@" namespace Foo {{ public class Bar {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForProjectWithAliasedProjectReference(file2, "alias1", file1, LanguageNames.CSharp, LanguageNames.CSharp); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ShorterTypeNameShouldShowBeforeLongerTypeName() { var file1 = $@" namespace Foo {{ public class SomeType {{}} public class SomeTypeWithLongerName {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); var completionList = await GetCompletionListAsync(markup).ConfigureAwait(false); AssertRelativeOrder(new List<string>() { "SomeType", "SomeTypeWithLongerName" }, completionList.Items); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")] public async Task AttributeTypeInAttributeNameContext() { var file1 = @" namespace Foo { public class MyAttribute : System.Attribute { } public class MyAttributeWithoutSuffix : System.Attribute { } public class MyClass { } }"; var file2 = @" namespace Test { [$$ class Program { } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemExistsAsync(markup, "My", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo", expectedDescriptionOrNull: "class Foo.MyAttribute", flags: CompletionItemFlags.Expanded); await VerifyTypeImportItemIsAbsentAsync(markup, "MyAttributeWithoutSuffix", inlineDescription: "Foo"); // We intentionally ignore attribute types without proper suffix for perf reason await VerifyTypeImportItemIsAbsentAsync(markup, "MyAttribute", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "MyClass", inlineDescription: "Foo"); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")] public async Task CommitAttributeTypeInAttributeNameContext(SourceCodeKind kind) { var file1 = @" namespace Foo { public class MyAttribute : System.Attribute { } }"; var file2 = @" namespace Test { [$$ class Program { } }"; var expectedCodeAfterCommit = @" using Foo; namespace Test { [My$$ class Program { } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "My", expectedCodeAfterCommit, sourceCodeKind: kind); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")] public async Task AttributeTypeInNonAttributeNameContext() { var file1 = @" namespace Foo { public class MyAttribute : System.Attribute { } public class MyAttributeWithoutSuffix : System.Attribute { } public class MyClass { } }"; var file2 = @" namespace Test { class Program { $$ } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemExistsAsync(markup, "MyAttribute", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo", expectedDescriptionOrNull: "class Foo.MyAttribute", flags: CompletionItemFlags.CachedAndExpanded); await VerifyTypeImportItemExistsAsync(markup, "MyAttributeWithoutSuffix", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo", expectedDescriptionOrNull: "class Foo.MyAttributeWithoutSuffix", flags: CompletionItemFlags.CachedAndExpanded); await VerifyTypeImportItemIsAbsentAsync(markup, "My", inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "MyClass", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo", expectedDescriptionOrNull: "class Foo.MyClass", flags: CompletionItemFlags.CachedAndExpanded); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")] public async Task CommitAttributeTypeInNonAttributeNameContext(SourceCodeKind kind) { var file1 = @" namespace Foo { public class MyAttribute : System.Attribute { } }"; var file2 = @" namespace Test { class Program { $$ } }"; var expectedCodeAfterCommit = @" using Foo; namespace Test { class Program { MyAttribute$$ } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "MyAttribute", expectedCodeAfterCommit, sourceCodeKind: kind); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")] public async Task AttributeTypeWithoutSuffixInAttributeNameContext() { // attribute suffix isn't capitalized var file1 = @" namespace Foo { public class Myattribute : System.Attribute { } public class MyClass { } }"; var file2 = @" namespace Test { [$$ class Program { } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemExistsAsync(markup, "Myattribute", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo", expectedDescriptionOrNull: "class Foo.Myattribute", flags: CompletionItemFlags.CachedAndExpanded); await VerifyTypeImportItemIsAbsentAsync(markup, "My", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "MyClass", inlineDescription: "Foo"); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")] public async Task CommitAttributeTypeWithoutSuffixInAttributeNameContext(SourceCodeKind kind) { // attribute suffix isn't capitalized var file1 = @" namespace Foo { public class Myattribute : System.Attribute { } }"; var file2 = @" namespace Test { [$$ class Program { } }"; var expectedCodeAfterCommit = @" using Foo; namespace Test { [Myattribute$$ class Program { } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "Myattribute", expectedCodeAfterCommit, sourceCodeKind: kind); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")] public async Task AttributeTypeWithoutSuffixInNonAttributeNameContext() { // attribute suffix isn't capitalized var file1 = @" namespace Foo { public class Myattribute : System.Attribute { } public class MyClass { } }"; var file2 = @" namespace Test { class Program { $$ } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemExistsAsync(markup, "Myattribute", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo", expectedDescriptionOrNull: "class Foo.Myattribute", flags: CompletionItemFlags.Expanded); await VerifyTypeImportItemIsAbsentAsync(markup, "My", inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "MyClass", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo", expectedDescriptionOrNull: "class Foo.MyClass", flags: CompletionItemFlags.CachedAndExpanded); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")] public async Task CommitAttributeTypeWithoutSuffixInNonAttributeNameContext(SourceCodeKind kind) { // attribute suffix isn't capitalized var file1 = @" namespace Foo { public class Myattribute : System.Attribute { } }"; var file2 = @" namespace Test { class Program { $$ } }"; var expectedCodeAfterCommit = @" using Foo; namespace Test { class Program { Myattribute$$ } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "Myattribute", expectedCodeAfterCommit, sourceCodeKind: kind); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")] public async Task VBAttributeTypeWithoutSuffixInAttributeNameContext() { var file1 = @" Namespace Foo Public Class Myattribute Inherits System.Attribute End Class Public Class MyVBClass End Class End Namespace"; var file2 = @" namespace Test { [$$ class Program { } }"; var markup = CreateMarkupForProjectWithProjectReference(file2, file1, LanguageNames.CSharp, LanguageNames.VisualBasic); await VerifyTypeImportItemExistsAsync(markup, "Myattribute", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo", expectedDescriptionOrNull: "class Foo.Myattribute", flags: CompletionItemFlags.Expanded); await VerifyTypeImportItemIsAbsentAsync(markup, "My", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "MyVBClass", inlineDescription: "Foo"); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37038, "https://github.com/dotnet/roslyn/issues/37038")] public async Task CommitTypeInUsingStaticContextShouldUseFullyQualifiedName(SourceCodeKind kind) { var file1 = @" namespace Foo { public class MyClass { } }"; var file2 = @" using static $$"; var expectedCodeAfterCommit = @" using static Foo.MyClass$$"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "MyClass", expectedCodeAfterCommit, sourceCodeKind: kind); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37038, "https://github.com/dotnet/roslyn/issues/37038")] public async Task CommitGenericTypeParameterInUsingAliasContextShouldUseFullyQualifiedName(SourceCodeKind kind) { var file1 = @" namespace Foo { public class MyClass { } }"; var file2 = @" using CollectionOfStringBuilders = System.Collections.Generic.List<$$>"; var expectedCodeAfterCommit = @" using CollectionOfStringBuilders = System.Collections.Generic.List<Foo.MyClass$$>"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "MyClass", expectedCodeAfterCommit, sourceCodeKind: kind); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37038, "https://github.com/dotnet/roslyn/issues/37038")] public async Task CommitGenericTypeParameterInUsingAliasContextShouldUseFullyQualifiedName2(SourceCodeKind kind) { var file1 = @" namespace Foo.Bar { public class MyClass { } }"; var file2 = @" namespace Foo { using CollectionOfStringBuilders = System.Collections.Generic.List<$$> }"; // Completion is not fully qualified var expectedCodeAfterCommit = @" namespace Foo { using CollectionOfStringBuilders = System.Collections.Generic.List<Foo.Bar.MyClass$$> }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "MyClass", expectedCodeAfterCommit, sourceCodeKind: kind); } [Fact] [Trait(Traits.Feature, Traits.Features.Completion)] [Trait(Traits.Feature, Traits.Features.Interactive)] [WorkItem(39027, "https://github.com/dotnet/roslyn/issues/39027")] public async Task TriggerCompletionInSubsequentSubmission() { var markup = @" <Workspace> <Submission Language=""C#"" CommonReferences=""true""> var x = ""10""; </Submission> <Submission Language=""C#"" CommonReferences=""true""> var y = $$ </Submission> </Workspace> "; var completionList = await GetCompletionListAsync(markup, workspaceKind: WorkspaceKind.Interactive).ConfigureAwait(false); Assert.NotEmpty(completionList.Items); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ShouldNotTriggerInsideTrivia() { var file1 = $@" namespace Foo {{ public class Bar {{}} }}"; var file2 = @" namespace Baz { /// <summary> /// <see cref=""B$$""/> /// </summary> class Bat { } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); } private static void AssertRelativeOrder(List<string> expectedTypesInRelativeOrder, ImmutableArray<CompletionItem> allCompletionItems) { var hashset = new HashSet<string>(expectedTypesInRelativeOrder); var actualTypesInRelativeOrder = allCompletionItems.SelectAsArray(item => hashset.Contains(item.DisplayText), item => item.DisplayText); Assert.Equal(expectedTypesInRelativeOrder.Count, actualTypesInRelativeOrder.Length); for (var i = 0; i < expectedTypesInRelativeOrder.Count; ++i) { Assert.Equal(expectedTypesInRelativeOrder[i], actualTypesInRelativeOrder[i]); } } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestBrowsableAwaysFromReferences(bool isProjectReference) { var srcDoc = @" class Program { void M() { $$ } }"; var refDoc = @" namespace Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public class Goo { } }"; var markup = isProjectReference switch { true => CreateMarkupForProjectWithProjectReference(srcDoc, refDoc, LanguageNames.CSharp, LanguageNames.CSharp), false => CreateMarkupForProjectWithMetadataReference(srcDoc, refDoc, LanguageNames.CSharp, LanguageNames.CSharp) }; await VerifyTypeImportItemExistsAsync( markup, "Goo", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestBrowsableNeverFromReferences(bool isProjectReference) { var srcDoc = @" class Program { void M() { $$ } }"; var refDoc = @" namespace Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public class Goo { } }"; var (markup, shouldContainItem) = isProjectReference switch { true => (CreateMarkupForProjectWithProjectReference(srcDoc, refDoc, LanguageNames.CSharp, LanguageNames.CSharp), true), false => (CreateMarkupForProjectWithMetadataReference(srcDoc, refDoc, LanguageNames.CSharp, LanguageNames.CSharp), false), }; if (shouldContainItem) { await VerifyTypeImportItemExistsAsync( markup, "Goo", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); } else { await VerifyTypeImportItemIsAbsentAsync( markup, "Goo", inlineDescription: "Foo"); } } [InlineData(true, true)] [InlineData(true, false)] [InlineData(false, true)] [InlineData(false, false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestBrowsableAdvancedFromReferences(bool isProjectReference, bool hideAdvancedMembers) { HideAdvancedMembers = hideAdvancedMembers; var srcDoc = @" class Program { void M() { $$ } }"; var refDoc = @" namespace Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public class Goo { } }"; var (markup, shouldContainItem) = isProjectReference switch { true => (CreateMarkupForProjectWithProjectReference(srcDoc, refDoc, LanguageNames.CSharp, LanguageNames.CSharp), true), false => (CreateMarkupForProjectWithMetadataReference(srcDoc, refDoc, LanguageNames.CSharp, LanguageNames.CSharp), !hideAdvancedMembers), }; if (shouldContainItem) { await VerifyTypeImportItemExistsAsync( markup, "Goo", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); } else { await VerifyTypeImportItemIsAbsentAsync( markup, "Goo", inlineDescription: "Foo"); } } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData('.')] [InlineData(';')] public async Task TestCommitWithCustomizedCommitCharForParameterlessConstructor(char commitChar) { var markup = @" namespace AA { public class C { } } namespace BB { public class B { public void M() { var c = new $$ } } }"; var expected = $@" using AA; namespace AA {{ public class C {{ }} }} namespace BB {{ public class B {{ public void M() {{ var c = new C(){commitChar} }} }} }}"; await VerifyProviderCommitAsync(markup, "C", expected, commitChar: commitChar, sourceCodeKind: SourceCodeKind.Regular); } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData('.')] [InlineData(';')] public async Task TestCommitWithCustomizedCommitCharUnderNonObjectCreationContext(char commitChar) { var markup = @" namespace AA { public class C { } } namespace BB { public class B { public void M() { $$ } } }"; var expected = $@" using AA; namespace AA {{ public class C {{ }} }} namespace BB {{ public class B {{ public void M() {{ C{commitChar} }} }} }}"; await VerifyProviderCommitAsync(markup, "C", expected, commitChar: commitChar, sourceCodeKind: SourceCodeKind.Regular); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(54493, "https://github.com/dotnet/roslyn/issues/54493")] public async Task CommitInLocalFunctionContext(SourceCodeKind kind) { var markup = @" namespace Foo { public class MyClass { } } namespace Test { class Program { public static void Main() { static $$ } } }"; var expectedCodeAfterCommit = @" using Foo; namespace Foo { public class MyClass { } } namespace Test { class Program { public static void Main() { static MyClass } } }"; await VerifyProviderCommitAsync(markup, "MyClass", expectedCodeAfterCommit, commitChar: null, sourceCodeKind: kind); } private Task VerifyTypeImportItemExistsAsync(string markup, string expectedItem, int glyph, string inlineDescription, string displayTextSuffix = null, string expectedDescriptionOrNull = null, CompletionItemFlags? flags = null) => VerifyItemExistsAsync(markup, expectedItem, displayTextSuffix: displayTextSuffix, glyph: glyph, inlineDescription: inlineDescription, expectedDescriptionOrNull: expectedDescriptionOrNull, isComplexTextEdit: true, flags: flags); private Task VerifyTypeImportItemIsAbsentAsync(string markup, string expectedItem, string inlineDescription, string displayTextSuffix = null) => VerifyItemIsAbsentAsync(markup, expectedItem, displayTextSuffix: displayTextSuffix, inlineDescription: inlineDescription); } }
// Licensed to the .NET Foundation under one or more 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.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders { [UseExportProvider] public class TypeImportCompletionProviderTests : AbstractCSharpCompletionProviderTests { internal override Type GetCompletionProviderType() => typeof(TypeImportCompletionProvider); private bool? ShowImportCompletionItemsOptionValue { get; set; } = true; private bool IsExpandedCompletion { get; set; } = true; private bool HideAdvancedMembers { get; set; } protected override OptionSet WithChangedOptions(OptionSet options) { return base.WithChangedOptions(options) .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, ShowImportCompletionItemsOptionValue) .WithChangedOption(CompletionServiceOptions.IsExpandedCompletion, IsExpandedCompletion) .WithChangedOption(CompletionOptions.HideAdvancedMembers, LanguageNames.CSharp, HideAdvancedMembers); } #region "Option tests" [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OptionSetToNull_ExpEnabled() { TypeImportCompletionFeatureFlag = true; ShowImportCompletionItemsOptionValue = null; var markup = @" class Bar { $$ }"; await VerifyAnyItemExistsAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OptionSetToNull_ExpDisabled() { ShowImportCompletionItemsOptionValue = null; IsExpandedCompletion = false; var markup = @" class Bar { $$ }"; await VerifyNoItemsExistAsync(markup); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OptionSetToFalse(bool isExperimentEnabled) { TypeImportCompletionFeatureFlag = isExperimentEnabled; ShowImportCompletionItemsOptionValue = false; IsExpandedCompletion = false; var markup = @" class Bar { $$ }"; await VerifyNoItemsExistAsync(markup); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OptionSetToTrue(bool isExperimentEnabled) { TypeImportCompletionFeatureFlag = isExperimentEnabled; ShowImportCompletionItemsOptionValue = true; var markup = @" class Bar { $$ }"; await VerifyAnyItemExistsAsync(markup); } #endregion #region "CompletionItem tests" [InlineData("class", (int)Glyph.ClassPublic)] [InlineData("record", (int)Glyph.ClassPublic)] [InlineData("struct", (int)Glyph.StructurePublic)] [InlineData("enum", (int)Glyph.EnumPublic)] [InlineData("interface", (int)Glyph.InterfacePublic)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Show_TopLevel_NoImport_InProject(string typeKind, int glyph) { var file1 = $@" namespace Foo {{ public {typeKind} Bar {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; await VerifyTypeImportItemExistsAsync( CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp), "Bar", glyph: glyph, inlineDescription: "Foo"); } [InlineData("class", (int)Glyph.ClassPublic)] [InlineData("record", (int)Glyph.ClassPublic)] [InlineData("struct", (int)Glyph.StructurePublic)] [InlineData("enum", (int)Glyph.EnumPublic)] [InlineData("interface", (int)Glyph.InterfacePublic)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Show_TopLevelStatement_NoImport_InProject(string typeKind, int glyph) { var file1 = $@" namespace Foo {{ public {typeKind} Bar {{}} }}"; var file2 = @" $$ "; await VerifyTypeImportItemExistsAsync( CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp), "Bar", glyph: glyph, inlineDescription: "Foo"); } [InlineData("class")] [InlineData("record")] [InlineData("struct")] [InlineData("enum")] [InlineData("interface")] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_SameNamespace_InProject(string typeKind) { var file1 = $@" namespace Foo {{ public {typeKind} Bar {{}} }}"; var file2 = @" namespace Foo { class Bat { $$ } }"; await VerifyTypeImportItemIsAbsentAsync( CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp), "Bar", inlineDescription: "Foo"); } [InlineData("class", (int)Glyph.ClassPublic)] [InlineData("record", (int)Glyph.ClassPublic)] [InlineData("struct", (int)Glyph.StructurePublic)] [InlineData("interface", (int)Glyph.InterfacePublic)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Show_TopLevel_MutipleOverrides_NoImport_InProject(string typeKind, int glyph) { var file1 = $@" namespace Foo {{ public {typeKind} Bar {{}} public {typeKind} Bar<T> {{}} public {typeKind} Bar<T1, T2> {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: glyph, inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar", displayTextSuffix: "<>", glyph: glyph, inlineDescription: "Foo"); } [InlineData("class")] [InlineData("record")] [InlineData("struct")] [InlineData("enum")] [InlineData("interface")] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_NestedType_NoImport_InProject(string typeKind) { var file1 = $@" namespace Foo {{ public class Bar {{ public {typeKind} Faz {{}} }} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemIsAbsentAsync(markup, "Faz", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Faz", inlineDescription: "Foo.Bar"); } [InlineData("class")] [InlineData("record")] [InlineData("struct")] [InlineData("enum")] [InlineData("interface")] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_WithImport_InProject(string typeKind) { var file1 = $@" namespace Foo {{ public {typeKind} Bar {{}} }}"; var file2 = @" namespace Baz { using Foo; class Bat { $$ } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Show_TopLevel_Public_NoImport_InReference(bool isProjectReference) { var file1 = $@" namespace Foo {{ public class Bar {{}} public record Bar2 {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar2", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_Public_WithImport_InReference(bool isProjectReference) { var file1 = $@" namespace Foo {{ public class Bar {{}} public record Bar2 {{}} }}"; var file2 = @" using Foo; namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar2", inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_Internal_NoImport_InReference(bool isProjectReference) { var file1 = $@" namespace Foo {{ internal class Bar {{}} internal record Bar2 {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar2", inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TopLevel_OverloadsWithMixedAccessibility_Internal_NoImport_InReference1(bool isProjectReference) { var file1 = $@" namespace Foo {{ internal class Bar {{}} public class Bar<T> {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", displayTextSuffix: "", inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar", displayTextSuffix: "<>", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_OverloadsWithMixedAccessibility_Internal_WithImport_InReference1(bool isProjectReference) { var file1 = $@" namespace Foo {{ internal class Bar {{}} public class Bar<T> {{}} }}"; var file2 = @" using Foo; namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", displayTextSuffix: "", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", displayTextSuffix: "<>", inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TopLevel_OverloadsWithMixedAccessibility_InternalWithIVT_NoImport_InReference1(bool isProjectReference) { var file1 = $@" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Project1"")] namespace Foo {{ internal class Bar {{}} public class Bar<T> {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassInternal, inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar", displayTextSuffix: "<>", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_OverloadsWithMixedAccessibility_InternalWithIVT_WithImport_InReference1(bool isProjectReference) { var file1 = $@" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Project1"")] namespace Foo {{ internal class Bar {{}} public class Bar<T> {{}} }}"; var file2 = @" using Foo; namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", displayTextSuffix: "<>", inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TopLevel_OverloadsWithMixedAccessibility_Internal_NoImport_InReference2(bool isProjectReference) { var file1 = $@" namespace Foo {{ public class Bar {{}} public class Bar<T> {{}} internal class Bar<T1, T2> {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar", displayTextSuffix: "<>", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_OverloadsWithMixedAccessibility_Internal_SameNamespace_InReference2(bool isProjectReference) { var file1 = $@" namespace Foo {{ public class Bar {{}} public class Bar<T> {{}} internal class Bar<T1, T2> {{}} }}"; var file2 = @" namespace Foo.Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", displayTextSuffix: "<>", inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TopLevel_OverloadsWithMixedAccessibility_InternalWithIVT_NoImport_InReference2(bool isProjectReference) { var file1 = $@" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Project1"")] namespace Foo {{ internal class Bar {{}} internal class Bar<T> {{}} internal class Bar<T1, T2> {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassInternal, inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar", displayTextSuffix: "<>", glyph: (int)Glyph.ClassInternal, inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Show_TopLevel_Internal_WithIVT_NoImport_InReference(bool isProjectReference) { var file1 = $@" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Project1"")] namespace Foo {{ internal class Bar {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassInternal, inlineDescription: "Foo"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Show_TopLevel_NoImport_InVBReference() { var file1 = $@" Namespace Bar Public Class Barr End CLass End Namespace"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForProjecWithVBProjectReference(file2, file1, sourceLanguage: LanguageNames.CSharp, rootNamespace: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Barr", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo.Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task VB_MixedCapitalization_Test() { var file1 = $@" Namespace Na Public Class Foo End Class End Namespace Namespace na Public Class Bar End Class End Namespace "; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForProjecWithVBProjectReference(file2, file1, sourceLanguage: LanguageNames.CSharp, rootNamespace: ""); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassPublic, inlineDescription: "Na"); await VerifyTypeImportItemExistsAsync(markup, "Foo", glyph: (int)Glyph.ClassPublic, inlineDescription: "Na"); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "na"); await VerifyTypeImportItemIsAbsentAsync(markup, "Foo", inlineDescription: "na"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task VB_MixedCapitalization_WithImport_Test() { var file1 = $@" Namespace Na Public Class Foo End Class End Namespace Namespace na Public Class Bar End Class End Namespace "; var file2 = @" using Na; namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForProjecWithVBProjectReference(file2, file1, sourceLanguage: LanguageNames.CSharp, rootNamespace: ""); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Na"); await VerifyTypeImportItemIsAbsentAsync(markup, "Foo", inlineDescription: "Na"); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "na"); await VerifyTypeImportItemIsAbsentAsync(markup, "Foo", inlineDescription: "na"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_Internal_NoImport_InVBReference() { var file1 = $@" Namespace Bar Friend Class Barr End CLass End Namespace"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForProjecWithVBProjectReference(file2, file1, sourceLanguage: LanguageNames.CSharp, rootNamespace: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Barr", inlineDescription: "Foo.Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_WithImport_InVBReference() { var file1 = $@" Namespace Bar Public Class Barr End CLass End Namespace"; var file2 = @" using Foo.Bar; namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForProjecWithVBProjectReference(file2, file1, sourceLanguage: LanguageNames.CSharp, rootNamespace: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "Barr", inlineDescription: "Foo.Bar"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypesWithIdenticalNameButDifferentNamespaces(bool isProjectReference) { var file1 = $@" namespace Foo {{ public class Bar {{}} public class Bar<T> {{}} }} namespace Baz {{ public class Bar<T> {{}} public class Bar {{}} }}"; var file2 = @" namespace NS { class C { $$ } }"; var markup = GetMarkupWithReference(file2, file1, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar", displayTextSuffix: "<>", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassPublic, inlineDescription: "Baz"); await VerifyTypeImportItemExistsAsync(markup, "Bar", displayTextSuffix: "<>", glyph: (int)Glyph.ClassPublic, inlineDescription: "Baz"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestNoCompletionItemWhenThereIsAlias(bool isProjectReference) { var file1 = @" using AliasFoo1 = Foo1.Foo2.Foo3.Foo4; using AliasFoo2 = Foo1.Foo2.Foo3.Foo4.Foo6; namespace Bar { using AliasFoo3 = Foo1.Foo2.Foo3.Foo5; using AliasFoo4 = Foo1.Foo2.Foo3.Foo5.Foo7; public class CC { public static void Main() { F$$ } } }"; var file2 = @" namespace Foo1 { namespace Foo2 { namespace Foo3 { public class Foo4 { public class Foo6 { } } public class Foo5 { public class Foo7 { } } } } }"; var markup = GetMarkupWithReference(file1, file2, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Foo4", "Foo1.Foo2.Foo3"); await VerifyTypeImportItemIsAbsentAsync(markup, "Foo6", "Foo1.Foo2.Foo3"); await VerifyTypeImportItemIsAbsentAsync(markup, "Foo5", "Foo1.Foo2.Foo3"); await VerifyTypeImportItemIsAbsentAsync(markup, "Foo7", "Foo1.Foo2.Foo3"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestAttributesAlias(bool isProjectReference) { var file1 = @" using myAlias = Foo.BarAttribute; using myAlia2 = Foo.BarAttributeDifferentEnding; namespace Foo2 { public class Main { $$ } }"; var file2 = @" namespace Foo { public class BarAttribute: System.Attribute { } public class BarAttributeDifferentEnding: System.Attribute { } }"; var markup = GetMarkupWithReference(file1, file2, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "BarAttribute", "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "BarAttributeDifferentEnding", "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestGenericsAliasHasNoEffect(bool isProjectReference) { var file1 = @" using AliasFoo1 = Foo1.Foo2.Foo3.Foo4<int>; namespace Bar { using AliasFoo2 = Foo1.Foo2.Foo3.Foo5<string>; public class CC { public static void Main() { F$$ } } }"; var file2 = @" namespace Foo1 { namespace Foo2 { namespace Foo3 { public class Foo4<T> { } public class Foo5<U> { } } } }"; var markup = GetMarkupWithReference(file1, file2, LanguageNames.CSharp, LanguageNames.CSharp, isProjectReference); await VerifyTypeImportItemExistsAsync(markup, "Foo4", (int)Glyph.ClassPublic, "Foo1.Foo2.Foo3", displayTextSuffix: "<>"); await VerifyTypeImportItemExistsAsync(markup, "Foo5", (int)Glyph.ClassPublic, "Foo1.Foo2.Foo3", displayTextSuffix: "<>"); } #endregion #region "Commit Change Tests" [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Commit_NoImport_InProject(SourceCodeKind kind) { var file1 = $@" namespace Foo {{ public class Bar {{ }} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var expectedCodeAfterCommit = @" using Foo; namespace Baz { class Bat { Bar$$ } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "Bar", expectedCodeAfterCommit, sourceCodeKind: kind); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Commit_TopLevelStatement_NoImport_InProject(SourceCodeKind kind) { var file1 = $@" namespace Foo {{ public class Bar {{ }} }}"; var file2 = @" $$ "; var expectedCodeAfterCommit = @"using Foo; Bar$$ "; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "Bar", expectedCodeAfterCommit, sourceCodeKind: kind); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Commit_TopLevelStatement_UnrelatedImport_InProject(SourceCodeKind kind) { var file1 = $@" namespace Foo {{ public class Bar {{ }} }}"; var file2 = @" using System; $$ "; var expectedCodeAfterCommit = @" using System; using Foo; Bar$$ "; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "Bar", expectedCodeAfterCommit, sourceCodeKind: kind); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Commit_NoImport_InVBReference(SourceCodeKind kind) { var file1 = $@" Namespace Bar Public Class Barr End CLass End Namespace"; var file2 = @" namespace Baz { class Bat { $$ } }"; var expectedCodeAfterCommit = @" using Foo.Bar; namespace Baz { class Bat { Barr$$ } }"; var markup = CreateMarkupForProjecWithVBProjectReference(file2, file1, sourceLanguage: LanguageNames.CSharp, rootNamespace: "Foo"); await VerifyCustomCommitProviderAsync(markup, "Barr", expectedCodeAfterCommit, sourceCodeKind: kind); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Commit_NoImport_InPEReference(SourceCodeKind kind) { var markup = $@"<Workspace> <Project Language=""{LanguageNames.CSharp}"" CommonReferences=""true""> <Document FilePath=""CSharpDocument""> class Bar {{ $$ }}</Document> </Project> </Workspace>"; var expectedCodeAfterCommit = @" using System; class Bar { Console$$ }"; await VerifyCustomCommitProviderAsync(markup, "Console", expectedCodeAfterCommit, sourceCodeKind: kind); } #endregion [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_Public_NoImport_InNonGlobalAliasedMetadataReference() { var file1 = $@" namespace Foo {{ public class Bar {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForProjectWithAliasedMetadataReference(file2, "alias1", file1, LanguageNames.CSharp, LanguageNames.CSharp, hasGlobalAlias: false); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Show_TopLevel_Public_NoImport_InGlobalAliasedMetadataReference() { var file1 = $@" namespace Foo {{ public class Bar {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForProjectWithAliasedMetadataReference(file2, "alias1", file1, LanguageNames.CSharp, LanguageNames.CSharp, hasGlobalAlias: true); await VerifyTypeImportItemExistsAsync(markup, "Bar", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotShow_TopLevel_Public_NoImport_InNonGlobalAliasedProjectReference() { var file1 = $@" namespace Foo {{ public class Bar {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForProjectWithAliasedProjectReference(file2, "alias1", file1, LanguageNames.CSharp, LanguageNames.CSharp); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ShorterTypeNameShouldShowBeforeLongerTypeName() { var file1 = $@" namespace Foo {{ public class SomeType {{}} public class SomeTypeWithLongerName {{}} }}"; var file2 = @" namespace Baz { class Bat { $$ } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); var completionList = await GetCompletionListAsync(markup).ConfigureAwait(false); AssertRelativeOrder(new List<string>() { "SomeType", "SomeTypeWithLongerName" }, completionList.Items); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")] public async Task AttributeTypeInAttributeNameContext() { var file1 = @" namespace Foo { public class MyAttribute : System.Attribute { } public class MyAttributeWithoutSuffix : System.Attribute { } public class MyClass { } }"; var file2 = @" namespace Test { [$$ class Program { } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemExistsAsync(markup, "My", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo", expectedDescriptionOrNull: "class Foo.MyAttribute", flags: CompletionItemFlags.Expanded); await VerifyTypeImportItemIsAbsentAsync(markup, "MyAttributeWithoutSuffix", inlineDescription: "Foo"); // We intentionally ignore attribute types without proper suffix for perf reason await VerifyTypeImportItemIsAbsentAsync(markup, "MyAttribute", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "MyClass", inlineDescription: "Foo"); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")] public async Task CommitAttributeTypeInAttributeNameContext(SourceCodeKind kind) { var file1 = @" namespace Foo { public class MyAttribute : System.Attribute { } }"; var file2 = @" namespace Test { [$$ class Program { } }"; var expectedCodeAfterCommit = @" using Foo; namespace Test { [My$$ class Program { } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "My", expectedCodeAfterCommit, sourceCodeKind: kind); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")] public async Task AttributeTypeInNonAttributeNameContext() { var file1 = @" namespace Foo { public class MyAttribute : System.Attribute { } public class MyAttributeWithoutSuffix : System.Attribute { } public class MyClass { } }"; var file2 = @" namespace Test { class Program { $$ } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemExistsAsync(markup, "MyAttribute", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo", expectedDescriptionOrNull: "class Foo.MyAttribute", flags: CompletionItemFlags.CachedAndExpanded); await VerifyTypeImportItemExistsAsync(markup, "MyAttributeWithoutSuffix", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo", expectedDescriptionOrNull: "class Foo.MyAttributeWithoutSuffix", flags: CompletionItemFlags.CachedAndExpanded); await VerifyTypeImportItemIsAbsentAsync(markup, "My", inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "MyClass", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo", expectedDescriptionOrNull: "class Foo.MyClass", flags: CompletionItemFlags.CachedAndExpanded); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")] public async Task CommitAttributeTypeInNonAttributeNameContext(SourceCodeKind kind) { var file1 = @" namespace Foo { public class MyAttribute : System.Attribute { } }"; var file2 = @" namespace Test { class Program { $$ } }"; var expectedCodeAfterCommit = @" using Foo; namespace Test { class Program { MyAttribute$$ } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "MyAttribute", expectedCodeAfterCommit, sourceCodeKind: kind); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")] public async Task AttributeTypeWithoutSuffixInAttributeNameContext() { // attribute suffix isn't capitalized var file1 = @" namespace Foo { public class Myattribute : System.Attribute { } public class MyClass { } }"; var file2 = @" namespace Test { [$$ class Program { } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemExistsAsync(markup, "Myattribute", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo", expectedDescriptionOrNull: "class Foo.Myattribute", flags: CompletionItemFlags.CachedAndExpanded); await VerifyTypeImportItemIsAbsentAsync(markup, "My", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "MyClass", inlineDescription: "Foo"); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")] public async Task CommitAttributeTypeWithoutSuffixInAttributeNameContext(SourceCodeKind kind) { // attribute suffix isn't capitalized var file1 = @" namespace Foo { public class Myattribute : System.Attribute { } }"; var file2 = @" namespace Test { [$$ class Program { } }"; var expectedCodeAfterCommit = @" using Foo; namespace Test { [Myattribute$$ class Program { } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "Myattribute", expectedCodeAfterCommit, sourceCodeKind: kind); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")] public async Task AttributeTypeWithoutSuffixInNonAttributeNameContext() { // attribute suffix isn't capitalized var file1 = @" namespace Foo { public class Myattribute : System.Attribute { } public class MyClass { } }"; var file2 = @" namespace Test { class Program { $$ } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemExistsAsync(markup, "Myattribute", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo", expectedDescriptionOrNull: "class Foo.Myattribute", flags: CompletionItemFlags.Expanded); await VerifyTypeImportItemIsAbsentAsync(markup, "My", inlineDescription: "Foo"); await VerifyTypeImportItemExistsAsync(markup, "MyClass", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo", expectedDescriptionOrNull: "class Foo.MyClass", flags: CompletionItemFlags.CachedAndExpanded); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")] public async Task CommitAttributeTypeWithoutSuffixInNonAttributeNameContext(SourceCodeKind kind) { // attribute suffix isn't capitalized var file1 = @" namespace Foo { public class Myattribute : System.Attribute { } }"; var file2 = @" namespace Test { class Program { $$ } }"; var expectedCodeAfterCommit = @" using Foo; namespace Test { class Program { Myattribute$$ } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "Myattribute", expectedCodeAfterCommit, sourceCodeKind: kind); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")] public async Task VBAttributeTypeWithoutSuffixInAttributeNameContext() { var file1 = @" Namespace Foo Public Class Myattribute Inherits System.Attribute End Class Public Class MyVBClass End Class End Namespace"; var file2 = @" namespace Test { [$$ class Program { } }"; var markup = CreateMarkupForProjectWithProjectReference(file2, file1, LanguageNames.CSharp, LanguageNames.VisualBasic); await VerifyTypeImportItemExistsAsync(markup, "Myattribute", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo", expectedDescriptionOrNull: "class Foo.Myattribute", flags: CompletionItemFlags.Expanded); await VerifyTypeImportItemIsAbsentAsync(markup, "My", inlineDescription: "Foo"); await VerifyTypeImportItemIsAbsentAsync(markup, "MyVBClass", inlineDescription: "Foo"); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37038, "https://github.com/dotnet/roslyn/issues/37038")] public async Task CommitTypeInUsingStaticContextShouldUseFullyQualifiedName(SourceCodeKind kind) { var file1 = @" namespace Foo { public class MyClass { } }"; var file2 = @" using static $$"; var expectedCodeAfterCommit = @" using static Foo.MyClass$$"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "MyClass", expectedCodeAfterCommit, sourceCodeKind: kind); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37038, "https://github.com/dotnet/roslyn/issues/37038")] public async Task CommitGenericTypeParameterInUsingAliasContextShouldUseFullyQualifiedName(SourceCodeKind kind) { var file1 = @" namespace Foo { public class MyClass { } }"; var file2 = @" using CollectionOfStringBuilders = System.Collections.Generic.List<$$>"; var expectedCodeAfterCommit = @" using CollectionOfStringBuilders = System.Collections.Generic.List<Foo.MyClass$$>"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "MyClass", expectedCodeAfterCommit, sourceCodeKind: kind); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37038, "https://github.com/dotnet/roslyn/issues/37038")] public async Task CommitGenericTypeParameterInUsingAliasContextShouldUseFullyQualifiedName2(SourceCodeKind kind) { var file1 = @" namespace Foo.Bar { public class MyClass { } }"; var file2 = @" namespace Foo { using CollectionOfStringBuilders = System.Collections.Generic.List<$$> }"; // Completion is not fully qualified var expectedCodeAfterCommit = @" namespace Foo { using CollectionOfStringBuilders = System.Collections.Generic.List<Foo.Bar.MyClass$$> }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyCustomCommitProviderAsync(markup, "MyClass", expectedCodeAfterCommit, sourceCodeKind: kind); } [Fact] [Trait(Traits.Feature, Traits.Features.Completion)] [Trait(Traits.Feature, Traits.Features.Interactive)] [WorkItem(39027, "https://github.com/dotnet/roslyn/issues/39027")] public async Task TriggerCompletionInSubsequentSubmission() { var markup = @" <Workspace> <Submission Language=""C#"" CommonReferences=""true""> var x = ""10""; </Submission> <Submission Language=""C#"" CommonReferences=""true""> var y = $$ </Submission> </Workspace> "; var completionList = await GetCompletionListAsync(markup, workspaceKind: WorkspaceKind.Interactive).ConfigureAwait(false); Assert.NotEmpty(completionList.Items); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ShouldNotTriggerInsideTrivia() { var file1 = $@" namespace Foo {{ public class Bar {{}} }}"; var file2 = @" namespace Baz { /// <summary> /// <see cref=""B$$""/> /// </summary> class Bat { } }"; var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "Foo"); } private static void AssertRelativeOrder(List<string> expectedTypesInRelativeOrder, ImmutableArray<CompletionItem> allCompletionItems) { var hashset = new HashSet<string>(expectedTypesInRelativeOrder); var actualTypesInRelativeOrder = allCompletionItems.SelectAsArray(item => hashset.Contains(item.DisplayText), item => item.DisplayText); Assert.Equal(expectedTypesInRelativeOrder.Count, actualTypesInRelativeOrder.Length); for (var i = 0; i < expectedTypesInRelativeOrder.Count; ++i) { Assert.Equal(expectedTypesInRelativeOrder[i], actualTypesInRelativeOrder[i]); } } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestBrowsableAwaysFromReferences(bool isProjectReference) { var srcDoc = @" class Program { void M() { $$ } }"; var refDoc = @" namespace Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public class Goo { } }"; var markup = isProjectReference switch { true => CreateMarkupForProjectWithProjectReference(srcDoc, refDoc, LanguageNames.CSharp, LanguageNames.CSharp), false => CreateMarkupForProjectWithMetadataReference(srcDoc, refDoc, LanguageNames.CSharp, LanguageNames.CSharp) }; await VerifyTypeImportItemExistsAsync( markup, "Goo", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); } [InlineData(true)] [InlineData(false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestBrowsableNeverFromReferences(bool isProjectReference) { var srcDoc = @" class Program { void M() { $$ } }"; var refDoc = @" namespace Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public class Goo { } }"; var (markup, shouldContainItem) = isProjectReference switch { true => (CreateMarkupForProjectWithProjectReference(srcDoc, refDoc, LanguageNames.CSharp, LanguageNames.CSharp), true), false => (CreateMarkupForProjectWithMetadataReference(srcDoc, refDoc, LanguageNames.CSharp, LanguageNames.CSharp), false), }; if (shouldContainItem) { await VerifyTypeImportItemExistsAsync( markup, "Goo", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); } else { await VerifyTypeImportItemIsAbsentAsync( markup, "Goo", inlineDescription: "Foo"); } } [InlineData(true, true)] [InlineData(true, false)] [InlineData(false, true)] [InlineData(false, false)] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestBrowsableAdvancedFromReferences(bool isProjectReference, bool hideAdvancedMembers) { HideAdvancedMembers = hideAdvancedMembers; var srcDoc = @" class Program { void M() { $$ } }"; var refDoc = @" namespace Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public class Goo { } }"; var (markup, shouldContainItem) = isProjectReference switch { true => (CreateMarkupForProjectWithProjectReference(srcDoc, refDoc, LanguageNames.CSharp, LanguageNames.CSharp), true), false => (CreateMarkupForProjectWithMetadataReference(srcDoc, refDoc, LanguageNames.CSharp, LanguageNames.CSharp), !hideAdvancedMembers), }; if (shouldContainItem) { await VerifyTypeImportItemExistsAsync( markup, "Goo", glyph: (int)Glyph.ClassPublic, inlineDescription: "Foo"); } else { await VerifyTypeImportItemIsAbsentAsync( markup, "Goo", inlineDescription: "Foo"); } } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData('.')] [InlineData(';')] public async Task TestCommitWithCustomizedCommitCharForParameterlessConstructor(char commitChar) { var markup = @" namespace AA { public class C { } } namespace BB { public class B { public void M() { var c = new $$ } } }"; var expected = $@" using AA; namespace AA {{ public class C {{ }} }} namespace BB {{ public class B {{ public void M() {{ var c = new C(){commitChar} }} }} }}"; await VerifyProviderCommitAsync(markup, "C", expected, commitChar: commitChar, sourceCodeKind: SourceCodeKind.Regular); } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData('.')] [InlineData(';')] public async Task TestCommitWithCustomizedCommitCharUnderNonObjectCreationContext(char commitChar) { var markup = @" namespace AA { public class C { } } namespace BB { public class B { public void M() { $$ } } }"; var expected = $@" using AA; namespace AA {{ public class C {{ }} }} namespace BB {{ public class B {{ public void M() {{ C{commitChar} }} }} }}"; await VerifyProviderCommitAsync(markup, "C", expected, commitChar: commitChar, sourceCodeKind: SourceCodeKind.Regular); } [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(54493, "https://github.com/dotnet/roslyn/issues/54493")] public async Task CommitInLocalFunctionContext(SourceCodeKind kind) { var markup = @" namespace Foo { public class MyClass { } } namespace Test { class Program { public static void Main() { static $$ } } }"; var expectedCodeAfterCommit = @" using Foo; namespace Foo { public class MyClass { } } namespace Test { class Program { public static void Main() { static MyClass } } }"; await VerifyProviderCommitAsync(markup, "MyClass", expectedCodeAfterCommit, commitChar: null, sourceCodeKind: kind); } private Task VerifyTypeImportItemExistsAsync(string markup, string expectedItem, int glyph, string inlineDescription, string displayTextSuffix = null, string expectedDescriptionOrNull = null, CompletionItemFlags? flags = null) => VerifyItemExistsAsync(markup, expectedItem, displayTextSuffix: displayTextSuffix, glyph: glyph, inlineDescription: inlineDescription, expectedDescriptionOrNull: expectedDescriptionOrNull, isComplexTextEdit: true, flags: flags); private Task VerifyTypeImportItemIsAbsentAsync(string markup, string expectedItem, string inlineDescription, string displayTextSuffix = null) => VerifyItemIsAbsentAsync(markup, expectedItem, displayTextSuffix: displayTextSuffix, inlineDescription: inlineDescription); } }
-1
dotnet/roslyn
56,095
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-02T00:01:28Z"
"2021-09-02T01:47:21Z"
212ca8da034e484813ea99027c29cc3f6405fe1f
fe389d485fb73f8186b32636bfc747a39a70b028
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Scripting/CSharp/ScriptOptionsExtensions.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 Microsoft.CodeAnalysis.Scripting; namespace Microsoft.CodeAnalysis.CSharp.Scripting { public static class ScriptOptionsExtensions { public static ScriptOptions WithLanguageVersion(this ScriptOptions options, LanguageVersion languageVersion) { var parseOptions = (options.ParseOptions is null) ? CSharpScriptCompiler.DefaultParseOptions : (options.ParseOptions is CSharpParseOptions existing) ? existing : throw new InvalidOperationException(string.Format(ScriptingResources.CannotSetLanguageSpecificOption, LanguageNames.CSharp, nameof(LanguageVersion))); return options.WithParseOptions(parseOptions.WithLanguageVersion(languageVersion)); } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.Scripting; namespace Microsoft.CodeAnalysis.CSharp.Scripting { public static class ScriptOptionsExtensions { public static ScriptOptions WithLanguageVersion(this ScriptOptions options, LanguageVersion languageVersion) { var parseOptions = (options.ParseOptions is null) ? CSharpScriptCompiler.DefaultParseOptions : (options.ParseOptions is CSharpParseOptions existing) ? existing : throw new InvalidOperationException(string.Format(ScriptingResources.CannotSetLanguageSpecificOption, LanguageNames.CSharp, nameof(LanguageVersion))); return options.WithParseOptions(parseOptions.WithLanguageVersion(languageVersion)); } } }
-1
dotnet/roslyn
56,095
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-02T00:01:28Z"
"2021-09-02T01:47:21Z"
212ca8da034e484813ea99027c29cc3f6405fe1f
fe389d485fb73f8186b32636bfc747a39a70b028
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Test/CommandLine/GeneratorDriverCacheTests.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 Xunit; namespace Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests { public class GeneratorDriverCacheTests : CommandLineTestBase { [Fact] public void DriverCache_Returns_Null_For_No_Match() { var driverCache = new GeneratorDriverCache(); var driver = driverCache.TryGetDriver("0"); Assert.Null(driver); } [Fact] public void DriverCache_Returns_Cached_Driver() { var drivers = GetDrivers(1); var driverCache = new GeneratorDriverCache(); driverCache.CacheGenerator("0", drivers[0]); var driver = driverCache.TryGetDriver("0"); Assert.Same(driver, drivers[0]); } [Fact] public void DriverCache_Can_Cache_Multiple_Drivers() { var drivers = GetDrivers(3); var driverCache = new GeneratorDriverCache(); driverCache.CacheGenerator("0", drivers[0]); driverCache.CacheGenerator("1", drivers[1]); driverCache.CacheGenerator("2", drivers[2]); var driver = driverCache.TryGetDriver("0"); Assert.Same(driver, drivers[0]); driver = driverCache.TryGetDriver("1"); Assert.Same(driver, drivers[1]); driver = driverCache.TryGetDriver("2"); Assert.Same(driver, drivers[2]); } [Fact] public void DriverCache_Evicts_Least_Recently_Used() { var drivers = GetDrivers(GeneratorDriverCache.MaxCacheSize + 2); var driverCache = new GeneratorDriverCache(); // put n+1 drivers into the cache for (int i = 0; i < GeneratorDriverCache.MaxCacheSize + 1; i++) { driverCache.CacheGenerator(i.ToString(), drivers[i]); } // current cache state is // (10, 9, 8, 7, 6, 5, 4, 3, 2, 1) // now try and retrieve the first driver which should no longer be in the cache var driver = driverCache.TryGetDriver("0"); Assert.Null(driver); // add it back driverCache.CacheGenerator("0", drivers[0]); // current cache state is // (0, 10, 9, 8, 7, 6, 5, 4, 3, 2) // access some drivers in the middle driver = driverCache.TryGetDriver("7"); driver = driverCache.TryGetDriver("4"); driver = driverCache.TryGetDriver("2"); // current cache state is // (2, 4, 7, 0, 10, 9, 8, 6, 5, 3) // try and get a new driver that was never in the cache driver = driverCache.TryGetDriver("11"); Assert.Null(driver); driverCache.CacheGenerator("11", drivers[11]); // current cache state is // (11, 2, 4, 7, 0, 10, 9, 8, 6, 5) // get a driver that has been evicted driver = driverCache.TryGetDriver("3"); Assert.Null(driver); } private static GeneratorDriver[] GetDrivers(int count) => Enumerable.Range(0, count).Select(i => CSharpGeneratorDriver.Create(Array.Empty<ISourceGenerator>())).ToArray(); } }
// Licensed to the .NET Foundation under one or more 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 Xunit; namespace Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests { public class GeneratorDriverCacheTests : CommandLineTestBase { [Fact] public void DriverCache_Returns_Null_For_No_Match() { var driverCache = new GeneratorDriverCache(); var driver = driverCache.TryGetDriver("0"); Assert.Null(driver); } [Fact] public void DriverCache_Returns_Cached_Driver() { var drivers = GetDrivers(1); var driverCache = new GeneratorDriverCache(); driverCache.CacheGenerator("0", drivers[0]); var driver = driverCache.TryGetDriver("0"); Assert.Same(driver, drivers[0]); } [Fact] public void DriverCache_Can_Cache_Multiple_Drivers() { var drivers = GetDrivers(3); var driverCache = new GeneratorDriverCache(); driverCache.CacheGenerator("0", drivers[0]); driverCache.CacheGenerator("1", drivers[1]); driverCache.CacheGenerator("2", drivers[2]); var driver = driverCache.TryGetDriver("0"); Assert.Same(driver, drivers[0]); driver = driverCache.TryGetDriver("1"); Assert.Same(driver, drivers[1]); driver = driverCache.TryGetDriver("2"); Assert.Same(driver, drivers[2]); } [Fact] public void DriverCache_Evicts_Least_Recently_Used() { var drivers = GetDrivers(GeneratorDriverCache.MaxCacheSize + 2); var driverCache = new GeneratorDriverCache(); // put n+1 drivers into the cache for (int i = 0; i < GeneratorDriverCache.MaxCacheSize + 1; i++) { driverCache.CacheGenerator(i.ToString(), drivers[i]); } // current cache state is // (10, 9, 8, 7, 6, 5, 4, 3, 2, 1) // now try and retrieve the first driver which should no longer be in the cache var driver = driverCache.TryGetDriver("0"); Assert.Null(driver); // add it back driverCache.CacheGenerator("0", drivers[0]); // current cache state is // (0, 10, 9, 8, 7, 6, 5, 4, 3, 2) // access some drivers in the middle driver = driverCache.TryGetDriver("7"); driver = driverCache.TryGetDriver("4"); driver = driverCache.TryGetDriver("2"); // current cache state is // (2, 4, 7, 0, 10, 9, 8, 6, 5, 3) // try and get a new driver that was never in the cache driver = driverCache.TryGetDriver("11"); Assert.Null(driver); driverCache.CacheGenerator("11", drivers[11]); // current cache state is // (11, 2, 4, 7, 0, 10, 9, 8, 6, 5) // get a driver that has been evicted driver = driverCache.TryGetDriver("3"); Assert.Null(driver); } private static GeneratorDriver[] GetDrivers(int count) => Enumerable.Range(0, count).Select(i => CSharpGeneratorDriver.Create(Array.Empty<ISourceGenerator>())).ToArray(); } }
-1
dotnet/roslyn
56,095
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-02T00:01:28Z"
"2021-09-02T01:47:21Z"
212ca8da034e484813ea99027c29cc3f6405fe1f
fe389d485fb73f8186b32636bfc747a39a70b028
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/VisualBasicTest/Recommendations/Declarations/GenericConstraintsKeywordRecommenderTests.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.Declarations Public Class GenericConstraintsKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterAsInSingleConstraintTest() VerifyRecommendationsContain(<File>Class Goo(Of T As |</File>, "Class", "Structure", "New") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterInMultipleConstraintTest() VerifyRecommendationsContain(<File>Class Goo(Of T As {|</File>, "Class", "Structure", "New") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterExplicitTypeTest() VerifyRecommendationsContain(<File>Class Goo(Of T As {OtherType, |</File>, "Class", "Structure", "New") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterStructureConstraintTest() VerifyRecommendationsMissing(<File>Class Goo(Of T As {Structure, |</File>, "Class", "Structure", "New") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassOnlyAfterNewTest() VerifyRecommendationsContain(<File>Class Goo(Of T As {New, |</File>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NewOnlyAfterClassTest() VerifyRecommendationsContain(<File>Class Goo(Of T As {Class, |</File>, "New") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterClassAndNewTest() VerifyRecommendationsMissing(<File>Class Goo(Of T As {Class, New,|</File>, "Class", "Structure", "New") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterEolTest() VerifyRecommendationsMissing( <File>Class Goo(Of T As |</File>, "New") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTest() VerifyRecommendationsContain( <File>Class Goo(Of T As _ |</File>, "New") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTestCommentsAfterLineContinuation() VerifyRecommendationsContain( <File>Class Goo(Of T As _ ' Test |</File>, "New") 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.Declarations Public Class GenericConstraintsKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterAsInSingleConstraintTest() VerifyRecommendationsContain(<File>Class Goo(Of T As |</File>, "Class", "Structure", "New") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterInMultipleConstraintTest() VerifyRecommendationsContain(<File>Class Goo(Of T As {|</File>, "Class", "Structure", "New") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AllAfterExplicitTypeTest() VerifyRecommendationsContain(<File>Class Goo(Of T As {OtherType, |</File>, "Class", "Structure", "New") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterStructureConstraintTest() VerifyRecommendationsMissing(<File>Class Goo(Of T As {Structure, |</File>, "Class", "Structure", "New") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassOnlyAfterNewTest() VerifyRecommendationsContain(<File>Class Goo(Of T As {New, |</File>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NewOnlyAfterClassTest() VerifyRecommendationsContain(<File>Class Goo(Of T As {Class, |</File>, "New") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterClassAndNewTest() VerifyRecommendationsMissing(<File>Class Goo(Of T As {Class, New,|</File>, "Class", "Structure", "New") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterEolTest() VerifyRecommendationsMissing( <File>Class Goo(Of T As |</File>, "New") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTest() VerifyRecommendationsContain( <File>Class Goo(Of T As _ |</File>, "New") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTestCommentsAfterLineContinuation() VerifyRecommendationsContain( <File>Class Goo(Of T As _ ' Test |</File>, "New") End Sub End Class End Namespace
-1
dotnet/roslyn
56,095
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-02T00:01:28Z"
"2021-09-02T01:47:21Z"
212ca8da034e484813ea99027c29cc3f6405fe1f
fe389d485fb73f8186b32636bfc747a39a70b028
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Portable/Binder/BinderFactory.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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class BinderFactory { // key in the binder cache. // PERF: we are not using ValueTuple because its Equals is relatively slow. private struct BinderCacheKey : IEquatable<BinderCacheKey> { public readonly CSharpSyntaxNode syntaxNode; public readonly NodeUsage usage; public BinderCacheKey(CSharpSyntaxNode syntaxNode, NodeUsage usage) { this.syntaxNode = syntaxNode; this.usage = usage; } bool IEquatable<BinderCacheKey>.Equals(BinderCacheKey other) { return syntaxNode == other.syntaxNode && this.usage == other.usage; } public override int GetHashCode() { return Hash.Combine(syntaxNode.GetHashCode(), (int)usage); } public override bool Equals(object obj) { throw new NotSupportedException(); } } // This dictionary stores contexts so we don't have to recreate them, which can be // expensive. private readonly ConcurrentCache<BinderCacheKey, Binder> _binderCache; private readonly CSharpCompilation _compilation; private readonly SyntaxTree _syntaxTree; private readonly BuckStopsHereBinder _buckStopsHereBinder; private readonly bool _ignoreAccessibility; // In a typing scenario, GetBinder is regularly called with a non-zero position. // This results in a lot of allocations of BinderFactoryVisitors. Pooling them // reduces this churn to almost nothing. private readonly ObjectPool<BinderFactoryVisitor> _binderFactoryVisitorPool; internal BinderFactory(CSharpCompilation compilation, SyntaxTree syntaxTree, bool ignoreAccessibility) { _compilation = compilation; _syntaxTree = syntaxTree; _ignoreAccessibility = ignoreAccessibility; _binderFactoryVisitorPool = new ObjectPool<BinderFactoryVisitor>(() => new BinderFactoryVisitor(this), 64); // 50 is more or less a guess, but it seems to work fine for scenarios that I tried. // we need something big enough to keep binders for most classes and some methods // in a typical syntax tree. // On the other side, note that the whole factory is weakly referenced and therefore short lived, // making this cache big is not very useful. // I noticed that while compiling Roslyn C# compiler most caches never see // more than 50 items added before getting collected. _binderCache = new ConcurrentCache<BinderCacheKey, Binder>(50); _buckStopsHereBinder = new BuckStopsHereBinder(compilation); } internal SyntaxTree SyntaxTree { get { return _syntaxTree; } } private bool InScript { get { return _syntaxTree.Options.Kind == SourceCodeKind.Script; } } /// <summary> /// Return binder for binding at node. /// <paramref name="memberDeclarationOpt"/> and <paramref name="memberOpt"/> /// are optional syntax and symbol for the member containing <paramref name="node"/>. /// If provided, the <see cref="BinderFactoryVisitor"/> will use the member symbol rather /// than looking up the member in the containing type, allowing this method to be called /// while calculating the member list. /// </summary> /// <remarks> /// Note, there is no guarantee that the factory always gives back the same binder instance for the same node. /// </remarks> internal Binder GetBinder(SyntaxNode node, CSharpSyntaxNode memberDeclarationOpt = null, Symbol memberOpt = null) { int position = node.SpanStart; // Unless this is interactive retrieving a binder for global statements // at the very top-level (i.e. in a completely empty file) use // node.Parent to maintain existing behavior. if ((!InScript || node.Kind() != SyntaxKind.CompilationUnit) && node.Parent != null) { node = node.Parent; } return GetBinder(node, position, memberDeclarationOpt, memberOpt); } internal Binder GetBinder(SyntaxNode node, int position, CSharpSyntaxNode memberDeclarationOpt = null, Symbol memberOpt = null) { Debug.Assert(node != null); #if DEBUG if (memberOpt is { ContainingSymbol: SourceMemberContainerTypeSymbol container }) { container.AssertMemberExposure(memberOpt); } #endif BinderFactoryVisitor visitor = _binderFactoryVisitorPool.Allocate(); visitor.Initialize(position, memberDeclarationOpt, memberOpt); Binder result = visitor.Visit(node); _binderFactoryVisitorPool.Free(visitor); return result; } internal InMethodBinder GetRecordConstructorInMethodBinder(SynthesizedRecordConstructor constructor) { var recordDecl = constructor.GetSyntax(); Debug.Assert(recordDecl.IsKind(SyntaxKind.RecordDeclaration)); var extraInfo = NodeUsage.ConstructorBodyOrInitializer; var key = BinderFactoryVisitor.CreateBinderCacheKey(recordDecl, extraInfo); if (!_binderCache.TryGetValue(key, out Binder resultBinder)) { // Ctors cannot be generic Debug.Assert(constructor.Arity == 0, "Generic Ctor, What to do?"); resultBinder = new InMethodBinder(constructor, GetInRecordBodyBinder(recordDecl)); _binderCache.TryAdd(key, resultBinder); } return (InMethodBinder)resultBinder; } internal Binder GetInRecordBodyBinder(RecordDeclarationSyntax typeDecl) { BinderFactoryVisitor visitor = _binderFactoryVisitorPool.Allocate(); visitor.Initialize(position: typeDecl.SpanStart, memberDeclarationOpt: null, memberOpt: null); Binder resultBinder = visitor.VisitTypeDeclarationCore(typeDecl, NodeUsage.NamedTypeBodyOrTypeParameters); _binderFactoryVisitorPool.Free(visitor); return resultBinder; } internal Binder GetInNamespaceBinder(CSharpSyntaxNode unit) { switch (unit.Kind()) { case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: { BinderFactoryVisitor visitor = _binderFactoryVisitorPool.Allocate(); visitor.Initialize(0, null, null); Binder result = visitor.VisitNamespaceDeclaration((BaseNamespaceDeclarationSyntax)unit, unit.SpanStart, inBody: true, inUsing: false); _binderFactoryVisitorPool.Free(visitor); return result; } case SyntaxKind.CompilationUnit: // imports are bound by the Script class binder: { BinderFactoryVisitor visitor = _binderFactoryVisitorPool.Allocate(); visitor.Initialize(0, null, null); Binder result = visitor.VisitCompilationUnit((CompilationUnitSyntax)unit, inUsing: false, inScript: InScript); _binderFactoryVisitorPool.Free(visitor); return result; } default: 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. #nullable disable using System; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class BinderFactory { // key in the binder cache. // PERF: we are not using ValueTuple because its Equals is relatively slow. private struct BinderCacheKey : IEquatable<BinderCacheKey> { public readonly CSharpSyntaxNode syntaxNode; public readonly NodeUsage usage; public BinderCacheKey(CSharpSyntaxNode syntaxNode, NodeUsage usage) { this.syntaxNode = syntaxNode; this.usage = usage; } bool IEquatable<BinderCacheKey>.Equals(BinderCacheKey other) { return syntaxNode == other.syntaxNode && this.usage == other.usage; } public override int GetHashCode() { return Hash.Combine(syntaxNode.GetHashCode(), (int)usage); } public override bool Equals(object obj) { throw new NotSupportedException(); } } // This dictionary stores contexts so we don't have to recreate them, which can be // expensive. private readonly ConcurrentCache<BinderCacheKey, Binder> _binderCache; private readonly CSharpCompilation _compilation; private readonly SyntaxTree _syntaxTree; private readonly BuckStopsHereBinder _buckStopsHereBinder; private readonly bool _ignoreAccessibility; // In a typing scenario, GetBinder is regularly called with a non-zero position. // This results in a lot of allocations of BinderFactoryVisitors. Pooling them // reduces this churn to almost nothing. private readonly ObjectPool<BinderFactoryVisitor> _binderFactoryVisitorPool; internal BinderFactory(CSharpCompilation compilation, SyntaxTree syntaxTree, bool ignoreAccessibility) { _compilation = compilation; _syntaxTree = syntaxTree; _ignoreAccessibility = ignoreAccessibility; _binderFactoryVisitorPool = new ObjectPool<BinderFactoryVisitor>(() => new BinderFactoryVisitor(this), 64); // 50 is more or less a guess, but it seems to work fine for scenarios that I tried. // we need something big enough to keep binders for most classes and some methods // in a typical syntax tree. // On the other side, note that the whole factory is weakly referenced and therefore short lived, // making this cache big is not very useful. // I noticed that while compiling Roslyn C# compiler most caches never see // more than 50 items added before getting collected. _binderCache = new ConcurrentCache<BinderCacheKey, Binder>(50); _buckStopsHereBinder = new BuckStopsHereBinder(compilation); } internal SyntaxTree SyntaxTree { get { return _syntaxTree; } } private bool InScript { get { return _syntaxTree.Options.Kind == SourceCodeKind.Script; } } /// <summary> /// Return binder for binding at node. /// <paramref name="memberDeclarationOpt"/> and <paramref name="memberOpt"/> /// are optional syntax and symbol for the member containing <paramref name="node"/>. /// If provided, the <see cref="BinderFactoryVisitor"/> will use the member symbol rather /// than looking up the member in the containing type, allowing this method to be called /// while calculating the member list. /// </summary> /// <remarks> /// Note, there is no guarantee that the factory always gives back the same binder instance for the same node. /// </remarks> internal Binder GetBinder(SyntaxNode node, CSharpSyntaxNode memberDeclarationOpt = null, Symbol memberOpt = null) { int position = node.SpanStart; // Unless this is interactive retrieving a binder for global statements // at the very top-level (i.e. in a completely empty file) use // node.Parent to maintain existing behavior. if ((!InScript || node.Kind() != SyntaxKind.CompilationUnit) && node.Parent != null) { node = node.Parent; } return GetBinder(node, position, memberDeclarationOpt, memberOpt); } internal Binder GetBinder(SyntaxNode node, int position, CSharpSyntaxNode memberDeclarationOpt = null, Symbol memberOpt = null) { Debug.Assert(node != null); #if DEBUG if (memberOpt is { ContainingSymbol: SourceMemberContainerTypeSymbol container }) { container.AssertMemberExposure(memberOpt); } #endif BinderFactoryVisitor visitor = _binderFactoryVisitorPool.Allocate(); visitor.Initialize(position, memberDeclarationOpt, memberOpt); Binder result = visitor.Visit(node); _binderFactoryVisitorPool.Free(visitor); return result; } internal InMethodBinder GetRecordConstructorInMethodBinder(SynthesizedRecordConstructor constructor) { var recordDecl = constructor.GetSyntax(); Debug.Assert(recordDecl.IsKind(SyntaxKind.RecordDeclaration)); var extraInfo = NodeUsage.ConstructorBodyOrInitializer; var key = BinderFactoryVisitor.CreateBinderCacheKey(recordDecl, extraInfo); if (!_binderCache.TryGetValue(key, out Binder resultBinder)) { // Ctors cannot be generic Debug.Assert(constructor.Arity == 0, "Generic Ctor, What to do?"); resultBinder = new InMethodBinder(constructor, GetInRecordBodyBinder(recordDecl)); _binderCache.TryAdd(key, resultBinder); } return (InMethodBinder)resultBinder; } internal Binder GetInRecordBodyBinder(RecordDeclarationSyntax typeDecl) { BinderFactoryVisitor visitor = _binderFactoryVisitorPool.Allocate(); visitor.Initialize(position: typeDecl.SpanStart, memberDeclarationOpt: null, memberOpt: null); Binder resultBinder = visitor.VisitTypeDeclarationCore(typeDecl, NodeUsage.NamedTypeBodyOrTypeParameters); _binderFactoryVisitorPool.Free(visitor); return resultBinder; } internal Binder GetInNamespaceBinder(CSharpSyntaxNode unit) { switch (unit.Kind()) { case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: { BinderFactoryVisitor visitor = _binderFactoryVisitorPool.Allocate(); visitor.Initialize(0, null, null); Binder result = visitor.VisitNamespaceDeclaration((BaseNamespaceDeclarationSyntax)unit, unit.SpanStart, inBody: true, inUsing: false); _binderFactoryVisitorPool.Free(visitor); return result; } case SyntaxKind.CompilationUnit: // imports are bound by the Script class binder: { BinderFactoryVisitor visitor = _binderFactoryVisitorPool.Allocate(); visitor.Initialize(0, null, null); Binder result = visitor.VisitCompilationUnit((CompilationUnitSyntax)unit, inUsing: false, inScript: InScript); _binderFactoryVisitorPool.Free(visitor); return result; } default: return null; } } } }
-1
dotnet/roslyn
56,095
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-02T00:01:28Z"
"2021-09-02T01:47:21Z"
212ca8da034e484813ea99027c29cc3f6405fe1f
fe389d485fb73f8186b32636bfc747a39a70b028
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/KeywordCompletionProviderTests.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.Providers Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.CompletionProviders Public Class KeywordCompletionProviderTests Inherits AbstractVisualBasicCompletionProviderTests Friend Overrides Function GetCompletionProviderType() As Type Return GetType(KeywordCompletionProvider) End Function <Fact(), Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function IsCommitCharacterTest() As Task Await VerifyCommonCommitCharactersAsync("$$", textTypedSoFar:="C") End Function <Fact(), Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub IsTextualTriggerCharacterTest() TestCommonIsTextualTriggerCharacter() VerifyTextualTriggerCharacter("goo$$(", shouldTriggerWithTriggerOnLettersEnabled:=True, shouldTriggerWithTriggerOnLettersDisabled:=True) End Sub <Fact(), Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function SendEnterThroughToEditorTest() As Task Await VerifySendEnterThroughToEditorAsync("$$", "Class", expected:=True) End Function <Fact(), Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function InEmptyFile() As Task Dim markup = "$$" Await VerifyAnyItemExistsAsync(markup) End Function <Fact(), Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function TestNotInInactiveCode() As Task Dim code = <Text> Class C Sub Main(args As String()) #If False Then $$ #End If End Sub End Class </Text>.Value Await VerifyNoItemsExistAsync(code) End Function <Fact(), Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function TestNotInString() As Task Dim code = <Text> Class C Sub Main(args As String()) dim c = "$$" End Sub End Class </Text>.Value Await VerifyNoItemsExistAsync(code) End Function <Fact(), Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function TestNotInUnterminatedString() As Task Dim code = <Text> Class C Sub Main(args As String()) dim c = "$$ End Sub End Class </Text>.Value Await VerifyNoItemsExistAsync(code) End Function <Fact(), Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function TestNotInSingleLineComment() As Task Dim code = <Text> Class C Sub Main(args As String()) dim c = '$$ End Sub End Class </Text>.Value Await VerifyNoItemsExistAsync(code) End Function <WorkItem(968256, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968256")> <Fact(), Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function TestUnionOfKeywordsFromBothFiles() As Task Dim markup = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="Proj1" PreprocessorSymbols="GOO=true"> <Document FilePath="CurrentDocument.vb"><![CDATA[ Class C Dim x As Integer #if GOO then sub goo() #End If $$ #If GOO Then end sub #End If End Class]]> </Document> </Project> <Project Language="Visual Basic" CommonReferences=" true" AssemblyName="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="Proj1" LinkFilePath="CurrentDocument.vb"/> </Project> </Workspace>.ToString().NormalizeLineEndings() Await VerifyItemInLinkedFilesAsync(markup, "Public", Nothing) Await VerifyItemInLinkedFilesAsync(markup, "For", Nothing) End Function <WorkItem(1736, "https://github.com/dotnet/roslyn/issues/1736")> <Fact(), Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function TestNotInInteger() As Task Dim code = <Text> Class C Sub Main(args As String()) dim c = 2$$00 End Sub End Class </Text>.Value Await VerifyNoItemsExistAsync(code) End Function <WorkItem(1736, "https://github.com/dotnet/roslyn/issues/1736")> <Fact(), Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function TestNotInDecimal() As Task Dim code = <Text> Class C Sub Main(args As String()) dim c = 2$$.00D End Sub End Class </Text>.Value Await VerifyNoItemsExistAsync(code) End Function <WorkItem(1736, "https://github.com/dotnet/roslyn/issues/1736")> <Fact(), Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function TestNotInFloat() As Task Dim code = <Text> Class C Sub Main(args As String()) dim c = 2$$.00 End Sub End Class </Text>.Value Await VerifyNoItemsExistAsync(code) End Function <WorkItem(1736, "https://github.com/dotnet/roslyn/issues/1736")> <Fact(), Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function TestNotInDate() As Task Dim code = <Text> Class C Sub Main(args As String()) dim c = #4/2$$/2015 End Sub End Class </Text>.Value Await VerifyNoItemsExistAsync(code) End Function <WorkItem(4167, "https://github.com/dotnet/roslyn/issues/4167")> <Fact(), Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function ImplementsAfterSub() As Task Dim code = " Interface I End Interface Class C Implements I Sub M() $$ End Sub End Class " Await VerifyItemExistsAsync(code, "Implements") 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 Microsoft.CodeAnalysis.VisualBasic.Completion.Providers Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.CompletionProviders Public Class KeywordCompletionProviderTests Inherits AbstractVisualBasicCompletionProviderTests Friend Overrides Function GetCompletionProviderType() As Type Return GetType(KeywordCompletionProvider) End Function <Fact(), Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function IsCommitCharacterTest() As Task Await VerifyCommonCommitCharactersAsync("$$", textTypedSoFar:="C") End Function <Fact(), Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub IsTextualTriggerCharacterTest() TestCommonIsTextualTriggerCharacter() VerifyTextualTriggerCharacter("goo$$(", shouldTriggerWithTriggerOnLettersEnabled:=True, shouldTriggerWithTriggerOnLettersDisabled:=True) End Sub <Fact(), Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function SendEnterThroughToEditorTest() As Task Await VerifySendEnterThroughToEditorAsync("$$", "Class", expected:=True) End Function <Fact(), Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function InEmptyFile() As Task Dim markup = "$$" Await VerifyAnyItemExistsAsync(markup) End Function <Fact(), Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function TestNotInInactiveCode() As Task Dim code = <Text> Class C Sub Main(args As String()) #If False Then $$ #End If End Sub End Class </Text>.Value Await VerifyNoItemsExistAsync(code) End Function <Fact(), Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function TestNotInString() As Task Dim code = <Text> Class C Sub Main(args As String()) dim c = "$$" End Sub End Class </Text>.Value Await VerifyNoItemsExistAsync(code) End Function <Fact(), Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function TestNotInUnterminatedString() As Task Dim code = <Text> Class C Sub Main(args As String()) dim c = "$$ End Sub End Class </Text>.Value Await VerifyNoItemsExistAsync(code) End Function <Fact(), Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function TestNotInSingleLineComment() As Task Dim code = <Text> Class C Sub Main(args As String()) dim c = '$$ End Sub End Class </Text>.Value Await VerifyNoItemsExistAsync(code) End Function <WorkItem(968256, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968256")> <Fact(), Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function TestUnionOfKeywordsFromBothFiles() As Task Dim markup = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="Proj1" PreprocessorSymbols="GOO=true"> <Document FilePath="CurrentDocument.vb"><![CDATA[ Class C Dim x As Integer #if GOO then sub goo() #End If $$ #If GOO Then end sub #End If End Class]]> </Document> </Project> <Project Language="Visual Basic" CommonReferences=" true" AssemblyName="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="Proj1" LinkFilePath="CurrentDocument.vb"/> </Project> </Workspace>.ToString().NormalizeLineEndings() Await VerifyItemInLinkedFilesAsync(markup, "Public", Nothing) Await VerifyItemInLinkedFilesAsync(markup, "For", Nothing) End Function <WorkItem(1736, "https://github.com/dotnet/roslyn/issues/1736")> <Fact(), Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function TestNotInInteger() As Task Dim code = <Text> Class C Sub Main(args As String()) dim c = 2$$00 End Sub End Class </Text>.Value Await VerifyNoItemsExistAsync(code) End Function <WorkItem(1736, "https://github.com/dotnet/roslyn/issues/1736")> <Fact(), Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function TestNotInDecimal() As Task Dim code = <Text> Class C Sub Main(args As String()) dim c = 2$$.00D End Sub End Class </Text>.Value Await VerifyNoItemsExistAsync(code) End Function <WorkItem(1736, "https://github.com/dotnet/roslyn/issues/1736")> <Fact(), Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function TestNotInFloat() As Task Dim code = <Text> Class C Sub Main(args As String()) dim c = 2$$.00 End Sub End Class </Text>.Value Await VerifyNoItemsExistAsync(code) End Function <WorkItem(1736, "https://github.com/dotnet/roslyn/issues/1736")> <Fact(), Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function TestNotInDate() As Task Dim code = <Text> Class C Sub Main(args As String()) dim c = #4/2$$/2015 End Sub End Class </Text>.Value Await VerifyNoItemsExistAsync(code) End Function <WorkItem(4167, "https://github.com/dotnet/roslyn/issues/4167")> <Fact(), Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function ImplementsAfterSub() As Task Dim code = " Interface I End Interface Class C Implements I Sub M() $$ End Sub End Class " Await VerifyItemExistsAsync(code, "Implements") End Function End Class End Namespace
-1
dotnet/roslyn
56,095
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-02T00:01:28Z"
"2021-09-02T01:47:21Z"
212ca8da034e484813ea99027c29cc3f6405fe1f
fe389d485fb73f8186b32636bfc747a39a70b028
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/CorLibrary/Choosing.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.Runtime.CompilerServices Imports CompilationCreationTestHelpers Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata Imports Roslyn.Test.Utilities Imports VBReferenceManager = Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilation.ReferenceManager Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.CorLibrary Public Class Choosing Inherits BasicTestBase <Fact()> Public Sub MultipleMscorlibReferencesInMetadata() Dim assemblies = MetadataTestHelpers.GetSymbolsForReferences( { TestResources.SymbolsTests.CorLibrary.GuidTest2, TestMetadata.ResourcesNet40.mscorlib }) Assert.Same(assemblies(1), DirectCast(assemblies(0).Modules(0), PEModuleSymbol).CorLibrary) End Sub <Fact, WorkItem(760148, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/760148")> Public Sub Bug760148_1() Dim corLib = CompilationUtils.CreateEmptyCompilation( <compilation> <file name="a.vb"> Namespace System Public class Object End Class End Namespace </file> </compilation>, options:=TestOptions.ReleaseDll) Dim obj = corLib.GetSpecialType(SpecialType.System_Object) Assert.False(obj.IsErrorType()) Assert.Same(corLib.Assembly, obj.ContainingAssembly) Dim consumer = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"> Namespace System Public class Object End Class End Namespace </file> </compilation>, {New VisualBasicCompilationReference(corLib)}, TestOptions.ReleaseDll) Assert.Same(obj, consumer.GetSpecialType(SpecialType.System_Object)) End Sub <Fact, WorkItem(760148, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/760148")> Public Sub Bug760148_2() Dim corLib = CompilationUtils.CreateEmptyCompilation( <compilation> <file name="a.vb"> Namespace System Class Object End Class End Namespace </file> </compilation>, options:=TestOptions.ReleaseDll) Dim obj = corLib.GetSpecialType(SpecialType.System_Object) Dim consumer = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"> Namespace System Public class Object End Class End Namespace </file> </compilation>, {New VisualBasicCompilationReference(corLib)}, TestOptions.ReleaseDll) Assert.True(consumer.GetSpecialType(SpecialType.System_Object).IsErrorType()) 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.Runtime.CompilerServices Imports CompilationCreationTestHelpers Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata Imports Roslyn.Test.Utilities Imports VBReferenceManager = Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilation.ReferenceManager Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.CorLibrary Public Class Choosing Inherits BasicTestBase <Fact()> Public Sub MultipleMscorlibReferencesInMetadata() Dim assemblies = MetadataTestHelpers.GetSymbolsForReferences( { TestResources.SymbolsTests.CorLibrary.GuidTest2, TestMetadata.ResourcesNet40.mscorlib }) Assert.Same(assemblies(1), DirectCast(assemblies(0).Modules(0), PEModuleSymbol).CorLibrary) End Sub <Fact, WorkItem(760148, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/760148")> Public Sub Bug760148_1() Dim corLib = CompilationUtils.CreateEmptyCompilation( <compilation> <file name="a.vb"> Namespace System Public class Object End Class End Namespace </file> </compilation>, options:=TestOptions.ReleaseDll) Dim obj = corLib.GetSpecialType(SpecialType.System_Object) Assert.False(obj.IsErrorType()) Assert.Same(corLib.Assembly, obj.ContainingAssembly) Dim consumer = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"> Namespace System Public class Object End Class End Namespace </file> </compilation>, {New VisualBasicCompilationReference(corLib)}, TestOptions.ReleaseDll) Assert.Same(obj, consumer.GetSpecialType(SpecialType.System_Object)) End Sub <Fact, WorkItem(760148, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/760148")> Public Sub Bug760148_2() Dim corLib = CompilationUtils.CreateEmptyCompilation( <compilation> <file name="a.vb"> Namespace System Class Object End Class End Namespace </file> </compilation>, options:=TestOptions.ReleaseDll) Dim obj = corLib.GetSpecialType(SpecialType.System_Object) Dim consumer = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"> Namespace System Public class Object End Class End Namespace </file> </compilation>, {New VisualBasicCompilationReference(corLib)}, TestOptions.ReleaseDll) Assert.True(consumer.GetSpecialType(SpecialType.System_Object).IsErrorType()) End Sub End Class End Namespace
-1
dotnet/roslyn
56,095
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-02T00:01:28Z"
"2021-09-02T01:47:21Z"
212ca8da034e484813ea99027c29cc3f6405fe1f
fe389d485fb73f8186b32636bfc747a39a70b028
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/Core/Portable/Shared/Extensions/ArrayExtensions.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.CodeAnalysis; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class ArrayExtensions { public static bool IsNullOrEmpty<T>([NotNullWhen(returnValue: false)] this T[]? array) => array == null || array.Length == 0; public static bool Contains<T>(this T[] array, T item) => Array.IndexOf(array, item) >= 0; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class ArrayExtensions { public static bool IsNullOrEmpty<T>([NotNullWhen(returnValue: false)] this T[]? array) => array == null || array.Length == 0; public static bool Contains<T>(this T[] array, T item) => Array.IndexOf(array, item) >= 0; } }
-1
dotnet/roslyn
56,095
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-02T00:01:28Z"
"2021-09-02T01:47:21Z"
212ca8da034e484813ea99027c29cc3f6405fe1f
fe389d485fb73f8186b32636bfc747a39a70b028
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/VisualBasic/SplitComment/VisualBasicSplitCommentService.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.Composition Imports Microsoft.CodeAnalysis.Editor.Implementation.SplitComment Imports Microsoft.CodeAnalysis.Host.Mef Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.SplitComment <ExportLanguageService(GetType(ISplitCommentService), LanguageNames.VisualBasic), [Shared]> Partial Friend Class VisualBasicSplitCommentService Implements ISplitCommentService <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public ReadOnly Property CommentStart As String Implements ISplitCommentService.CommentStart Get Return "'" End Get End Property Public Function IsAllowed(root As SyntaxNode, trivia As SyntaxTrivia) As Boolean Implements ISplitCommentService.IsAllowed ' We don't currently allow splitting the comment if there is a preceding line continuation character. This is ' primarily because this is not a common enough scenario to warrant the extra complexity in this fixer. Dim currentTrivia = trivia While currentTrivia <> Nothing AndAlso currentTrivia.SpanStart > 0 Dim previousTrivia = root.FindTrivia(currentTrivia.SpanStart - 1) If previousTrivia.IsKind(SyntaxKind.LineContinuationTrivia) Then Return False End If If previousTrivia.IsKind(SyntaxKind.WhitespaceTrivia) Then currentTrivia = previousTrivia Continue While End If Return True End While Return True 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.Composition Imports Microsoft.CodeAnalysis.Editor.Implementation.SplitComment Imports Microsoft.CodeAnalysis.Host.Mef Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.SplitComment <ExportLanguageService(GetType(ISplitCommentService), LanguageNames.VisualBasic), [Shared]> Partial Friend Class VisualBasicSplitCommentService Implements ISplitCommentService <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public ReadOnly Property CommentStart As String Implements ISplitCommentService.CommentStart Get Return "'" End Get End Property Public Function IsAllowed(root As SyntaxNode, trivia As SyntaxTrivia) As Boolean Implements ISplitCommentService.IsAllowed ' We don't currently allow splitting the comment if there is a preceding line continuation character. This is ' primarily because this is not a common enough scenario to warrant the extra complexity in this fixer. Dim currentTrivia = trivia While currentTrivia <> Nothing AndAlso currentTrivia.SpanStart > 0 Dim previousTrivia = root.FindTrivia(currentTrivia.SpanStart - 1) If previousTrivia.IsKind(SyntaxKind.LineContinuationTrivia) Then Return False End If If previousTrivia.IsKind(SyntaxKind.WhitespaceTrivia) Then currentTrivia = previousTrivia Continue While End If Return True End While Return True End Function End Class End Namespace
-1
dotnet/roslyn
56,095
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-02T00:01:28Z"
"2021-09-02T01:47:21Z"
212ca8da034e484813ea99027c29cc3f6405fe1f
fe389d485fb73f8186b32636bfc747a39a70b028
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/CSharpTest2/Recommendations/SetKeywordRecommenderTests.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.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class SetKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int Goo { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPropertyPrivate() { await VerifyKeywordAsync( @"class C { int Goo { private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPropertyAttribute() { await VerifyKeywordAsync( @"class C { int Goo { [Bar] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPropertyAttributeAndPrivate() { await VerifyKeywordAsync( @"class C { int Goo { [Bar] private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPropertyGet() { await VerifyKeywordAsync( @"class C { int Goo { get; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPropertyGetAndPrivate() { await VerifyKeywordAsync( @"class C { int Goo { get; private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPropertyGetAndAttribute() { await VerifyKeywordAsync( @"class C { int Goo { get; [Bar] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPropertyGetAndAttributeAndPrivate() { await VerifyKeywordAsync( @"class C { int Goo { get; [Bar] private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGetAccessorBlock() { await VerifyKeywordAsync( @"class C { int Goo { get { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGetAccessorBlockAndPrivate() { await VerifyKeywordAsync( @"class C { int Goo { get { } private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGetAccessorBlockAndAttribute() { await VerifyKeywordAsync( @"class C { int Goo { get { } [Bar] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGetAccessorBlockAndAttributeAndPrivate() { await VerifyKeywordAsync( @"class C { int Goo { get { } [Bar] private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPropertySetKeyword() { await VerifyAbsenceAsync( @"class C { int Goo { set $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPropertySetAccessor() { await VerifyAbsenceAsync( @"class C { int Goo { set; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEvent() { await VerifyAbsenceAsync( @"class C { event Goo E { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexer() { await VerifyKeywordAsync( @"class C { int this[int i] { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerPrivate() { await VerifyKeywordAsync( @"class C { int this[int i] { private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerAttribute() { await VerifyKeywordAsync( @"class C { int this[int i] { [Bar] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerAttributeAndPrivate() { await VerifyKeywordAsync( @"class C { int this[int i] { [Bar] private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerGet() { await VerifyKeywordAsync( @"class C { int this[int i] { get; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerGetAndPrivate() { await VerifyKeywordAsync( @"class C { int this[int i] { get; private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerGetAndAttribute() { await VerifyKeywordAsync( @"class C { int this[int i] { get; [Bar] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerGetAndAttributeAndPrivate() { await VerifyKeywordAsync( @"class C { int this[int i] { get; [Bar] private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerGetBlock() { await VerifyKeywordAsync( @"class C { int this[int i] { get { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerGetBlockAndPrivate() { await VerifyKeywordAsync( @"class C { int this[int i] { get { } private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerGetBlockAndAttribute() { await VerifyKeywordAsync( @"class C { int this[int i] { get { } [Bar] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerGetBlockAndAttributeAndPrivate() { await VerifyKeywordAsync( @"class C { int this[int i] { get { } [Bar] private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterIndexerSetKeyword() { await VerifyAbsenceAsync( @"class C { int this[int i] { set $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterIndexerSetAccessor() { await VerifyAbsenceAsync( @"class C { int this[int i] { set; $$"); } } }
// Licensed to the .NET Foundation under one or more 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.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class SetKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int Goo { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPropertyPrivate() { await VerifyKeywordAsync( @"class C { int Goo { private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPropertyAttribute() { await VerifyKeywordAsync( @"class C { int Goo { [Bar] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPropertyAttributeAndPrivate() { await VerifyKeywordAsync( @"class C { int Goo { [Bar] private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPropertyGet() { await VerifyKeywordAsync( @"class C { int Goo { get; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPropertyGetAndPrivate() { await VerifyKeywordAsync( @"class C { int Goo { get; private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPropertyGetAndAttribute() { await VerifyKeywordAsync( @"class C { int Goo { get; [Bar] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPropertyGetAndAttributeAndPrivate() { await VerifyKeywordAsync( @"class C { int Goo { get; [Bar] private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGetAccessorBlock() { await VerifyKeywordAsync( @"class C { int Goo { get { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGetAccessorBlockAndPrivate() { await VerifyKeywordAsync( @"class C { int Goo { get { } private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGetAccessorBlockAndAttribute() { await VerifyKeywordAsync( @"class C { int Goo { get { } [Bar] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGetAccessorBlockAndAttributeAndPrivate() { await VerifyKeywordAsync( @"class C { int Goo { get { } [Bar] private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPropertySetKeyword() { await VerifyAbsenceAsync( @"class C { int Goo { set $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPropertySetAccessor() { await VerifyAbsenceAsync( @"class C { int Goo { set; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEvent() { await VerifyAbsenceAsync( @"class C { event Goo E { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexer() { await VerifyKeywordAsync( @"class C { int this[int i] { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerPrivate() { await VerifyKeywordAsync( @"class C { int this[int i] { private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerAttribute() { await VerifyKeywordAsync( @"class C { int this[int i] { [Bar] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerAttributeAndPrivate() { await VerifyKeywordAsync( @"class C { int this[int i] { [Bar] private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerGet() { await VerifyKeywordAsync( @"class C { int this[int i] { get; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerGetAndPrivate() { await VerifyKeywordAsync( @"class C { int this[int i] { get; private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerGetAndAttribute() { await VerifyKeywordAsync( @"class C { int this[int i] { get; [Bar] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerGetAndAttributeAndPrivate() { await VerifyKeywordAsync( @"class C { int this[int i] { get; [Bar] private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerGetBlock() { await VerifyKeywordAsync( @"class C { int this[int i] { get { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerGetBlockAndPrivate() { await VerifyKeywordAsync( @"class C { int this[int i] { get { } private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerGetBlockAndAttribute() { await VerifyKeywordAsync( @"class C { int this[int i] { get { } [Bar] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerGetBlockAndAttributeAndPrivate() { await VerifyKeywordAsync( @"class C { int this[int i] { get { } [Bar] private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterIndexerSetKeyword() { await VerifyAbsenceAsync( @"class C { int this[int i] { set $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterIndexerSetAccessor() { await VerifyAbsenceAsync( @"class C { int this[int i] { set; $$"); } } }
-1
dotnet/roslyn
56,095
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-02T00:01:28Z"
"2021-09-02T01:47:21Z"
212ca8da034e484813ea99027c29cc3f6405fe1f
fe389d485fb73f8186b32636bfc747a39a70b028
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/VisualBasicTest/Recommendations/Statements/EachKeywordRecommenderTests.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.Statements Public Class EachKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EachNotInMethodBodyTest() VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "Each") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EachAfterForKeywordTest() VerifyRecommendationsContain(<MethodBody>For |</MethodBody>, "Each") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EachNotAfterTouchingForTest() VerifyRecommendationsMissing(<MethodBody>For|</MethodBody>, "Each") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EachTouchingLoopIdentifierTest() VerifyRecommendationsContain(<MethodBody>For i|</MethodBody>, "Each") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterEolTest() VerifyRecommendationsMissing( <MethodBody>For |</MethodBody>, "Each") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTest() VerifyRecommendationsContain( <MethodBody>For _ |</MethodBody>, "Each") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTestCommentsAfterLineContinuation() VerifyRecommendationsContain( <MethodBody>For _ ' Test |</MethodBody>, "Each") End Sub <WorkItem(4946, "http://github.com/dotnet/roslyn/issues/4946")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInForLoop() VerifyNoRecommendations( <MethodBody>For | = 1 To 100 Next</MethodBody>) 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.Statements Public Class EachKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EachNotInMethodBodyTest() VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "Each") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EachAfterForKeywordTest() VerifyRecommendationsContain(<MethodBody>For |</MethodBody>, "Each") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EachNotAfterTouchingForTest() VerifyRecommendationsMissing(<MethodBody>For|</MethodBody>, "Each") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EachTouchingLoopIdentifierTest() VerifyRecommendationsContain(<MethodBody>For i|</MethodBody>, "Each") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterEolTest() VerifyRecommendationsMissing( <MethodBody>For |</MethodBody>, "Each") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTest() VerifyRecommendationsContain( <MethodBody>For _ |</MethodBody>, "Each") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTestCommentsAfterLineContinuation() VerifyRecommendationsContain( <MethodBody>For _ ' Test |</MethodBody>, "Each") End Sub <WorkItem(4946, "http://github.com/dotnet/roslyn/issues/4946")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInForLoop() VerifyNoRecommendations( <MethodBody>For | = 1 To 100 Next</MethodBody>) End Sub End Class End Namespace
-1
dotnet/roslyn
56,095
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-02T00:01:28Z"
"2021-09-02T01:47:21Z"
212ca8da034e484813ea99027c29cc3f6405fe1f
fe389d485fb73f8186b32636bfc747a39a70b028
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/CSharpTest/Diagnostics/Configuration/ConfigureSeverity/DotNetDiagnosticSeverityBasedSeverityConfigurationTests.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.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeFixes.Configuration.ConfigureSeverity; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.Configuration.ConfigureSeverity { public abstract partial class DotNetDiagnosticSeverityBasedSeverityConfigurationTests : AbstractSuppressionDiagnosticTest { private sealed class CustomDiagnosticAnalyzer : DiagnosticAnalyzer { private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( id: "XYZ0001", title: "Title", messageFormat: "Message", category: "Category", defaultSeverity: DiagnosticSeverity.Info, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction( c => c.ReportDiagnostic(Diagnostic.Create(Rule, c.Node.GetLocation())), SyntaxKind.ClassDeclaration); } } protected internal override string GetLanguage() => LanguageNames.CSharp; protected override ParseOptions GetScriptOptions() => Options.Script; internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new CustomDiagnosticAnalyzer(), new ConfigureSeverityLevelCodeFixProvider()); } public class NoneConfigurationTests : DotNetDiagnosticSeverityBasedSeverityConfigurationTests { protected override int CodeActionIndex => 0; [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_Empty_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig""></AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # XYZ0001: Title dotnet_diagnostic.XYZ0001.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_diagnostic.XYZ0001.severity = suggestion # Comment </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_diagnostic.XYZ0001.severity = none # Comment </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_InvalidHeader_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb] dotnet_diagnostic.XYZ0001.severity = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb] dotnet_diagnostic.XYZ0001.severity = suggestion [*.cs] # XYZ0001: Title dotnet_diagnostic.XYZ0001.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_MaintainExistingEntry_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_diagnostic.XYZ0001.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestMissingInRegularAndScriptAsync(input); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_InvalidRule_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_diagnostic.XYZ1111.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_diagnostic.XYZ1111.severity = none # XYZ0001: Title dotnet_diagnostic.XYZ0001.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] [WorkItem(45446, "https://github.com/dotnet/roslyn/issues/45446")] public async Task ConfigureEditorconfig_MissingRule_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_diagnostic.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_diagnostic.severity = none # XYZ0001: Title dotnet_diagnostic.XYZ0001.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RegexHeaderMatch_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program/file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*am/fi*e.cs] # XYZ0001: Title dotnet_diagnostic.XYZ0001.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program/file.cs""> class Program1 { } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*am/fi*e.cs] # XYZ0001: Title dotnet_diagnostic.XYZ0001.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RegexHeaderNonMatch_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program/file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*am/fii*e.cs] # XYZ0001: Title dotnet_diagnostic.XYZ0001.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program/file.cs""> class Program1 { } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*am/fii*e.cs] # XYZ0001: Title dotnet_diagnostic.XYZ0001.severity = warning [*.cs] # XYZ0001: Title dotnet_diagnostic.XYZ0001.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } } } }
// Licensed to the .NET Foundation under one or more 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.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeFixes.Configuration.ConfigureSeverity; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.Configuration.ConfigureSeverity { public abstract partial class DotNetDiagnosticSeverityBasedSeverityConfigurationTests : AbstractSuppressionDiagnosticTest { private sealed class CustomDiagnosticAnalyzer : DiagnosticAnalyzer { private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( id: "XYZ0001", title: "Title", messageFormat: "Message", category: "Category", defaultSeverity: DiagnosticSeverity.Info, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction( c => c.ReportDiagnostic(Diagnostic.Create(Rule, c.Node.GetLocation())), SyntaxKind.ClassDeclaration); } } protected internal override string GetLanguage() => LanguageNames.CSharp; protected override ParseOptions GetScriptOptions() => Options.Script; internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new CustomDiagnosticAnalyzer(), new ConfigureSeverityLevelCodeFixProvider()); } public class NoneConfigurationTests : DotNetDiagnosticSeverityBasedSeverityConfigurationTests { protected override int CodeActionIndex => 0; [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_Empty_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig""></AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # XYZ0001: Title dotnet_diagnostic.XYZ0001.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_diagnostic.XYZ0001.severity = suggestion # Comment </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_diagnostic.XYZ0001.severity = none # Comment </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_InvalidHeader_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb] dotnet_diagnostic.XYZ0001.severity = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb] dotnet_diagnostic.XYZ0001.severity = suggestion [*.cs] # XYZ0001: Title dotnet_diagnostic.XYZ0001.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_MaintainExistingEntry_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_diagnostic.XYZ0001.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestMissingInRegularAndScriptAsync(input); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_InvalidRule_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_diagnostic.XYZ1111.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_diagnostic.XYZ1111.severity = none # XYZ0001: Title dotnet_diagnostic.XYZ0001.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] [WorkItem(45446, "https://github.com/dotnet/roslyn/issues/45446")] public async Task ConfigureEditorconfig_MissingRule_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_diagnostic.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_diagnostic.severity = none # XYZ0001: Title dotnet_diagnostic.XYZ0001.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RegexHeaderMatch_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program/file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*am/fi*e.cs] # XYZ0001: Title dotnet_diagnostic.XYZ0001.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program/file.cs""> class Program1 { } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*am/fi*e.cs] # XYZ0001: Title dotnet_diagnostic.XYZ0001.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RegexHeaderNonMatch_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program/file.cs""> [|class Program1 { }|] </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*am/fii*e.cs] # XYZ0001: Title dotnet_diagnostic.XYZ0001.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program/file.cs""> class Program1 { } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*am/fii*e.cs] # XYZ0001: Title dotnet_diagnostic.XYZ0001.severity = warning [*.cs] # XYZ0001: Title dotnet_diagnostic.XYZ0001.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } } } }
-1
dotnet/roslyn
56,095
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-02T00:01:28Z"
"2021-09-02T01:47:21Z"
212ca8da034e484813ea99027c29cc3f6405fe1f
fe389d485fb73f8186b32636bfc747a39a70b028
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/VisualBasic/Portable/CodeGen/OperatorKind.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.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic <Flags()> Friend Enum UnaryOperatorKind Plus = 1 Minus = 2 [Not] = 3 IntrinsicOpMask = &H3 Lifted = &H4 UserDefined = &H8 Implicit = &H10 Explicit = &H20 IsTrue = &H30 IsFalse = &H40 OpMask = IntrinsicOpMask Or &H70 [Error] = &H80 End Enum <Flags()> Friend Enum BinaryOperatorKind Add = 1 Concatenate = 2 [Like] = 3 Equals = 4 NotEquals = 5 LessThanOrEqual = 6 GreaterThanOrEqual = 7 LessThan = 8 GreaterThan = 9 Subtract = 10 Multiply = 11 Power = 12 Divide = 13 Modulo = 14 IntegerDivide = 15 LeftShift = 16 RightShift = 17 [Xor] = 18 [Or] = 19 [OrElse] = 20 [And] = 21 [AndAlso] = 22 [Is] = 23 [IsNot] = 24 OpMask = &H1F Lifted = &H20 CompareText = &H40 UserDefined = &H80 [Error] = &H100 ''' <summary> ''' Built-in binary operators bound in "OperandOfConditionalBranch" mode are marked with ''' this flag by the Binder, which makes them eligible for some optimizations in ''' <see cref="LocalRewriter.VisitNullableIsTrueOperator(BoundNullableIsTrueOperator)"/> ''' </summary> IsOperandOfConditionalBranch = &H200 ''' <summary> ''' <see cref="LocalRewriter.AdjustIfOptimizableForConditionalBranch"/> marks built-in binary operators ''' with this flag in order to inform <see cref="LocalRewriter.VisitBinaryOperator"/> that the operator ''' should be a subject for optimization around use of three-valued Boolean logic. ''' The optimization should be applied only when we are absolutely sure that we will "snap" Null to false. ''' That is when we actually have the <see cref="BoundNullableIsTrueOperator"/> as the ancestor and no user defined operators ''' in between. We simply don't know that information during binding because we haven't bound binary operators ''' up the hierarchy yet. So the optimization is triggered by the fact of snapping Null to false ''' (getting to the <see cref="LocalRewriter.VisitNullableIsTrueOperator"/> method) and then we are making ''' sure we don't have anything unexpected in between. ''' </summary> OptimizableForConditionalBranch = &H400 End Enum 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.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic <Flags()> Friend Enum UnaryOperatorKind Plus = 1 Minus = 2 [Not] = 3 IntrinsicOpMask = &H3 Lifted = &H4 UserDefined = &H8 Implicit = &H10 Explicit = &H20 IsTrue = &H30 IsFalse = &H40 OpMask = IntrinsicOpMask Or &H70 [Error] = &H80 End Enum <Flags()> Friend Enum BinaryOperatorKind Add = 1 Concatenate = 2 [Like] = 3 Equals = 4 NotEquals = 5 LessThanOrEqual = 6 GreaterThanOrEqual = 7 LessThan = 8 GreaterThan = 9 Subtract = 10 Multiply = 11 Power = 12 Divide = 13 Modulo = 14 IntegerDivide = 15 LeftShift = 16 RightShift = 17 [Xor] = 18 [Or] = 19 [OrElse] = 20 [And] = 21 [AndAlso] = 22 [Is] = 23 [IsNot] = 24 OpMask = &H1F Lifted = &H20 CompareText = &H40 UserDefined = &H80 [Error] = &H100 ''' <summary> ''' Built-in binary operators bound in "OperandOfConditionalBranch" mode are marked with ''' this flag by the Binder, which makes them eligible for some optimizations in ''' <see cref="LocalRewriter.VisitNullableIsTrueOperator(BoundNullableIsTrueOperator)"/> ''' </summary> IsOperandOfConditionalBranch = &H200 ''' <summary> ''' <see cref="LocalRewriter.AdjustIfOptimizableForConditionalBranch"/> marks built-in binary operators ''' with this flag in order to inform <see cref="LocalRewriter.VisitBinaryOperator"/> that the operator ''' should be a subject for optimization around use of three-valued Boolean logic. ''' The optimization should be applied only when we are absolutely sure that we will "snap" Null to false. ''' That is when we actually have the <see cref="BoundNullableIsTrueOperator"/> as the ancestor and no user defined operators ''' in between. We simply don't know that information during binding because we haven't bound binary operators ''' up the hierarchy yet. So the optimization is triggered by the fact of snapping Null to false ''' (getting to the <see cref="LocalRewriter.VisitNullableIsTrueOperator"/> method) and then we are making ''' sure we don't have anything unexpected in between. ''' </summary> OptimizableForConditionalBranch = &H400 End Enum End Namespace
-1
dotnet/roslyn
56,095
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
"2021-09-02T00:01:28Z"
"2021-09-02T01:47:21Z"
212ca8da034e484813ea99027c29cc3f6405fe1f
fe389d485fb73f8186b32636bfc747a39a70b028
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/CSharp/Portable/CodeFixes/Nullable/CSharpDeclareAsNullableCodeFixProvider.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.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.DeclareAsNullable { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.DeclareAsNullable), Shared] internal class CSharpDeclareAsNullableCodeFixProvider : SyntaxEditorBasedCodeFixProvider { // We want to distinguish different situations: // 1. local null assignments: `return null;`, `local = null;`, `parameter = null;` (high confidence that the null is introduced deliberately and the API should be updated) // 2. invocation with null: `M(null);`, or assigning null to field or property (test code might do this even though the API should remain not-nullable, so FixAll should be invoked with care) // 3. conditional: `return x?.ToString();` private const string AssigningNullLiteralLocallyEquivalenceKey = nameof(AssigningNullLiteralLocallyEquivalenceKey); private const string AssigningNullLiteralRemotelyEquivalenceKey = nameof(AssigningNullLiteralRemotelyEquivalenceKey); private const string ConditionalOperatorEquivalenceKey = nameof(ConditionalOperatorEquivalenceKey); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpDeclareAsNullableCodeFixProvider() { } // warning CS8603: Possible null reference return. // warning CS8600: Converting null literal or possible null value to non-nullable type. // warning CS8625: Cannot convert null literal to non-nullable reference type. // warning CS8618: Non-nullable property is uninitialized public sealed override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create("CS8603", "CS8600", "CS8625", "CS8618"); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.Compile; public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var diagnostic = context.Diagnostics.First(); var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); if (root == null) { return; } var model = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false); if (model == null) { return; } var node = root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true); var declarationTypeToFix = TryGetDeclarationTypeToFix(model, node); if (declarationTypeToFix == null) { return; } context.RegisterCodeFix(new MyCodeAction( c => FixAsync(context.Document, diagnostic, c), GetEquivalenceKey(node, model)), context.Diagnostics); } private static string GetEquivalenceKey(SyntaxNode node, SemanticModel model) { return IsRemoteApiUsage(node, model) ? AssigningNullLiteralRemotelyEquivalenceKey : node.IsKind(SyntaxKind.ConditionalAccessExpression) ? ConditionalOperatorEquivalenceKey : AssigningNullLiteralLocallyEquivalenceKey; static bool IsRemoteApiUsage(SyntaxNode node, SemanticModel model) { if (node.IsParentKind(SyntaxKind.Argument)) { // M(null) could be used in a test return true; } if (node.Parent is AssignmentExpressionSyntax assignment) { var symbol = model.GetSymbolInfo(assignment.Left).Symbol; if (symbol is IFieldSymbol) { // x.field could be used in a test return true; } else if (symbol is IPropertySymbol) { // x.Property could be used in a test return true; } } return false; } } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { // a method can have multiple `return null;` statements, but we should only fix its return type once using var _ = PooledHashSet<TypeSyntax>.GetInstance(out var alreadyHandled); var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); if (model != null) { foreach (var diagnostic in diagnostics) { var node = diagnostic.Location.FindNode(getInnermostNodeForTie: true, cancellationToken); MakeDeclarationNullable(editor, model, node, alreadyHandled); } } } protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic, Document document, SemanticModel model, string? equivalenceKey, CancellationToken cancellationToken) { var node = diagnostic.Location.FindNode(getInnermostNodeForTie: true, cancellationToken); return equivalenceKey == GetEquivalenceKey(node, model); } private static void MakeDeclarationNullable(SyntaxEditor editor, SemanticModel model, SyntaxNode node, HashSet<TypeSyntax> alreadyHandled) { var declarationTypeToFix = TryGetDeclarationTypeToFix(model, node); if (declarationTypeToFix != null && alreadyHandled.Add(declarationTypeToFix)) { var fixedDeclaration = SyntaxFactory.NullableType(declarationTypeToFix.WithoutTrivia()).WithTriviaFrom(declarationTypeToFix); editor.ReplaceNode(declarationTypeToFix, fixedDeclaration); } } private static TypeSyntax? TryGetDeclarationTypeToFix(SemanticModel model, SyntaxNode node) { if (!IsExpressionSupported(node)) { return null; } if (node.IsParentKind(SyntaxKind.ReturnStatement, SyntaxKind.YieldReturnStatement)) { var containingMember = node.GetAncestors().FirstOrDefault(a => a.IsKind( SyntaxKind.MethodDeclaration, SyntaxKind.PropertyDeclaration, SyntaxKind.ParenthesizedLambdaExpression, SyntaxKind.SimpleLambdaExpression, SyntaxKind.LocalFunctionStatement, SyntaxKind.AnonymousMethodExpression, SyntaxKind.ConstructorDeclaration, SyntaxKind.DestructorDeclaration, SyntaxKind.OperatorDeclaration, SyntaxKind.IndexerDeclaration, SyntaxKind.EventDeclaration)); if (containingMember == null) { return null; } var onYield = node.IsParentKind(SyntaxKind.YieldReturnStatement); return containingMember switch { MethodDeclarationSyntax method => // string M() { return null; } // async Task<string> M() { return null; } // IEnumerable<string> M() { yield return null; } TryGetReturnType(method.ReturnType, method.Modifiers, onYield), LocalFunctionStatementSyntax localFunction => // string local() { return null; } // async Task<string> local() { return null; } // IEnumerable<string> local() { yield return null; } TryGetReturnType(localFunction.ReturnType, localFunction.Modifiers, onYield), PropertyDeclarationSyntax property => // string x { get { return null; } } // IEnumerable<string> Property { get { yield return null; } } TryGetReturnType(property.Type, modifiers: default, onYield), _ => null, }; } // string x = null; if (node.Parent?.Parent?.IsParentKind(SyntaxKind.VariableDeclaration) == true) { var variableDeclaration = (VariableDeclarationSyntax)node.Parent.Parent.Parent!; if (variableDeclaration.Variables.Count != 1) { // string x = null, y = null; return null; } return variableDeclaration.Type; } // x = null; if (node.Parent is AssignmentExpressionSyntax assignment) { var symbol = model.GetSymbolInfo(assignment.Left).Symbol; if (symbol is ILocalSymbol local) { var syntax = local.DeclaringSyntaxReferences[0].GetSyntax(); if (syntax is VariableDeclaratorSyntax declarator && declarator.Parent is VariableDeclarationSyntax declaration && declaration.Variables.Count == 1) { return declaration.Type; } } else if (symbol is IParameterSymbol parameter) { return TryGetParameterTypeSyntax(parameter); } else if (symbol is IFieldSymbol { IsImplicitlyDeclared: false } field) { // implicitly declared fields don't have DeclaringSyntaxReferences so filter them out var syntax = field.DeclaringSyntaxReferences[0].GetSyntax(); if (syntax is VariableDeclaratorSyntax declarator && declarator.Parent is VariableDeclarationSyntax declaration && declaration.Variables.Count == 1) { return declaration.Type; } else if (syntax is TupleElementSyntax tupleElement) { return tupleElement.Type; } } else if (symbol is IFieldSymbol { CorrespondingTupleField: IFieldSymbol tupleField }) { // Assigning a tuple field, eg. foo.Item1 = null // The tupleField won't have DeclaringSyntaxReferences because it's implicitly declared, otherwise it // would have fallen into the branch above. We can use the Locations instead, if there is one and it's in source if (tupleField.Locations is { Length: 1 } && tupleField.Locations[0] is { IsInSource: true } location) { if (location.FindNode(default) is TupleElementSyntax tupleElement) { return tupleElement.Type; } } } else if (symbol is IPropertySymbol property) { var syntax = property.DeclaringSyntaxReferences[0].GetSyntax(); if (syntax is PropertyDeclarationSyntax declaration) { return declaration.Type; } } return null; } // Method(null) if (node.Parent is ArgumentSyntax argument && argument.Parent?.Parent is InvocationExpressionSyntax invocation) { var symbol = model.GetSymbolInfo(invocation.Expression).Symbol; if (!(symbol is IMethodSymbol method) || method.PartialImplementationPart is object) { // We don't handle partial methods yet return null; } if (argument.NameColon?.Name is IdentifierNameSyntax { Identifier: var identifier }) { var parameter = method.Parameters.Where(p => p.Name == identifier.Text).FirstOrDefault(); return TryGetParameterTypeSyntax(parameter); } var index = invocation.ArgumentList.Arguments.IndexOf(argument); if (index >= 0 && index < method.Parameters.Length) { var parameter = method.Parameters[index]; return TryGetParameterTypeSyntax(parameter); } return null; } // string x { get; set; } = null; if (node.Parent.IsParentKind(SyntaxKind.PropertyDeclaration, out PropertyDeclarationSyntax? propertyDeclaration)) { return propertyDeclaration.Type; } // string x { get; } // Unassigned value that's not marked as null if (node is PropertyDeclarationSyntax propertyDeclarationSyntax) { return propertyDeclarationSyntax.Type; } // string x; // Unassigned value that's not marked as null if (node is VariableDeclaratorSyntax { Parent: VariableDeclarationSyntax { Parent: FieldDeclarationSyntax _ } declarationSyntax } && declarationSyntax.Variables.Count == 1) { return declarationSyntax.Type; } // void M(string x = null) { } if (node.Parent.IsParentKind(SyntaxKind.Parameter, out ParameterSyntax? optionalParameter)) { var parameterSymbol = model.GetDeclaredSymbol(optionalParameter); return TryGetParameterTypeSyntax(parameterSymbol); } // static string M() => null; if (node.IsParentKind(SyntaxKind.ArrowExpressionClause) && node.Parent.IsParentKind(SyntaxKind.MethodDeclaration, out MethodDeclarationSyntax? arrowMethod)) { return arrowMethod.ReturnType; } return null; // local functions static TypeSyntax? TryGetReturnType(TypeSyntax returnType, SyntaxTokenList modifiers, bool onYield) { if (modifiers.Any(SyntaxKind.AsyncKeyword) || onYield) { // async Task<string> M() { return null; } // async IAsyncEnumerable<string> M() { yield return null; } // IEnumerable<string> M() { yield return null; } return TryGetSingleTypeArgument(returnType); } // string M() { return null; } return returnType; } static TypeSyntax? TryGetSingleTypeArgument(TypeSyntax type) { switch (type) { case QualifiedNameSyntax qualified: return TryGetSingleTypeArgument(qualified.Right); case GenericNameSyntax generic: var typeArguments = generic.TypeArgumentList.Arguments; if (typeArguments.Count == 1) { return typeArguments[0]; } break; } return null; } static TypeSyntax? TryGetParameterTypeSyntax(IParameterSymbol? parameterSymbol) { if (parameterSymbol is object && parameterSymbol.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() is ParameterSyntax parameterSyntax && parameterSymbol.ContainingSymbol is IMethodSymbol method && method.GetAllMethodSymbolsOfPartialParts().Length == 1) { return parameterSyntax.Type; } return null; } } private static bool IsExpressionSupported(SyntaxNode node) { return node.IsKind( SyntaxKind.NullLiteralExpression, SyntaxKind.AsExpression, SyntaxKind.DefaultExpression, SyntaxKind.DefaultLiteralExpression, SyntaxKind.ConditionalExpression, SyntaxKind.ConditionalAccessExpression, SyntaxKind.PropertyDeclaration, SyntaxKind.VariableDeclarator); } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument, string equivalenceKey) : base(CSharpFeaturesResources.Declare_as_nullable, createChangedDocument, equivalenceKey) { } } } }
// Licensed to the .NET Foundation under one or more 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.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.DeclareAsNullable { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.DeclareAsNullable), Shared] internal class CSharpDeclareAsNullableCodeFixProvider : SyntaxEditorBasedCodeFixProvider { // We want to distinguish different situations: // 1. local null assignments: `return null;`, `local = null;`, `parameter = null;` (high confidence that the null is introduced deliberately and the API should be updated) // 2. invocation with null: `M(null);`, or assigning null to field or property (test code might do this even though the API should remain not-nullable, so FixAll should be invoked with care) // 3. conditional: `return x?.ToString();` private const string AssigningNullLiteralLocallyEquivalenceKey = nameof(AssigningNullLiteralLocallyEquivalenceKey); private const string AssigningNullLiteralRemotelyEquivalenceKey = nameof(AssigningNullLiteralRemotelyEquivalenceKey); private const string ConditionalOperatorEquivalenceKey = nameof(ConditionalOperatorEquivalenceKey); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpDeclareAsNullableCodeFixProvider() { } // warning CS8603: Possible null reference return. // warning CS8600: Converting null literal or possible null value to non-nullable type. // warning CS8625: Cannot convert null literal to non-nullable reference type. // warning CS8618: Non-nullable property is uninitialized public sealed override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create("CS8603", "CS8600", "CS8625", "CS8618"); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.Compile; public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var diagnostic = context.Diagnostics.First(); var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); if (root == null) { return; } var model = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false); if (model == null) { return; } var node = root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true); var declarationTypeToFix = TryGetDeclarationTypeToFix(model, node); if (declarationTypeToFix == null) { return; } context.RegisterCodeFix(new MyCodeAction( c => FixAsync(context.Document, diagnostic, c), GetEquivalenceKey(node, model)), context.Diagnostics); } private static string GetEquivalenceKey(SyntaxNode node, SemanticModel model) { return IsRemoteApiUsage(node, model) ? AssigningNullLiteralRemotelyEquivalenceKey : node.IsKind(SyntaxKind.ConditionalAccessExpression) ? ConditionalOperatorEquivalenceKey : AssigningNullLiteralLocallyEquivalenceKey; static bool IsRemoteApiUsage(SyntaxNode node, SemanticModel model) { if (node.IsParentKind(SyntaxKind.Argument)) { // M(null) could be used in a test return true; } if (node.Parent is AssignmentExpressionSyntax assignment) { var symbol = model.GetSymbolInfo(assignment.Left).Symbol; if (symbol is IFieldSymbol) { // x.field could be used in a test return true; } else if (symbol is IPropertySymbol) { // x.Property could be used in a test return true; } } return false; } } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { // a method can have multiple `return null;` statements, but we should only fix its return type once using var _ = PooledHashSet<TypeSyntax>.GetInstance(out var alreadyHandled); var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); if (model != null) { foreach (var diagnostic in diagnostics) { var node = diagnostic.Location.FindNode(getInnermostNodeForTie: true, cancellationToken); MakeDeclarationNullable(editor, model, node, alreadyHandled); } } } protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic, Document document, SemanticModel model, string? equivalenceKey, CancellationToken cancellationToken) { var node = diagnostic.Location.FindNode(getInnermostNodeForTie: true, cancellationToken); return equivalenceKey == GetEquivalenceKey(node, model); } private static void MakeDeclarationNullable(SyntaxEditor editor, SemanticModel model, SyntaxNode node, HashSet<TypeSyntax> alreadyHandled) { var declarationTypeToFix = TryGetDeclarationTypeToFix(model, node); if (declarationTypeToFix != null && alreadyHandled.Add(declarationTypeToFix)) { var fixedDeclaration = SyntaxFactory.NullableType(declarationTypeToFix.WithoutTrivia()).WithTriviaFrom(declarationTypeToFix); editor.ReplaceNode(declarationTypeToFix, fixedDeclaration); } } private static TypeSyntax? TryGetDeclarationTypeToFix(SemanticModel model, SyntaxNode node) { if (!IsExpressionSupported(node)) { return null; } if (node.IsParentKind(SyntaxKind.ReturnStatement, SyntaxKind.YieldReturnStatement)) { var containingMember = node.GetAncestors().FirstOrDefault(a => a.IsKind( SyntaxKind.MethodDeclaration, SyntaxKind.PropertyDeclaration, SyntaxKind.ParenthesizedLambdaExpression, SyntaxKind.SimpleLambdaExpression, SyntaxKind.LocalFunctionStatement, SyntaxKind.AnonymousMethodExpression, SyntaxKind.ConstructorDeclaration, SyntaxKind.DestructorDeclaration, SyntaxKind.OperatorDeclaration, SyntaxKind.IndexerDeclaration, SyntaxKind.EventDeclaration)); if (containingMember == null) { return null; } var onYield = node.IsParentKind(SyntaxKind.YieldReturnStatement); return containingMember switch { MethodDeclarationSyntax method => // string M() { return null; } // async Task<string> M() { return null; } // IEnumerable<string> M() { yield return null; } TryGetReturnType(method.ReturnType, method.Modifiers, onYield), LocalFunctionStatementSyntax localFunction => // string local() { return null; } // async Task<string> local() { return null; } // IEnumerable<string> local() { yield return null; } TryGetReturnType(localFunction.ReturnType, localFunction.Modifiers, onYield), PropertyDeclarationSyntax property => // string x { get { return null; } } // IEnumerable<string> Property { get { yield return null; } } TryGetReturnType(property.Type, modifiers: default, onYield), _ => null, }; } // string x = null; if (node.Parent?.Parent?.IsParentKind(SyntaxKind.VariableDeclaration) == true) { var variableDeclaration = (VariableDeclarationSyntax)node.Parent.Parent.Parent!; if (variableDeclaration.Variables.Count != 1) { // string x = null, y = null; return null; } return variableDeclaration.Type; } // x = null; if (node.Parent is AssignmentExpressionSyntax assignment) { var symbol = model.GetSymbolInfo(assignment.Left).Symbol; if (symbol is ILocalSymbol local) { var syntax = local.DeclaringSyntaxReferences[0].GetSyntax(); if (syntax is VariableDeclaratorSyntax declarator && declarator.Parent is VariableDeclarationSyntax declaration && declaration.Variables.Count == 1) { return declaration.Type; } } else if (symbol is IParameterSymbol parameter) { return TryGetParameterTypeSyntax(parameter); } else if (symbol is IFieldSymbol { IsImplicitlyDeclared: false } field) { // implicitly declared fields don't have DeclaringSyntaxReferences so filter them out var syntax = field.DeclaringSyntaxReferences[0].GetSyntax(); if (syntax is VariableDeclaratorSyntax declarator && declarator.Parent is VariableDeclarationSyntax declaration && declaration.Variables.Count == 1) { return declaration.Type; } else if (syntax is TupleElementSyntax tupleElement) { return tupleElement.Type; } } else if (symbol is IFieldSymbol { CorrespondingTupleField: IFieldSymbol tupleField }) { // Assigning a tuple field, eg. foo.Item1 = null // The tupleField won't have DeclaringSyntaxReferences because it's implicitly declared, otherwise it // would have fallen into the branch above. We can use the Locations instead, if there is one and it's in source if (tupleField.Locations is { Length: 1 } && tupleField.Locations[0] is { IsInSource: true } location) { if (location.FindNode(default) is TupleElementSyntax tupleElement) { return tupleElement.Type; } } } else if (symbol is IPropertySymbol property) { var syntax = property.DeclaringSyntaxReferences[0].GetSyntax(); if (syntax is PropertyDeclarationSyntax declaration) { return declaration.Type; } } return null; } // Method(null) if (node.Parent is ArgumentSyntax argument && argument.Parent?.Parent is InvocationExpressionSyntax invocation) { var symbol = model.GetSymbolInfo(invocation.Expression).Symbol; if (!(symbol is IMethodSymbol method) || method.PartialImplementationPart is object) { // We don't handle partial methods yet return null; } if (argument.NameColon?.Name is IdentifierNameSyntax { Identifier: var identifier }) { var parameter = method.Parameters.Where(p => p.Name == identifier.Text).FirstOrDefault(); return TryGetParameterTypeSyntax(parameter); } var index = invocation.ArgumentList.Arguments.IndexOf(argument); if (index >= 0 && index < method.Parameters.Length) { var parameter = method.Parameters[index]; return TryGetParameterTypeSyntax(parameter); } return null; } // string x { get; set; } = null; if (node.Parent.IsParentKind(SyntaxKind.PropertyDeclaration, out PropertyDeclarationSyntax? propertyDeclaration)) { return propertyDeclaration.Type; } // string x { get; } // Unassigned value that's not marked as null if (node is PropertyDeclarationSyntax propertyDeclarationSyntax) { return propertyDeclarationSyntax.Type; } // string x; // Unassigned value that's not marked as null if (node is VariableDeclaratorSyntax { Parent: VariableDeclarationSyntax { Parent: FieldDeclarationSyntax _ } declarationSyntax } && declarationSyntax.Variables.Count == 1) { return declarationSyntax.Type; } // void M(string x = null) { } if (node.Parent.IsParentKind(SyntaxKind.Parameter, out ParameterSyntax? optionalParameter)) { var parameterSymbol = model.GetDeclaredSymbol(optionalParameter); return TryGetParameterTypeSyntax(parameterSymbol); } // static string M() => null; if (node.IsParentKind(SyntaxKind.ArrowExpressionClause) && node.Parent.IsParentKind(SyntaxKind.MethodDeclaration, out MethodDeclarationSyntax? arrowMethod)) { return arrowMethod.ReturnType; } return null; // local functions static TypeSyntax? TryGetReturnType(TypeSyntax returnType, SyntaxTokenList modifiers, bool onYield) { if (modifiers.Any(SyntaxKind.AsyncKeyword) || onYield) { // async Task<string> M() { return null; } // async IAsyncEnumerable<string> M() { yield return null; } // IEnumerable<string> M() { yield return null; } return TryGetSingleTypeArgument(returnType); } // string M() { return null; } return returnType; } static TypeSyntax? TryGetSingleTypeArgument(TypeSyntax type) { switch (type) { case QualifiedNameSyntax qualified: return TryGetSingleTypeArgument(qualified.Right); case GenericNameSyntax generic: var typeArguments = generic.TypeArgumentList.Arguments; if (typeArguments.Count == 1) { return typeArguments[0]; } break; } return null; } static TypeSyntax? TryGetParameterTypeSyntax(IParameterSymbol? parameterSymbol) { if (parameterSymbol is object && parameterSymbol.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() is ParameterSyntax parameterSyntax && parameterSymbol.ContainingSymbol is IMethodSymbol method && method.GetAllMethodSymbolsOfPartialParts().Length == 1) { return parameterSyntax.Type; } return null; } } private static bool IsExpressionSupported(SyntaxNode node) { return node.IsKind( SyntaxKind.NullLiteralExpression, SyntaxKind.AsExpression, SyntaxKind.DefaultExpression, SyntaxKind.DefaultLiteralExpression, SyntaxKind.ConditionalExpression, SyntaxKind.ConditionalAccessExpression, SyntaxKind.PropertyDeclaration, SyntaxKind.VariableDeclarator); } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument, string equivalenceKey) : base(CSharpFeaturesResources.Declare_as_nullable, createChangedDocument, equivalenceKey) { } } } }
-1