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
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
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
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/Serialization/SerializationThreadPool.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; namespace Roslyn.Utilities { internal static class SerializationThreadPool { public static Task<object?> RunOnBackgroundThreadAsync(Func<object?> start) => ImmediateBackgroundThreadPool.QueueAsync(start); public static Task<object?> RunOnBackgroundThreadAsync(Func<object?, object?> start, object? obj) => ImmediateBackgroundThreadPool.QueueAsync(start, obj); /// <summary> /// Naive thread pool focused on reducing the latency to execution of chunky work items as much as possible. /// If a thread is ready to process a work item the moment a work item is queued, it's used, otherwise /// a new thread is created. This is meant as a stop-gap measure for workloads that would otherwise be /// creating a new thread for every work item. /// </summary> /// <remarks> /// This class is derived from <see href="https://github.com/dotnet/machinelearning/blob/ebc431f531436c45097c88757dfd14fe0c1381b3/src/Microsoft.ML.Core/Utilities/ThreadUtils.cs">dotnet/machinelearning</see>. /// </remarks> private static class ImmediateBackgroundThreadPool { /// <summary>How long should threads wait around for additional work items before retiring themselves.</summary> private static readonly TimeSpan s_idleTimeout = TimeSpan.FromSeconds(1); /// <summary>The queue of work items. Also used as a lock to protect all relevant state.</summary> private static readonly Queue<(Delegate function, object? state, TaskCompletionSource<object?> tcs)> s_queue = new(); /// <summary>The number of threads currently waiting in <c>tryDequeue</c> for work to arrive.</summary> private static int s_availableThreads = 0; /// <summary> /// Queues a <see cref="Func{TResult}"/> delegate to be executed immediately on another thread, /// and returns a <see cref="Task"/> that represents its eventual completion. The task will /// always end in the <see cref="TaskStatus.RanToCompletion"/> state; if the delegate throws /// an exception, it'll be allowed to propagate on the thread, crashing the process. /// </summary> public static Task<object?> QueueAsync(Func<object?> threadStart) => QueueAsync((Delegate)threadStart, state: null); /// <summary> /// Queues a <see cref="Func{T, TResult}"/> delegate and associated state to be executed immediately on /// another thread, and returns a <see cref="Task"/> that represents its eventual completion. /// </summary> public static Task<object?> QueueAsync(Func<object?, object?> threadStart, object? state) => QueueAsync((Delegate)threadStart, state); private static Task<object?> QueueAsync(Delegate threadStart, object? state) { // Create the TaskCompletionSource used to represent this work. 'RunContinuationsAsynchronously' ensures // continuations do not also run on the threads created by 'createThread'. var tcs = new TaskCompletionSource<object?>(TaskCreationOptions.RunContinuationsAsynchronously); // Queue the work for a thread to pick up. If no thread is immediately available, it will create one. enqueue((threadStart, state, tcs)); // Return the task. return tcs.Task; static void createThread() { // Create a new background thread to run the work. var t = new Thread(() => { // Repeatedly get the next item and invoke it, setting its TCS when we're done. // This will wait for up to the idle time before giving up and exiting. while (tryDequeue(out var item)) { try { if (item.function is Func<object?, object?> callbackWithState) { item.tcs.SetResult(callbackWithState(item.state)); } else { item.tcs.SetResult(((Func<object?>)item.function)()); } } catch (OperationCanceledException ex) { item.tcs.TrySetCanceled(ex.CancellationToken); } catch (Exception ex) { item.tcs.TrySetException(ex); } } }); t.IsBackground = true; t.Start(); } static void enqueue((Delegate function, object? state, TaskCompletionSource<object?> tcs) item) { // Enqueue the work. If there are currently fewer threads waiting // for work than there are work items in the queue, create another // thread. This is a heuristic, in that we might end up creating // more threads than are truly needed, but this whole type is being // used to replace a previous solution where every work item created // its own thread, so this is an improvement regardless of any // such inefficiencies. lock (s_queue) { s_queue.Enqueue(item); if (s_queue.Count <= s_availableThreads) { Monitor.Pulse(s_queue); return; } } // No thread was currently available. Create one. createThread(); } static bool tryDequeue(out (Delegate function, object? state, TaskCompletionSource<object?> tcs) item) { // Dequeues the next item if one is available. Before checking, // the available thread count is increased, so that enqueuers can // see how many threads are currently waiting, with the count // decreased after. Each time it waits, it'll wait for at most // the idle timeout before giving up. lock (s_queue) { s_availableThreads++; try { while (s_queue.Count == 0) { if (!Monitor.Wait(s_queue, s_idleTimeout)) { if (s_queue.Count > 0) { // The wait timed out, but a new item was added to the queue between the time // this thread entered the ready queue and the point where the lock was // reacquired. Make sure to process the available item, since there is no // guarantee another thread will exist or be notified to handle it separately. // // The following is one sequence which requires this path handle the queued // element for correctness: // // 1. Thread A calls tryDequeue, and releases the lock in Wait // 2. Thread B calls enqueue and holds the lock // 3. Thread A times out and enters the ready thread queue // 4. Thread B observes that s_queue.Count (1) <= s_availableThreads (1), so it // calls Pulse instead of creating a new thread // 5. Thread B releases the lock // 6. Thread A acquires the lock, and Monitor.Wait returns false // // Since no new thread was created in step 4, we must handle the enqueued // element or the thread will exit and the item will sit in the queue // indefinitely. break; } item = default; return false; } } } finally { s_availableThreads--; } item = s_queue.Dequeue(); 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.Generic; using System.Threading; using System.Threading.Tasks; namespace Roslyn.Utilities { internal static class SerializationThreadPool { public static Task<object?> RunOnBackgroundThreadAsync(Func<object?> start) => ImmediateBackgroundThreadPool.QueueAsync(start); public static Task<object?> RunOnBackgroundThreadAsync(Func<object?, object?> start, object? obj) => ImmediateBackgroundThreadPool.QueueAsync(start, obj); /// <summary> /// Naive thread pool focused on reducing the latency to execution of chunky work items as much as possible. /// If a thread is ready to process a work item the moment a work item is queued, it's used, otherwise /// a new thread is created. This is meant as a stop-gap measure for workloads that would otherwise be /// creating a new thread for every work item. /// </summary> /// <remarks> /// This class is derived from <see href="https://github.com/dotnet/machinelearning/blob/ebc431f531436c45097c88757dfd14fe0c1381b3/src/Microsoft.ML.Core/Utilities/ThreadUtils.cs">dotnet/machinelearning</see>. /// </remarks> private static class ImmediateBackgroundThreadPool { /// <summary>How long should threads wait around for additional work items before retiring themselves.</summary> private static readonly TimeSpan s_idleTimeout = TimeSpan.FromSeconds(1); /// <summary>The queue of work items. Also used as a lock to protect all relevant state.</summary> private static readonly Queue<(Delegate function, object? state, TaskCompletionSource<object?> tcs)> s_queue = new(); /// <summary>The number of threads currently waiting in <c>tryDequeue</c> for work to arrive.</summary> private static int s_availableThreads = 0; /// <summary> /// Queues a <see cref="Func{TResult}"/> delegate to be executed immediately on another thread, /// and returns a <see cref="Task"/> that represents its eventual completion. The task will /// always end in the <see cref="TaskStatus.RanToCompletion"/> state; if the delegate throws /// an exception, it'll be allowed to propagate on the thread, crashing the process. /// </summary> public static Task<object?> QueueAsync(Func<object?> threadStart) => QueueAsync((Delegate)threadStart, state: null); /// <summary> /// Queues a <see cref="Func{T, TResult}"/> delegate and associated state to be executed immediately on /// another thread, and returns a <see cref="Task"/> that represents its eventual completion. /// </summary> public static Task<object?> QueueAsync(Func<object?, object?> threadStart, object? state) => QueueAsync((Delegate)threadStart, state); private static Task<object?> QueueAsync(Delegate threadStart, object? state) { // Create the TaskCompletionSource used to represent this work. 'RunContinuationsAsynchronously' ensures // continuations do not also run on the threads created by 'createThread'. var tcs = new TaskCompletionSource<object?>(TaskCreationOptions.RunContinuationsAsynchronously); // Queue the work for a thread to pick up. If no thread is immediately available, it will create one. enqueue((threadStart, state, tcs)); // Return the task. return tcs.Task; static void createThread() { // Create a new background thread to run the work. var t = new Thread(() => { // Repeatedly get the next item and invoke it, setting its TCS when we're done. // This will wait for up to the idle time before giving up and exiting. while (tryDequeue(out var item)) { try { if (item.function is Func<object?, object?> callbackWithState) { item.tcs.SetResult(callbackWithState(item.state)); } else { item.tcs.SetResult(((Func<object?>)item.function)()); } } catch (OperationCanceledException ex) { item.tcs.TrySetCanceled(ex.CancellationToken); } catch (Exception ex) { item.tcs.TrySetException(ex); } } }); t.IsBackground = true; t.Start(); } static void enqueue((Delegate function, object? state, TaskCompletionSource<object?> tcs) item) { // Enqueue the work. If there are currently fewer threads waiting // for work than there are work items in the queue, create another // thread. This is a heuristic, in that we might end up creating // more threads than are truly needed, but this whole type is being // used to replace a previous solution where every work item created // its own thread, so this is an improvement regardless of any // such inefficiencies. lock (s_queue) { s_queue.Enqueue(item); if (s_queue.Count <= s_availableThreads) { Monitor.Pulse(s_queue); return; } } // No thread was currently available. Create one. createThread(); } static bool tryDequeue(out (Delegate function, object? state, TaskCompletionSource<object?> tcs) item) { // Dequeues the next item if one is available. Before checking, // the available thread count is increased, so that enqueuers can // see how many threads are currently waiting, with the count // decreased after. Each time it waits, it'll wait for at most // the idle timeout before giving up. lock (s_queue) { s_availableThreads++; try { while (s_queue.Count == 0) { if (!Monitor.Wait(s_queue, s_idleTimeout)) { if (s_queue.Count > 0) { // The wait timed out, but a new item was added to the queue between the time // this thread entered the ready queue and the point where the lock was // reacquired. Make sure to process the available item, since there is no // guarantee another thread will exist or be notified to handle it separately. // // The following is one sequence which requires this path handle the queued // element for correctness: // // 1. Thread A calls tryDequeue, and releases the lock in Wait // 2. Thread B calls enqueue and holds the lock // 3. Thread A times out and enters the ready thread queue // 4. Thread B observes that s_queue.Count (1) <= s_availableThreads (1), so it // calls Pulse instead of creating a new thread // 5. Thread B releases the lock // 6. Thread A acquires the lock, and Monitor.Wait returns false // // Since no new thread was created in step 4, we must handle the enqueued // element or the thread will exit and the item will sit in the queue // indefinitely. break; } item = default; return false; } } } finally { s_availableThreads--; } item = s_queue.Dequeue(); return true; } } } } } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/BKTree.Edge.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Roslyn.Utilities { internal partial class BKTree { private struct Edge { // The edit distance between the child and parent connected by this edge. // The child can be found in _nodes at ChildNodeIndex. public readonly int EditDistance; /// <summary>Where the child node can be found in <see cref="_nodes"/>.</summary> public readonly int ChildNodeIndex; public Edge(int editDistance, int childNodeIndex) { EditDistance = editDistance; ChildNodeIndex = childNodeIndex; } internal void WriteTo(ObjectWriter writer) { writer.WriteInt32(EditDistance); writer.WriteInt32(ChildNodeIndex); } internal static Edge ReadFrom(ObjectReader reader) => new(editDistance: reader.ReadInt32(), childNodeIndex: reader.ReadInt32()); } } }
// Licensed to the .NET Foundation under one or more 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 Roslyn.Utilities { internal partial class BKTree { private struct Edge { // The edit distance between the child and parent connected by this edge. // The child can be found in _nodes at ChildNodeIndex. public readonly int EditDistance; /// <summary>Where the child node can be found in <see cref="_nodes"/>.</summary> public readonly int ChildNodeIndex; public Edge(int editDistance, int childNodeIndex) { EditDistance = editDistance; ChildNodeIndex = childNodeIndex; } internal void WriteTo(ObjectWriter writer) { writer.WriteInt32(EditDistance); writer.WriteInt32(ChildNodeIndex); } internal static Edge ReadFrom(ObjectReader reader) => new(editDistance: reader.ReadInt32(), childNodeIndex: reader.ReadInt32()); } } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/CodeLens/ReferenceMethodDescriptor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Runtime.Serialization; namespace Microsoft.CodeAnalysis.CodeLens { /// <summary> /// A caller method of a callee /// </summary> [DataContract] internal sealed class ReferenceMethodDescriptor { /// <summary> /// Returns method's fully quilified name without parameters /// </summary> [DataMember(Order = 0)] public string FullName { get; private set; } /// <summary> /// Returns method's file path. /// </summary> [DataMember(Order = 1)] public string FilePath { get; private set; } /// <summary> /// Returns output file path for the project containing the method. /// </summary> [DataMember(Order = 2)] public string OutputFilePath { get; private set; } /// <summary> /// Describe a caller method of a callee /// </summary> /// <param name="fullName">Method's fully qualified name</param> /// <param name="filePath">Method full path</param> /// <remarks> /// Method full name is expected to be in the .NET full name type convention. That is, /// namespace/type is delimited by '.' and nested type is delimited by '+' /// </remarks> public ReferenceMethodDescriptor(string fullName, string filePath, string outputFilePath) { FullName = fullName; FilePath = filePath; OutputFilePath = outputFilePath; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Runtime.Serialization; namespace Microsoft.CodeAnalysis.CodeLens { /// <summary> /// A caller method of a callee /// </summary> [DataContract] internal sealed class ReferenceMethodDescriptor { /// <summary> /// Returns method's fully quilified name without parameters /// </summary> [DataMember(Order = 0)] public string FullName { get; private set; } /// <summary> /// Returns method's file path. /// </summary> [DataMember(Order = 1)] public string FilePath { get; private set; } /// <summary> /// Returns output file path for the project containing the method. /// </summary> [DataMember(Order = 2)] public string OutputFilePath { get; private set; } /// <summary> /// Describe a caller method of a callee /// </summary> /// <param name="fullName">Method's fully qualified name</param> /// <param name="filePath">Method full path</param> /// <remarks> /// Method full name is expected to be in the .NET full name type convention. That is, /// namespace/type is delimited by '.' and nested type is delimited by '+' /// </remarks> public ReferenceMethodDescriptor(string fullName, string filePath, string outputFilePath) { FullName = fullName; FilePath = filePath; OutputFilePath = outputFilePath; } } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/LanguageServer/ProtocolUnitTests/Formatting/FormatDocumentOnTypeTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Formatting { public class FormatDocumentOnTypeTests : AbstractLanguageServerProtocolTests { [Fact] public async Task TestFormatDocumentOnTypeAsync() { var markup = @"class A { void M() { if (true) {{|type:|} } }"; var expected = @"class A { void M() { if (true) { } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var characterTyped = ";"; var locationTyped = locations["type"].Single(); var documentText = await testLspServer.GetCurrentSolution().GetDocuments(locationTyped.Uri).Single().GetTextAsync(); var results = await RunFormatDocumentOnTypeAsync(testLspServer, characterTyped, locationTyped); var actualText = ApplyTextEdits(results, documentText); Assert.Equal(expected, actualText); } [Fact] public async Task TestFormatDocumentOnType_UseTabsAsync() { var markup = @"class A { void M() { if (true) {{|type:|} } }"; var expected = @"class A { void M() { if (true) { } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var characterTyped = ";"; var locationTyped = locations["type"].Single(); var documentText = await testLspServer.GetCurrentSolution().GetDocuments(locationTyped.Uri).Single().GetTextAsync(); var results = await RunFormatDocumentOnTypeAsync(testLspServer, characterTyped, locationTyped, insertSpaces: false, tabSize: 4); var actualText = ApplyTextEdits(results, documentText); Assert.Equal(expected, actualText); } private static async Task<LSP.TextEdit[]> RunFormatDocumentOnTypeAsync( TestLspServer testLspServer, string characterTyped, LSP.Location locationTyped, bool insertSpaces = true, int tabSize = 4) { return await testLspServer.ExecuteRequestAsync<LSP.DocumentOnTypeFormattingParams, LSP.TextEdit[]>(LSP.Methods.TextDocumentOnTypeFormattingName, CreateDocumentOnTypeFormattingParams( characterTyped, locationTyped, insertSpaces, tabSize), new LSP.ClientCapabilities(), null, CancellationToken.None); } private static LSP.DocumentOnTypeFormattingParams CreateDocumentOnTypeFormattingParams( string characterTyped, LSP.Location locationTyped, bool insertSpaces, int tabSize) => new LSP.DocumentOnTypeFormattingParams() { Position = locationTyped.Range.Start, Character = characterTyped, TextDocument = CreateTextDocumentIdentifier(locationTyped.Uri), Options = new LSP.FormattingOptions() { InsertSpaces = insertSpaces, TabSize = tabSize, } }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Formatting { public class FormatDocumentOnTypeTests : AbstractLanguageServerProtocolTests { [Fact] public async Task TestFormatDocumentOnTypeAsync() { var markup = @"class A { void M() { if (true) {{|type:|} } }"; var expected = @"class A { void M() { if (true) { } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var characterTyped = ";"; var locationTyped = locations["type"].Single(); var documentText = await testLspServer.GetCurrentSolution().GetDocuments(locationTyped.Uri).Single().GetTextAsync(); var results = await RunFormatDocumentOnTypeAsync(testLspServer, characterTyped, locationTyped); var actualText = ApplyTextEdits(results, documentText); Assert.Equal(expected, actualText); } [Fact] public async Task TestFormatDocumentOnType_UseTabsAsync() { var markup = @"class A { void M() { if (true) {{|type:|} } }"; var expected = @"class A { void M() { if (true) { } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var characterTyped = ";"; var locationTyped = locations["type"].Single(); var documentText = await testLspServer.GetCurrentSolution().GetDocuments(locationTyped.Uri).Single().GetTextAsync(); var results = await RunFormatDocumentOnTypeAsync(testLspServer, characterTyped, locationTyped, insertSpaces: false, tabSize: 4); var actualText = ApplyTextEdits(results, documentText); Assert.Equal(expected, actualText); } private static async Task<LSP.TextEdit[]> RunFormatDocumentOnTypeAsync( TestLspServer testLspServer, string characterTyped, LSP.Location locationTyped, bool insertSpaces = true, int tabSize = 4) { return await testLspServer.ExecuteRequestAsync<LSP.DocumentOnTypeFormattingParams, LSP.TextEdit[]>(LSP.Methods.TextDocumentOnTypeFormattingName, CreateDocumentOnTypeFormattingParams( characterTyped, locationTyped, insertSpaces, tabSize), new LSP.ClientCapabilities(), null, CancellationToken.None); } private static LSP.DocumentOnTypeFormattingParams CreateDocumentOnTypeFormattingParams( string characterTyped, LSP.Location locationTyped, bool insertSpaces, int tabSize) => new LSP.DocumentOnTypeFormattingParams() { Position = locationTyped.Range.Start, Character = characterTyped, TextDocument = CreateTextDocumentIdentifier(locationTyped.Uri), Options = new LSP.FormattingOptions() { InsertSpaces = insertSpaces, TabSize = tabSize, } }; } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/Interactive/Host/Interactive/Core/InteractiveHost.LazyRemoteService.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. extern alias Scripting; using System; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Pipes; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Roslyn.Utilities; using StreamJsonRpc; using Scripting::Microsoft.CodeAnalysis.Scripting.Hosting; namespace Microsoft.CodeAnalysis.Interactive { internal partial class InteractiveHost { private sealed class LazyRemoteService { private readonly AsyncLazy<InitializedRemoteService> _lazyInitializedService; private readonly CancellationTokenSource _cancellationSource; public readonly InteractiveHostOptions Options; public readonly InteractiveHost Host; public readonly bool SkipInitialization; public readonly int InstanceId; public LazyRemoteService(InteractiveHost host, InteractiveHostOptions options, int instanceId, bool skipInitialization) { _lazyInitializedService = new AsyncLazy<InitializedRemoteService>(TryStartAndInitializeProcessAsync, cacheResult: true); _cancellationSource = new CancellationTokenSource(); InstanceId = instanceId; Options = options; Host = host; SkipInitialization = skipInitialization; } public void Dispose() { // Cancel the creation of the process if it is in progress. // If it is the cancellation will clean up all resources allocated during the creation. _cancellationSource.Cancel(); // If the value has been calculated already, dispose the service. if (_lazyInitializedService.TryGetValue(out var initializedService)) { initializedService.Service?.Dispose(); } } internal Task<InitializedRemoteService> GetInitializedServiceAsync() => _lazyInitializedService.GetValueAsync(_cancellationSource.Token); internal InitializedRemoteService? TryGetInitializedService() => _lazyInitializedService.TryGetValue(out var service) ? service : default; private async Task<InitializedRemoteService> TryStartAndInitializeProcessAsync(CancellationToken cancellationToken) { try { var remoteService = await TryStartProcessAsync(Options.HostPath, Options.Culture, cancellationToken).ConfigureAwait(false); if (remoteService == null) { return default; } RemoteExecutionResult result; if (SkipInitialization) { result = new RemoteExecutionResult( success: true, sourcePaths: ImmutableArray<string>.Empty, referencePaths: ImmutableArray<string>.Empty, workingDirectory: Host._initialWorkingDirectory, initializationResult: new RemoteInitializationResult( initializationScript: null, metadataReferencePaths: ImmutableArray.Create(typeof(object).Assembly.Location, typeof(InteractiveScriptGlobals).Assembly.Location), imports: ImmutableArray<string>.Empty)); Host.ProcessInitialized?.Invoke(remoteService.PlatformInfo, Options, result); return new InitializedRemoteService(remoteService, result); } bool initializing = true; cancellationToken.Register(() => { if (initializing) { // kill the process without triggering auto-reset: remoteService.Dispose(); } }); // try to execute initialization script: var isRestarting = InstanceId > 1; result = await ExecuteRemoteAsync(remoteService, nameof(Service.InitializeContextAsync), Options.InitializationFilePath, isRestarting).ConfigureAwait(false); initializing = false; if (!result.Success) { Host.ReportProcessExited(remoteService.Process); remoteService.Dispose(); return default; } Contract.ThrowIfNull(result.InitializationResult); // Hook up a handler that initiates restart when the process exits. // Note that this is just so that we restart the process as soon as we see it dying and it doesn't need to be 100% bullet-proof. // If we don't receive the "process exited" event we will restart the process upon the next remote operation. remoteService.HookAutoRestartEvent(); Host.ProcessInitialized?.Invoke(remoteService.PlatformInfo, Options, result); return new InitializedRemoteService(remoteService, result); } #pragma warning disable CA2016 // Forward the 'CancellationToken' parameter to methods // await ExecuteRemoteAsync above does not take cancellationToken // - we don't currently support cancellation of the RPC call, // but JsonRpc.InvokeAsync that we use still claims it may throw OperationCanceledException.. catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e)) #pragma warning restore CA2016 { throw ExceptionUtilities.Unreachable; } } private async Task<RemoteService?> TryStartProcessAsync(string hostPath, CultureInfo culture, CancellationToken cancellationToken) { int currentProcessId = Process.GetCurrentProcess().Id; var pipeName = typeof(InteractiveHost).FullName + Guid.NewGuid(); var newProcess = new Process { StartInfo = new ProcessStartInfo(hostPath) { Arguments = pipeName + " " + currentProcessId, WorkingDirectory = Host._initialWorkingDirectory, CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, StandardErrorEncoding = OutputEncoding, StandardOutputEncoding = OutputEncoding }, // enables Process.Exited event to be raised: EnableRaisingEvents = true }; try { newProcess.Start(); } catch (Exception e) { Host.WriteOutputInBackground( isError: true, string.Format(InteractiveHostResources.Failed_to_create_a_remote_process_for_interactive_code_execution, hostPath), e.Message); Host.InteractiveHostProcessCreationFailed?.Invoke(e, TryGetExitCode(newProcess)); return null; } Host.InteractiveHostProcessCreated?.Invoke(newProcess); int newProcessId = -1; try { newProcessId = newProcess.Id; } catch { newProcessId = 0; } var clientStream = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous); JsonRpc? jsonRpc = null; void ProcessExitedBeforeEstablishingConnection(object sender, EventArgs e) { Host.InteractiveHostProcessCreationFailed?.Invoke(null, TryGetExitCode(newProcess)); _cancellationSource.Cancel(); } // Connecting the named pipe client would block if the process exits before the connection is established, // as the client waits for the server to become available. We signal the cancellation token to abort. newProcess.Exited += ProcessExitedBeforeEstablishingConnection; InteractiveHostPlatformInfo platformInfo; try { if (!CheckAlive(newProcess, hostPath)) { Host.InteractiveHostProcessCreationFailed?.Invoke(null, TryGetExitCode(newProcess)); return null; } await clientStream.ConnectAsync(cancellationToken).ConfigureAwait(false); jsonRpc = CreateRpc(clientStream, incomingCallTarget: null); platformInfo = (await jsonRpc.InvokeWithCancellationAsync<InteractiveHostPlatformInfo.Data>( nameof(Service.InitializeAsync), new object[] { Host._replServiceProviderType.AssemblyQualifiedName, culture.Name }, cancellationToken).ConfigureAwait(false)).Deserialize(); } catch (Exception e) { if (CheckAlive(newProcess, hostPath)) { RemoteService.InitiateTermination(newProcess, newProcessId); } jsonRpc?.Dispose(); Host.InteractiveHostProcessCreationFailed?.Invoke(e, TryGetExitCode(newProcess)); return null; } finally { newProcess.Exited -= ProcessExitedBeforeEstablishingConnection; } return new RemoteService(Host, newProcess, newProcessId, jsonRpc, platformInfo, Options); } private bool CheckAlive(Process process, string hostPath) { bool alive = process.IsAlive(); if (!alive) { string errorString = process.StandardError.ReadToEnd(); Host.WriteOutputInBackground( isError: true, string.Format(InteractiveHostResources.Failed_to_launch_0_process_exit_code_colon_1_with_output_colon, hostPath, process.ExitCode), errorString); } return alive; } private static int? TryGetExitCode(Process process) { try { return process.ExitCode; } catch { 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. extern alias Scripting; using System; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Pipes; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Roslyn.Utilities; using StreamJsonRpc; using Scripting::Microsoft.CodeAnalysis.Scripting.Hosting; namespace Microsoft.CodeAnalysis.Interactive { internal partial class InteractiveHost { private sealed class LazyRemoteService { private readonly AsyncLazy<InitializedRemoteService> _lazyInitializedService; private readonly CancellationTokenSource _cancellationSource; public readonly InteractiveHostOptions Options; public readonly InteractiveHost Host; public readonly bool SkipInitialization; public readonly int InstanceId; public LazyRemoteService(InteractiveHost host, InteractiveHostOptions options, int instanceId, bool skipInitialization) { _lazyInitializedService = new AsyncLazy<InitializedRemoteService>(TryStartAndInitializeProcessAsync, cacheResult: true); _cancellationSource = new CancellationTokenSource(); InstanceId = instanceId; Options = options; Host = host; SkipInitialization = skipInitialization; } public void Dispose() { // Cancel the creation of the process if it is in progress. // If it is the cancellation will clean up all resources allocated during the creation. _cancellationSource.Cancel(); // If the value has been calculated already, dispose the service. if (_lazyInitializedService.TryGetValue(out var initializedService)) { initializedService.Service?.Dispose(); } } internal Task<InitializedRemoteService> GetInitializedServiceAsync() => _lazyInitializedService.GetValueAsync(_cancellationSource.Token); internal InitializedRemoteService? TryGetInitializedService() => _lazyInitializedService.TryGetValue(out var service) ? service : default; private async Task<InitializedRemoteService> TryStartAndInitializeProcessAsync(CancellationToken cancellationToken) { try { var remoteService = await TryStartProcessAsync(Options.HostPath, Options.Culture, cancellationToken).ConfigureAwait(false); if (remoteService == null) { return default; } RemoteExecutionResult result; if (SkipInitialization) { result = new RemoteExecutionResult( success: true, sourcePaths: ImmutableArray<string>.Empty, referencePaths: ImmutableArray<string>.Empty, workingDirectory: Host._initialWorkingDirectory, initializationResult: new RemoteInitializationResult( initializationScript: null, metadataReferencePaths: ImmutableArray.Create(typeof(object).Assembly.Location, typeof(InteractiveScriptGlobals).Assembly.Location), imports: ImmutableArray<string>.Empty)); Host.ProcessInitialized?.Invoke(remoteService.PlatformInfo, Options, result); return new InitializedRemoteService(remoteService, result); } bool initializing = true; cancellationToken.Register(() => { if (initializing) { // kill the process without triggering auto-reset: remoteService.Dispose(); } }); // try to execute initialization script: var isRestarting = InstanceId > 1; result = await ExecuteRemoteAsync(remoteService, nameof(Service.InitializeContextAsync), Options.InitializationFilePath, isRestarting).ConfigureAwait(false); initializing = false; if (!result.Success) { Host.ReportProcessExited(remoteService.Process); remoteService.Dispose(); return default; } Contract.ThrowIfNull(result.InitializationResult); // Hook up a handler that initiates restart when the process exits. // Note that this is just so that we restart the process as soon as we see it dying and it doesn't need to be 100% bullet-proof. // If we don't receive the "process exited" event we will restart the process upon the next remote operation. remoteService.HookAutoRestartEvent(); Host.ProcessInitialized?.Invoke(remoteService.PlatformInfo, Options, result); return new InitializedRemoteService(remoteService, result); } #pragma warning disable CA2016 // Forward the 'CancellationToken' parameter to methods // await ExecuteRemoteAsync above does not take cancellationToken // - we don't currently support cancellation of the RPC call, // but JsonRpc.InvokeAsync that we use still claims it may throw OperationCanceledException.. catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e)) #pragma warning restore CA2016 { throw ExceptionUtilities.Unreachable; } } private async Task<RemoteService?> TryStartProcessAsync(string hostPath, CultureInfo culture, CancellationToken cancellationToken) { int currentProcessId = Process.GetCurrentProcess().Id; var pipeName = typeof(InteractiveHost).FullName + Guid.NewGuid(); var newProcess = new Process { StartInfo = new ProcessStartInfo(hostPath) { Arguments = pipeName + " " + currentProcessId, WorkingDirectory = Host._initialWorkingDirectory, CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, StandardErrorEncoding = OutputEncoding, StandardOutputEncoding = OutputEncoding }, // enables Process.Exited event to be raised: EnableRaisingEvents = true }; try { newProcess.Start(); } catch (Exception e) { Host.WriteOutputInBackground( isError: true, string.Format(InteractiveHostResources.Failed_to_create_a_remote_process_for_interactive_code_execution, hostPath), e.Message); Host.InteractiveHostProcessCreationFailed?.Invoke(e, TryGetExitCode(newProcess)); return null; } Host.InteractiveHostProcessCreated?.Invoke(newProcess); int newProcessId = -1; try { newProcessId = newProcess.Id; } catch { newProcessId = 0; } var clientStream = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous); JsonRpc? jsonRpc = null; void ProcessExitedBeforeEstablishingConnection(object sender, EventArgs e) { Host.InteractiveHostProcessCreationFailed?.Invoke(null, TryGetExitCode(newProcess)); _cancellationSource.Cancel(); } // Connecting the named pipe client would block if the process exits before the connection is established, // as the client waits for the server to become available. We signal the cancellation token to abort. newProcess.Exited += ProcessExitedBeforeEstablishingConnection; InteractiveHostPlatformInfo platformInfo; try { if (!CheckAlive(newProcess, hostPath)) { Host.InteractiveHostProcessCreationFailed?.Invoke(null, TryGetExitCode(newProcess)); return null; } await clientStream.ConnectAsync(cancellationToken).ConfigureAwait(false); jsonRpc = CreateRpc(clientStream, incomingCallTarget: null); platformInfo = (await jsonRpc.InvokeWithCancellationAsync<InteractiveHostPlatformInfo.Data>( nameof(Service.InitializeAsync), new object[] { Host._replServiceProviderType.AssemblyQualifiedName, culture.Name }, cancellationToken).ConfigureAwait(false)).Deserialize(); } catch (Exception e) { if (CheckAlive(newProcess, hostPath)) { RemoteService.InitiateTermination(newProcess, newProcessId); } jsonRpc?.Dispose(); Host.InteractiveHostProcessCreationFailed?.Invoke(e, TryGetExitCode(newProcess)); return null; } finally { newProcess.Exited -= ProcessExitedBeforeEstablishingConnection; } return new RemoteService(Host, newProcess, newProcessId, jsonRpc, platformInfo, Options); } private bool CheckAlive(Process process, string hostPath) { bool alive = process.IsAlive(); if (!alive) { string errorString = process.StandardError.ReadToEnd(); Host.WriteOutputInBackground( isError: true, string.Format(InteractiveHostResources.Failed_to_launch_0_process_exit_code_colon_1_with_output_colon, hostPath, process.ExitCode), errorString); } return alive; } private static int? TryGetExitCode(Process process) { try { return process.ExitCode; } catch { return null; } } } } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/InlineDeclaration/CSharpInlineDeclarationTests_FixAllTests.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 Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.InlineDeclaration { public partial class CSharpInlineDeclarationTests { [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task FixAllInDocument1() { await TestInRegularAndScriptAsync( @"class C { void M() { int {|FixAllInDocument:i|}, j; if (int.TryParse(v, out i, out j)) { } } }", @"class C { void M() { if (int.TryParse(v, out int i, out int j)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task FixAllInDocument2() { await TestInRegularAndScriptAsync( @"class C { void M() { {|FixAllInDocument:int|} i; if (int.TryParse(v, out i)) { } } void M1() { int i; if (int.TryParse(v, out i)) { } } }", @"class C { void M() { if (int.TryParse(v, out int i)) { } } void M1() { if (int.TryParse(v, out int i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task FixAllInDocument3() { await TestInRegularAndScriptAsync( @"class C { void M() { // Now get final exe and args. CTtrl-F5 wraps exe in cmd prompt string {|FixAllInDocument:finalExecutable|}, finalArguments; GetExeAndArguments(useCmdShell, executable, arguments, out finalExecutable, out finalArguments); } }", @"class C { void M() { // Now get final exe and args. CTtrl-F5 wraps exe in cmd prompt GetExeAndArguments(useCmdShell, executable, arguments, out string finalExecutable, out string finalArguments); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] [WorkItem(29935, "https://github.com/dotnet/roslyn/issues/29935")] public async Task FixAllInDocumentSymbolResolution() { await TestInRegularAndScriptAsync( @"class C { void M() { string {|FixAllInDocument:s|}; bool b; A(out s, out b); } void A(out string s, out bool b) { s = string.Empty; b = false; } void A(out string s, out string s2) { s = s2 = string.Empty; } }", @"class C { void M() { A(out string s, out bool b); } void A(out string s, out bool b) { s = string.Empty; b = false; } void A(out string s, out string s2) { s = s2 = string.Empty; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] [WorkItem(28323, "https://github.com/dotnet/roslyn/issues/28323")] public async Task FixAllInDocument4() { await TestInRegularAndScriptAsync( @"class C { void M() { int {|FixAllInDocument:i1|}; int i2; int.TryParse(v, out i1); int.TryParse(v, out i2); } }", @"class C { void M() { int.TryParse(v, out int i1); int.TryParse(v, out int i2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] [WorkItem(28323, "https://github.com/dotnet/roslyn/issues/28323")] public async Task FixAllInDocument5() { await TestInRegularAndScriptAsync( @"class C { void M() { int dummy; int {|FixAllInDocument:i1|}; int i2; int.TryParse(v, out i1); int.TryParse(v, out i2); dummy = 42; } }", @"class C { void M() { int dummy; int.TryParse(v, out int i1); int.TryParse(v, out int i2); dummy = 42; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] [WorkItem(28323, "https://github.com/dotnet/roslyn/issues/28323")] public async Task FixAllInDocument6() { await TestInRegularAndScriptAsync( @"class C { void M() { int {|FixAllInDocument:i1|}; int dummy; int i2; int.TryParse(v, out i1); int.TryParse(v, out i2); dummy = 42; } }", @"class C { void M() { int dummy; int.TryParse(v, out int i1); int.TryParse(v, out int i2); dummy = 42; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] [WorkItem(28323, "https://github.com/dotnet/roslyn/issues/28323")] public async Task FixAllInDocument7() { await TestInRegularAndScriptAsync( @"class C { void M() { int {|FixAllInDocument:i1|}; int i2; int dummy; int.TryParse(v, out i1); int.TryParse(v, out i2); dummy = 42; } }", @"class C { void M() { int dummy; int.TryParse(v, out int i1); int.TryParse(v, out int i2); dummy = 42; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task FixAllInDocument8() { await TestInRegularAndScriptAsync( @"class C { void M() { int dummy, {|FixAllInDocument:i1|}, i2; int.TryParse(v, out i1); int.TryParse(v, out i2); dummy = 42; } }", @"class C { void M() { int dummy; int.TryParse(v, out int i1); int.TryParse(v, out int i2); dummy = 42; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task FixAllInDocument9() { await TestInRegularAndScriptAsync( @"class C { void M() { int {|FixAllInDocument:i1|}, dummy, i2; int.TryParse(v, out i1); int.TryParse(v, out i2); dummy = 42; } }", @"class C { void M() { int dummy; int.TryParse(v, out int i1); int.TryParse(v, out int i2); dummy = 42; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task FixAllInDocument10() { await TestInRegularAndScriptAsync( @"class C { void M() { int {|FixAllInDocument:i1|}, i2, dummy; int.TryParse(v, out i1); int.TryParse(v, out i2); dummy = 42; } }", @"class C { void M() { int dummy; int.TryParse(v, out int i1); int.TryParse(v, out int i2); dummy = 42; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task FixAllInDocument11() { await TestInRegularAndScriptAsync( @"class C { void M() { int {|FixAllInDocument:i1|}, i2; int.TryParse(v, out i1); int.TryParse(v, out i2); } }", @"class C { void M() { int.TryParse(v, out int i1); int.TryParse(v, out int i2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] [WorkItem(28323, "https://github.com/dotnet/roslyn/issues/28323")] public async Task FixAllInDocumentComments1() { await TestInRegularAndScriptAsync( @"class C { void M() { /* leading */ int {|FixAllInDocument:i1|}; int i2; // trailing int.TryParse(v, out i1); int.TryParse(v, out i2); } }", @"class C { void M() { /* leading */ // trailing int.TryParse(v, out int i1); int.TryParse(v, out int i2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] [WorkItem(28323, "https://github.com/dotnet/roslyn/issues/28323")] public async Task FixAllInDocumentComments2() { await TestInRegularAndScriptAsync( @"class C { void M() { /* leading */ int dummy; /* in-between */ int {|FixAllInDocument:i1|}; int i2; // trailing int.TryParse(v, out i1); int.TryParse(v, out i2); dummy = 42; } }", @"class C { void M() { /* leading */ int dummy; /* in-between */ // trailing int.TryParse(v, out int i1); int.TryParse(v, out int i2); dummy = 42; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] [WorkItem(28323, "https://github.com/dotnet/roslyn/issues/28323")] public async Task FixAllInDocumentComments3() { await TestInRegularAndScriptAsync( @"class C { void M() { int {|FixAllInDocument:i1|}; /* 0 */int /* 1 */ dummy /* 2 */; /* 3*/ int i2; int.TryParse(v, out i1); int.TryParse(v, out i2); dummy = 42; } }", @"class C { void M() { /* 0 */ int /* 1 */ dummy /* 2 */; /* 3*/ int.TryParse(v, out int i1); int.TryParse(v, out int i2); dummy = 42; } }"); } } }
// Licensed to the .NET Foundation under one or more 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 Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.InlineDeclaration { public partial class CSharpInlineDeclarationTests { [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task FixAllInDocument1() { await TestInRegularAndScriptAsync( @"class C { void M() { int {|FixAllInDocument:i|}, j; if (int.TryParse(v, out i, out j)) { } } }", @"class C { void M() { if (int.TryParse(v, out int i, out int j)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task FixAllInDocument2() { await TestInRegularAndScriptAsync( @"class C { void M() { {|FixAllInDocument:int|} i; if (int.TryParse(v, out i)) { } } void M1() { int i; if (int.TryParse(v, out i)) { } } }", @"class C { void M() { if (int.TryParse(v, out int i)) { } } void M1() { if (int.TryParse(v, out int i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task FixAllInDocument3() { await TestInRegularAndScriptAsync( @"class C { void M() { // Now get final exe and args. CTtrl-F5 wraps exe in cmd prompt string {|FixAllInDocument:finalExecutable|}, finalArguments; GetExeAndArguments(useCmdShell, executable, arguments, out finalExecutable, out finalArguments); } }", @"class C { void M() { // Now get final exe and args. CTtrl-F5 wraps exe in cmd prompt GetExeAndArguments(useCmdShell, executable, arguments, out string finalExecutable, out string finalArguments); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] [WorkItem(29935, "https://github.com/dotnet/roslyn/issues/29935")] public async Task FixAllInDocumentSymbolResolution() { await TestInRegularAndScriptAsync( @"class C { void M() { string {|FixAllInDocument:s|}; bool b; A(out s, out b); } void A(out string s, out bool b) { s = string.Empty; b = false; } void A(out string s, out string s2) { s = s2 = string.Empty; } }", @"class C { void M() { A(out string s, out bool b); } void A(out string s, out bool b) { s = string.Empty; b = false; } void A(out string s, out string s2) { s = s2 = string.Empty; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] [WorkItem(28323, "https://github.com/dotnet/roslyn/issues/28323")] public async Task FixAllInDocument4() { await TestInRegularAndScriptAsync( @"class C { void M() { int {|FixAllInDocument:i1|}; int i2; int.TryParse(v, out i1); int.TryParse(v, out i2); } }", @"class C { void M() { int.TryParse(v, out int i1); int.TryParse(v, out int i2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] [WorkItem(28323, "https://github.com/dotnet/roslyn/issues/28323")] public async Task FixAllInDocument5() { await TestInRegularAndScriptAsync( @"class C { void M() { int dummy; int {|FixAllInDocument:i1|}; int i2; int.TryParse(v, out i1); int.TryParse(v, out i2); dummy = 42; } }", @"class C { void M() { int dummy; int.TryParse(v, out int i1); int.TryParse(v, out int i2); dummy = 42; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] [WorkItem(28323, "https://github.com/dotnet/roslyn/issues/28323")] public async Task FixAllInDocument6() { await TestInRegularAndScriptAsync( @"class C { void M() { int {|FixAllInDocument:i1|}; int dummy; int i2; int.TryParse(v, out i1); int.TryParse(v, out i2); dummy = 42; } }", @"class C { void M() { int dummy; int.TryParse(v, out int i1); int.TryParse(v, out int i2); dummy = 42; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] [WorkItem(28323, "https://github.com/dotnet/roslyn/issues/28323")] public async Task FixAllInDocument7() { await TestInRegularAndScriptAsync( @"class C { void M() { int {|FixAllInDocument:i1|}; int i2; int dummy; int.TryParse(v, out i1); int.TryParse(v, out i2); dummy = 42; } }", @"class C { void M() { int dummy; int.TryParse(v, out int i1); int.TryParse(v, out int i2); dummy = 42; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task FixAllInDocument8() { await TestInRegularAndScriptAsync( @"class C { void M() { int dummy, {|FixAllInDocument:i1|}, i2; int.TryParse(v, out i1); int.TryParse(v, out i2); dummy = 42; } }", @"class C { void M() { int dummy; int.TryParse(v, out int i1); int.TryParse(v, out int i2); dummy = 42; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task FixAllInDocument9() { await TestInRegularAndScriptAsync( @"class C { void M() { int {|FixAllInDocument:i1|}, dummy, i2; int.TryParse(v, out i1); int.TryParse(v, out i2); dummy = 42; } }", @"class C { void M() { int dummy; int.TryParse(v, out int i1); int.TryParse(v, out int i2); dummy = 42; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task FixAllInDocument10() { await TestInRegularAndScriptAsync( @"class C { void M() { int {|FixAllInDocument:i1|}, i2, dummy; int.TryParse(v, out i1); int.TryParse(v, out i2); dummy = 42; } }", @"class C { void M() { int dummy; int.TryParse(v, out int i1); int.TryParse(v, out int i2); dummy = 42; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task FixAllInDocument11() { await TestInRegularAndScriptAsync( @"class C { void M() { int {|FixAllInDocument:i1|}, i2; int.TryParse(v, out i1); int.TryParse(v, out i2); } }", @"class C { void M() { int.TryParse(v, out int i1); int.TryParse(v, out int i2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] [WorkItem(28323, "https://github.com/dotnet/roslyn/issues/28323")] public async Task FixAllInDocumentComments1() { await TestInRegularAndScriptAsync( @"class C { void M() { /* leading */ int {|FixAllInDocument:i1|}; int i2; // trailing int.TryParse(v, out i1); int.TryParse(v, out i2); } }", @"class C { void M() { /* leading */ // trailing int.TryParse(v, out int i1); int.TryParse(v, out int i2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] [WorkItem(28323, "https://github.com/dotnet/roslyn/issues/28323")] public async Task FixAllInDocumentComments2() { await TestInRegularAndScriptAsync( @"class C { void M() { /* leading */ int dummy; /* in-between */ int {|FixAllInDocument:i1|}; int i2; // trailing int.TryParse(v, out i1); int.TryParse(v, out i2); dummy = 42; } }", @"class C { void M() { /* leading */ int dummy; /* in-between */ // trailing int.TryParse(v, out int i1); int.TryParse(v, out int i2); dummy = 42; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] [WorkItem(28323, "https://github.com/dotnet/roslyn/issues/28323")] public async Task FixAllInDocumentComments3() { await TestInRegularAndScriptAsync( @"class C { void M() { int {|FixAllInDocument:i1|}; /* 0 */int /* 1 */ dummy /* 2 */; /* 3*/ int i2; int.TryParse(v, out i1); int.TryParse(v, out i2); dummy = 42; } }", @"class C { void M() { /* 0 */ int /* 1 */ dummy /* 2 */; /* 3*/ int.TryParse(v, out int i1); int.TryParse(v, out int i2); dummy = 42; } }"); } } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/CSharp/Impl/ProjectSystemShim/EntryPointFinder.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 Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim { internal class EntryPointFinder : AbstractEntryPointFinder { protected override bool MatchesMainMethodName(string name) => name == "Main"; public static IEnumerable<INamedTypeSymbol> FindEntryPoints(INamespaceSymbol symbol) { var visitor = new EntryPointFinder(); visitor.Visit(symbol); return visitor.EntryPoints; } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim { internal class EntryPointFinder : AbstractEntryPointFinder { protected override bool MatchesMainMethodName(string name) => name == "Main"; public static IEnumerable<INamedTypeSymbol> FindEntryPoints(INamespaceSymbol symbol) { var visitor = new EntryPointFinder(); visitor.Visit(symbol); return visitor.EntryPoints; } } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/VisualStudioMetadataAsSourceFileSupportService.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.CodeAnalysis.MetadataAsSource; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation { [Export(typeof(VisualStudioMetadataAsSourceFileSupportService))] internal sealed class VisualStudioMetadataAsSourceFileSupportService : IVsSolutionEvents { private readonly IMetadataAsSourceFileService _metadataAsSourceFileService; #pragma warning disable IDE0052 // Remove unread private members - Used to store the AdviseSolutionEvents cookie. private readonly uint _eventCookie; #pragma warning restore IDE0052 // Remove unread private members [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioMetadataAsSourceFileSupportService(SVsServiceProvider serviceProvider, IMetadataAsSourceFileService metadataAsSourceFileService) { _metadataAsSourceFileService = metadataAsSourceFileService; var solution = (IVsSolution)serviceProvider.GetService(typeof(SVsSolution)); ErrorHandler.ThrowOnFailure(solution.AdviseSolutionEvents(this, out _eventCookie)); } public int OnAfterCloseSolution(object pUnkReserved) { _metadataAsSourceFileService.CleanupGeneratedFiles(); return VSConstants.S_OK; } public int OnAfterLoadProject(IVsHierarchy pStubHierarchy, IVsHierarchy pRealHierarchy) => VSConstants.E_NOTIMPL; public int OnAfterOpenProject(IVsHierarchy pHierarchy, int fAdded) => VSConstants.E_NOTIMPL; public int OnAfterOpenSolution(object pUnkReserved, int fNewSolution) => VSConstants.E_NOTIMPL; public int OnBeforeCloseProject(IVsHierarchy pHierarchy, int fRemoved) => VSConstants.E_NOTIMPL; public int OnBeforeCloseSolution(object pUnkReserved) => VSConstants.E_NOTIMPL; public int OnBeforeUnloadProject(IVsHierarchy pRealHierarchy, IVsHierarchy pStubHierarchy) => VSConstants.E_NOTIMPL; public int OnQueryCloseProject(IVsHierarchy pHierarchy, int fRemoving, ref int pfCancel) => VSConstants.E_NOTIMPL; public int OnQueryCloseSolution(object pUnkReserved, ref int pfCancel) => VSConstants.E_NOTIMPL; public int OnQueryUnloadProject(IVsHierarchy pRealHierarchy, ref int pfCancel) => 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. #nullable disable using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation { [Export(typeof(VisualStudioMetadataAsSourceFileSupportService))] internal sealed class VisualStudioMetadataAsSourceFileSupportService : IVsSolutionEvents { private readonly IMetadataAsSourceFileService _metadataAsSourceFileService; #pragma warning disable IDE0052 // Remove unread private members - Used to store the AdviseSolutionEvents cookie. private readonly uint _eventCookie; #pragma warning restore IDE0052 // Remove unread private members [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioMetadataAsSourceFileSupportService(SVsServiceProvider serviceProvider, IMetadataAsSourceFileService metadataAsSourceFileService) { _metadataAsSourceFileService = metadataAsSourceFileService; var solution = (IVsSolution)serviceProvider.GetService(typeof(SVsSolution)); ErrorHandler.ThrowOnFailure(solution.AdviseSolutionEvents(this, out _eventCookie)); } public int OnAfterCloseSolution(object pUnkReserved) { _metadataAsSourceFileService.CleanupGeneratedFiles(); return VSConstants.S_OK; } public int OnAfterLoadProject(IVsHierarchy pStubHierarchy, IVsHierarchy pRealHierarchy) => VSConstants.E_NOTIMPL; public int OnAfterOpenProject(IVsHierarchy pHierarchy, int fAdded) => VSConstants.E_NOTIMPL; public int OnAfterOpenSolution(object pUnkReserved, int fNewSolution) => VSConstants.E_NOTIMPL; public int OnBeforeCloseProject(IVsHierarchy pHierarchy, int fRemoved) => VSConstants.E_NOTIMPL; public int OnBeforeCloseSolution(object pUnkReserved) => VSConstants.E_NOTIMPL; public int OnBeforeUnloadProject(IVsHierarchy pRealHierarchy, IVsHierarchy pStubHierarchy) => VSConstants.E_NOTIMPL; public int OnQueryCloseProject(IVsHierarchy pHierarchy, int fRemoving, ref int pfCancel) => VSConstants.E_NOTIMPL; public int OnQueryCloseSolution(object pUnkReserved, ref int pfCancel) => VSConstants.E_NOTIMPL; public int OnQueryUnloadProject(IVsHierarchy pRealHierarchy, ref int pfCancel) => VSConstants.E_NOTIMPL; } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/FindUsages/AbstractFindUsagesService.DefinitionTrackingContext.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 System.Threading.Tasks; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.Editor.FindUsages { internal abstract partial class AbstractFindUsagesService { /// <summary> /// Forwards <see cref="IFindUsagesContext"/> notifications to an underlying <see cref="IFindUsagesContext"/> /// while also keeping track of the <see cref="DefinitionItem"/> definitions reported. /// /// These can then be used by <see cref="GetThirdPartyDefinitions"/> to report the /// definitions found to third parties in case they want to add any additional definitions /// to the results we present. /// </summary> private class DefinitionTrackingContext : IFindUsagesContext { private readonly IFindUsagesContext _underlyingContext; private readonly object _gate = new(); private readonly List<DefinitionItem> _definitions = new(); public DefinitionTrackingContext(IFindUsagesContext underlyingContext) => _underlyingContext = underlyingContext; public IStreamingProgressTracker ProgressTracker => _underlyingContext.ProgressTracker; public ValueTask ReportMessageAsync(string message, CancellationToken cancellationToken) => _underlyingContext.ReportMessageAsync(message, cancellationToken); public ValueTask SetSearchTitleAsync(string title, CancellationToken cancellationToken) => _underlyingContext.SetSearchTitleAsync(title, cancellationToken); public ValueTask OnReferenceFoundAsync(SourceReferenceItem reference, CancellationToken cancellationToken) => _underlyingContext.OnReferenceFoundAsync(reference, cancellationToken); public ValueTask OnDefinitionFoundAsync(DefinitionItem definition, CancellationToken cancellationToken) { lock (_gate) { _definitions.Add(definition); } return _underlyingContext.OnDefinitionFoundAsync(definition, cancellationToken); } public ImmutableArray<DefinitionItem> GetDefinitions() { lock (_gate) { return _definitions.ToImmutableArray(); } } } } }
// Licensed to the .NET Foundation under one or more 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 System.Threading.Tasks; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.Editor.FindUsages { internal abstract partial class AbstractFindUsagesService { /// <summary> /// Forwards <see cref="IFindUsagesContext"/> notifications to an underlying <see cref="IFindUsagesContext"/> /// while also keeping track of the <see cref="DefinitionItem"/> definitions reported. /// /// These can then be used by <see cref="GetThirdPartyDefinitions"/> to report the /// definitions found to third parties in case they want to add any additional definitions /// to the results we present. /// </summary> private class DefinitionTrackingContext : IFindUsagesContext { private readonly IFindUsagesContext _underlyingContext; private readonly object _gate = new(); private readonly List<DefinitionItem> _definitions = new(); public DefinitionTrackingContext(IFindUsagesContext underlyingContext) => _underlyingContext = underlyingContext; public IStreamingProgressTracker ProgressTracker => _underlyingContext.ProgressTracker; public ValueTask ReportMessageAsync(string message, CancellationToken cancellationToken) => _underlyingContext.ReportMessageAsync(message, cancellationToken); public ValueTask SetSearchTitleAsync(string title, CancellationToken cancellationToken) => _underlyingContext.SetSearchTitleAsync(title, cancellationToken); public ValueTask OnReferenceFoundAsync(SourceReferenceItem reference, CancellationToken cancellationToken) => _underlyingContext.OnReferenceFoundAsync(reference, cancellationToken); public ValueTask OnDefinitionFoundAsync(DefinitionItem definition, CancellationToken cancellationToken) { lock (_gate) { _definitions.Add(definition); } return _underlyingContext.OnDefinitionFoundAsync(definition, cancellationToken); } public ImmutableArray<DefinitionItem> GetDefinitions() { lock (_gate) { return _definitions.ToImmutableArray(); } } } } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/CSharp/FixInterpolatedVerbatimString/FixInterpolatedVerbatimStringCommandHandler.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 System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.FixInterpolatedVerbatimString { /// <summary> /// Replaces <c>@$"</c> with <c>$@"</c>, which is the preferred and until C# 8.0 the only supported form /// of an interpolated verbatim string start token. In C# 8.0 we still auto-correct to this form for consistency. /// </summary> [Export(typeof(ICommandHandler))] [ContentType(ContentTypeNames.CSharpContentType)] [Name(nameof(FixInterpolatedVerbatimStringCommandHandler))] internal sealed class FixInterpolatedVerbatimStringCommandHandler : IChainedCommandHandler<TypeCharCommandArgs> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FixInterpolatedVerbatimStringCommandHandler() { } public string DisplayName => CSharpEditorResources.Fix_interpolated_verbatim_string; public void ExecuteCommand(TypeCharCommandArgs args, Action nextCommandHandler, CommandExecutionContext executionContext) { // We need to check for the token *after* the opening quote is typed, so defer to the editor first nextCommandHandler(); var cancellationToken = executionContext.OperationContext.UserCancellationToken; if (cancellationToken.IsCancellationRequested) { return; } try { ExecuteCommandWorker(args, cancellationToken); } catch (OperationCanceledException) { // According to Editor command handler API guidelines, it's best if we return early if cancellation // is requested instead of throwing. Otherwise, we could end up in an invalid state due to already // calling nextCommandHandler(). } } private static void ExecuteCommandWorker(TypeCharCommandArgs args, CancellationToken cancellationToken) { if (args.TypedChar == '"') { var caret = args.TextView.GetCaretPoint(args.SubjectBuffer); if (caret != null) { var position = caret.Value.Position; var snapshot = caret.Value.Snapshot; if (position >= 3 && snapshot[position - 1] == '"' && snapshot[position - 2] == '$' && snapshot[position - 3] == '@') { var document = snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null) { var root = document.GetSyntaxRootSynchronously(cancellationToken); var token = root.FindToken(position - 3); if (token.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken)) { args.SubjectBuffer.Replace(new Span(position - 3, 2), "$@"); } } } } } } public CommandState GetCommandState(TypeCharCommandArgs args, Func<CommandState> nextCommandHandler) => nextCommandHandler(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.FixInterpolatedVerbatimString { /// <summary> /// Replaces <c>@$"</c> with <c>$@"</c>, which is the preferred and until C# 8.0 the only supported form /// of an interpolated verbatim string start token. In C# 8.0 we still auto-correct to this form for consistency. /// </summary> [Export(typeof(ICommandHandler))] [ContentType(ContentTypeNames.CSharpContentType)] [Name(nameof(FixInterpolatedVerbatimStringCommandHandler))] internal sealed class FixInterpolatedVerbatimStringCommandHandler : IChainedCommandHandler<TypeCharCommandArgs> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FixInterpolatedVerbatimStringCommandHandler() { } public string DisplayName => CSharpEditorResources.Fix_interpolated_verbatim_string; public void ExecuteCommand(TypeCharCommandArgs args, Action nextCommandHandler, CommandExecutionContext executionContext) { // We need to check for the token *after* the opening quote is typed, so defer to the editor first nextCommandHandler(); var cancellationToken = executionContext.OperationContext.UserCancellationToken; if (cancellationToken.IsCancellationRequested) { return; } try { ExecuteCommandWorker(args, cancellationToken); } catch (OperationCanceledException) { // According to Editor command handler API guidelines, it's best if we return early if cancellation // is requested instead of throwing. Otherwise, we could end up in an invalid state due to already // calling nextCommandHandler(). } } private static void ExecuteCommandWorker(TypeCharCommandArgs args, CancellationToken cancellationToken) { if (args.TypedChar == '"') { var caret = args.TextView.GetCaretPoint(args.SubjectBuffer); if (caret != null) { var position = caret.Value.Position; var snapshot = caret.Value.Snapshot; if (position >= 3 && snapshot[position - 1] == '"' && snapshot[position - 2] == '$' && snapshot[position - 3] == '@') { var document = snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null) { var root = document.GetSyntaxRootSynchronously(cancellationToken); var token = root.FindToken(position - 3); if (token.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken)) { args.SubjectBuffer.Replace(new Span(position - 3, 2), "$@"); } } } } } } public CommandState GetCommandState(TypeCharCommandArgs args, Func<CommandState> nextCommandHandler) => nextCommandHandler(); } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/TrueKeywordRecommenderTests.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 Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class TrueKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(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 TestNotInPreprocessor1() { await VerifyAbsenceAsync( @"class C { #$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPreprocessor2() { await VerifyAbsenceAsync( @"class C { #line $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInExpression() { await VerifyKeywordAsync(AddInsideMethod( @"var q = $$")); } [WorkItem(542970, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542970")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPIf() { await VerifyKeywordAsync( @"#if $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPIf_Or() { await VerifyKeywordAsync( @"#if a || $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPIf_And() { await VerifyKeywordAsync( @"#if a && $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPIf_Not() { await VerifyKeywordAsync( @"#if ! $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPIf_Paren() { await VerifyKeywordAsync( @"#if ( $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPIf_Equals() { await VerifyKeywordAsync( @"#if a == $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPIf_NotEquals() { await VerifyKeywordAsync( @"#if a != $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPElIf() { await VerifyKeywordAsync( @"#if true #elif $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPelIf_Or() { await VerifyKeywordAsync( @"#if true #elif a || $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPElIf_And() { await VerifyKeywordAsync( @"#if true #elif a && $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPElIf_Not() { await VerifyKeywordAsync( @"#if true #elif ! $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPElIf_Paren() { await VerifyKeywordAsync( @"#if true #elif ( $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPElIf_Equals() { await VerifyKeywordAsync( @"#if true #elif a == $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPElIf_NotEquals() { await VerifyKeywordAsync( @"#if true #elif a != $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUnaryOperator() { await VerifyKeywordAsync( @"class C { public static bool operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterImplicitOperator() { await VerifyAbsenceAsync( @"class C { public static implicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterExplicitOperator() { await VerifyAbsenceAsync( @"class C { public static implicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestBeforeInactiveRegion() { await VerifyKeywordAsync( @"class C { void Init() { #if $$ H"); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterTypeOf() { await VerifyAbsenceAsync(AddInsideMethod( @"typeof($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDefault() { await VerifyAbsenceAsync(AddInsideMethod( @"default($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSizeOf() { await VerifyAbsenceAsync(AddInsideMethod( @"sizeof($$")); } [WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInObjectInitializerMemberContext() { await VerifyAbsenceAsync(@" class C { public int x, y; void M() { var c = new C { x = 2, y = 3, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefExpression() { await VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); } } }
// Licensed to the .NET Foundation under one or more 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 Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class TrueKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(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 TestNotInPreprocessor1() { await VerifyAbsenceAsync( @"class C { #$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPreprocessor2() { await VerifyAbsenceAsync( @"class C { #line $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInExpression() { await VerifyKeywordAsync(AddInsideMethod( @"var q = $$")); } [WorkItem(542970, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542970")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPIf() { await VerifyKeywordAsync( @"#if $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPIf_Or() { await VerifyKeywordAsync( @"#if a || $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPIf_And() { await VerifyKeywordAsync( @"#if a && $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPIf_Not() { await VerifyKeywordAsync( @"#if ! $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPIf_Paren() { await VerifyKeywordAsync( @"#if ( $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPIf_Equals() { await VerifyKeywordAsync( @"#if a == $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPIf_NotEquals() { await VerifyKeywordAsync( @"#if a != $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPElIf() { await VerifyKeywordAsync( @"#if true #elif $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPelIf_Or() { await VerifyKeywordAsync( @"#if true #elif a || $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPElIf_And() { await VerifyKeywordAsync( @"#if true #elif a && $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPElIf_Not() { await VerifyKeywordAsync( @"#if true #elif ! $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPElIf_Paren() { await VerifyKeywordAsync( @"#if true #elif ( $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPElIf_Equals() { await VerifyKeywordAsync( @"#if true #elif a == $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPElIf_NotEquals() { await VerifyKeywordAsync( @"#if true #elif a != $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUnaryOperator() { await VerifyKeywordAsync( @"class C { public static bool operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterImplicitOperator() { await VerifyAbsenceAsync( @"class C { public static implicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterExplicitOperator() { await VerifyAbsenceAsync( @"class C { public static implicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestBeforeInactiveRegion() { await VerifyKeywordAsync( @"class C { void Init() { #if $$ H"); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterTypeOf() { await VerifyAbsenceAsync(AddInsideMethod( @"typeof($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDefault() { await VerifyAbsenceAsync(AddInsideMethod( @"default($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSizeOf() { await VerifyAbsenceAsync(AddInsideMethod( @"sizeof($$")); } [WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInObjectInitializerMemberContext() { await VerifyAbsenceAsync(@" class C { public int x, y; void M() { var c = new C { x = 2, y = 3, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefExpression() { await VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); } } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/RuleSet/RuleSetInclude.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.IO; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a Include tag in a RuleSet file. /// </summary> public class RuleSetInclude { private readonly string _includePath; /// <summary> /// The path of the included file. /// </summary> public string IncludePath { get { return _includePath; } } private readonly ReportDiagnostic _action; /// <summary> /// The effective action to apply on this included ruleset. /// </summary> public ReportDiagnostic Action { get { return _action; } } /// <summary> /// Create a RuleSetInclude given the include path and the effective action. /// </summary> public RuleSetInclude(string includePath, ReportDiagnostic action) { _includePath = includePath; _action = action; } /// <summary> /// Gets the RuleSet associated with this ruleset include /// </summary> /// <param name="parent">The parent of this ruleset include</param> public RuleSet? LoadRuleSet(RuleSet parent) { // Try to load the rule set RuleSet? ruleSet = null; string? path = _includePath; try { path = GetIncludePath(parent); if (path == null) { return null; } ruleSet = RuleSetProcessor.LoadFromFile(path); } catch (FileNotFoundException) { // The compiler uses the same rule set files as FxCop, but doesn't have all of // the same logic for resolving included files. For the moment, just ignore any // includes we can't resolve. } catch (Exception e) { throw new InvalidRuleSetException(string.Format(CodeAnalysisResources.InvalidRuleSetInclude, path, e.Message)); } return ruleSet; } /// <summary> /// Returns a full path to the include file. Relative paths are expanded relative to the current rule set file. /// </summary> /// <param name="parent">The parent of this rule set include</param> private string? GetIncludePath(RuleSet parent) { var resolvedIncludePath = resolveIncludePath(_includePath, parent?.FilePath); if (resolvedIncludePath == null) { return null; } // Return the canonical full path return Path.GetFullPath(resolvedIncludePath); static string? resolveIncludePath(string includePath, string? parentRulesetPath) { var resolvedIncludePath = resolveIncludePathCore(includePath, parentRulesetPath); if (resolvedIncludePath == null && PathUtilities.IsUnixLikePlatform) { // Attempt to resolve legacy ruleset includes after replacing Windows style directory separator char with current plaform's directory separator char. includePath = includePath.Replace('\\', Path.DirectorySeparatorChar); resolvedIncludePath = resolveIncludePathCore(includePath, parentRulesetPath); } return resolvedIncludePath; } static string? resolveIncludePathCore(string includePath, string? parentRulesetPath) { includePath = Environment.ExpandEnvironmentVariables(includePath); // If a full path is specified then use it if (Path.IsPathRooted(includePath)) { if (File.Exists(includePath)) { return includePath; } } else if (!string.IsNullOrEmpty(parentRulesetPath)) { // Otherwise, try to find the include file relative to the parent ruleset. includePath = PathUtilities.CombinePathsUnchecked(Path.GetDirectoryName(parentRulesetPath) ?? "", includePath); if (File.Exists(includePath)) { return includePath; } } return null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a Include tag in a RuleSet file. /// </summary> public class RuleSetInclude { private readonly string _includePath; /// <summary> /// The path of the included file. /// </summary> public string IncludePath { get { return _includePath; } } private readonly ReportDiagnostic _action; /// <summary> /// The effective action to apply on this included ruleset. /// </summary> public ReportDiagnostic Action { get { return _action; } } /// <summary> /// Create a RuleSetInclude given the include path and the effective action. /// </summary> public RuleSetInclude(string includePath, ReportDiagnostic action) { _includePath = includePath; _action = action; } /// <summary> /// Gets the RuleSet associated with this ruleset include /// </summary> /// <param name="parent">The parent of this ruleset include</param> public RuleSet? LoadRuleSet(RuleSet parent) { // Try to load the rule set RuleSet? ruleSet = null; string? path = _includePath; try { path = GetIncludePath(parent); if (path == null) { return null; } ruleSet = RuleSetProcessor.LoadFromFile(path); } catch (FileNotFoundException) { // The compiler uses the same rule set files as FxCop, but doesn't have all of // the same logic for resolving included files. For the moment, just ignore any // includes we can't resolve. } catch (Exception e) { throw new InvalidRuleSetException(string.Format(CodeAnalysisResources.InvalidRuleSetInclude, path, e.Message)); } return ruleSet; } /// <summary> /// Returns a full path to the include file. Relative paths are expanded relative to the current rule set file. /// </summary> /// <param name="parent">The parent of this rule set include</param> private string? GetIncludePath(RuleSet parent) { var resolvedIncludePath = resolveIncludePath(_includePath, parent?.FilePath); if (resolvedIncludePath == null) { return null; } // Return the canonical full path return Path.GetFullPath(resolvedIncludePath); static string? resolveIncludePath(string includePath, string? parentRulesetPath) { var resolvedIncludePath = resolveIncludePathCore(includePath, parentRulesetPath); if (resolvedIncludePath == null && PathUtilities.IsUnixLikePlatform) { // Attempt to resolve legacy ruleset includes after replacing Windows style directory separator char with current plaform's directory separator char. includePath = includePath.Replace('\\', Path.DirectorySeparatorChar); resolvedIncludePath = resolveIncludePathCore(includePath, parentRulesetPath); } return resolvedIncludePath; } static string? resolveIncludePathCore(string includePath, string? parentRulesetPath) { includePath = Environment.ExpandEnvironmentVariables(includePath); // If a full path is specified then use it if (Path.IsPathRooted(includePath)) { if (File.Exists(includePath)) { return includePath; } } else if (!string.IsNullOrEmpty(parentRulesetPath)) { // Otherwise, try to find the include file relative to the parent ruleset. includePath = PathUtilities.CombinePathsUnchecked(Path.GetDirectoryName(parentRulesetPath) ?? "", includePath); if (File.Exists(includePath)) { return includePath; } } return null; } } } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/PEWriter/MethodSpecComparer.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.CodeAnalysis; using Roslyn.Utilities; namespace Microsoft.Cci { internal sealed class MethodSpecComparer : IEqualityComparer<IGenericMethodInstanceReference> { private readonly MetadataWriter _metadataWriter; internal MethodSpecComparer(MetadataWriter metadataWriter) { _metadataWriter = metadataWriter; } public bool Equals(IGenericMethodInstanceReference? x, IGenericMethodInstanceReference? y) { if (x == y) { return true; } RoslynDebug.Assert(x is object && y is object); return _metadataWriter.GetMethodDefinitionOrReferenceHandle(x.GetGenericMethod(_metadataWriter.Context)) == _metadataWriter.GetMethodDefinitionOrReferenceHandle(y.GetGenericMethod(_metadataWriter.Context)) && _metadataWriter.GetMethodSpecificationSignatureHandle(x) == _metadataWriter.GetMethodSpecificationSignatureHandle(y); } public int GetHashCode(IGenericMethodInstanceReference methodInstanceReference) { return Hash.Combine( _metadataWriter.GetMethodDefinitionOrReferenceHandle(methodInstanceReference.GetGenericMethod(_metadataWriter.Context)).GetHashCode(), _metadataWriter.GetMethodSpecificationSignatureHandle(methodInstanceReference).GetHashCode()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Roslyn.Utilities; namespace Microsoft.Cci { internal sealed class MethodSpecComparer : IEqualityComparer<IGenericMethodInstanceReference> { private readonly MetadataWriter _metadataWriter; internal MethodSpecComparer(MetadataWriter metadataWriter) { _metadataWriter = metadataWriter; } public bool Equals(IGenericMethodInstanceReference? x, IGenericMethodInstanceReference? y) { if (x == y) { return true; } RoslynDebug.Assert(x is object && y is object); return _metadataWriter.GetMethodDefinitionOrReferenceHandle(x.GetGenericMethod(_metadataWriter.Context)) == _metadataWriter.GetMethodDefinitionOrReferenceHandle(y.GetGenericMethod(_metadataWriter.Context)) && _metadataWriter.GetMethodSpecificationSignatureHandle(x) == _metadataWriter.GetMethodSpecificationSignatureHandle(y); } public int GetHashCode(IGenericMethodInstanceReference methodInstanceReference) { return Hash.Combine( _metadataWriter.GetMethodDefinitionOrReferenceHandle(methodInstanceReference.GetGenericMethod(_metadataWriter.Context)).GetHashCode(), _metadataWriter.GetMethodSpecificationSignatureHandle(methodInstanceReference).GetHashCode()); } } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/Completion/CompletionProviders/DeclarationNameCompletionProvider.DeclarationInfo.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; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { internal partial class DeclarationNameCompletionProvider { internal struct NameDeclarationInfo { private static readonly ImmutableArray<SymbolKindOrTypeKind> s_parameterSyntaxKind = ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Parameter)); private static readonly ImmutableArray<SymbolKindOrTypeKind> s_propertySyntaxKind = ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Property)); public NameDeclarationInfo( ImmutableArray<SymbolKindOrTypeKind> possibleSymbolKinds, Accessibility? accessibility, DeclarationModifiers declarationModifiers, ITypeSymbol type, IAliasSymbol alias) { PossibleSymbolKinds = possibleSymbolKinds; DeclaredAccessibility = accessibility; Modifiers = declarationModifiers; Type = type; Alias = alias; } public ImmutableArray<SymbolKindOrTypeKind> PossibleSymbolKinds { get; } public DeclarationModifiers Modifiers { get; } public ITypeSymbol Type { get; } public IAliasSymbol Alias { get; } public Accessibility? DeclaredAccessibility { get; } internal static async Task<NameDeclarationInfo> GetDeclarationInfoAsync(Document document, int position, CancellationToken cancellationToken) { var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var token = tree.FindTokenOnLeftOfPosition(position, cancellationToken).GetPreviousTokenIfTouchingWord(position); var semanticModel = await document.ReuseExistingSpeculativeModelAsync(token.SpanStart, cancellationToken).ConfigureAwait(false); var typeInferenceService = document.GetLanguageService<ITypeInferenceService>(); if (IsTupleTypeElement(token, semanticModel, cancellationToken, out var result) || IsPrimaryConstructorParameter(token, semanticModel, cancellationToken, out result) || IsParameterDeclaration(token, semanticModel, cancellationToken, out result) || IsTypeParameterDeclaration(token, out result) || IsLocalFunctionDeclaration(token, semanticModel, cancellationToken, out result) || IsLocalVariableDeclaration(token, semanticModel, cancellationToken, out result) || IsEmbeddedVariableDeclaration(token, semanticModel, cancellationToken, out result) || IsForEachVariableDeclaration(token, semanticModel, cancellationToken, out result) || IsIncompleteMemberDeclaration(token, semanticModel, cancellationToken, out result) || IsFieldDeclaration(token, semanticModel, cancellationToken, out result) || IsMethodDeclaration(token, semanticModel, cancellationToken, out result) || IsPropertyDeclaration(token, semanticModel, cancellationToken, out result) || IsPossibleOutVariableDeclaration(token, semanticModel, typeInferenceService, cancellationToken, out result) || IsTupleLiteralElement(token, semanticModel, cancellationToken, out result) || IsPossibleVariableOrLocalMethodDeclaration(token, semanticModel, cancellationToken, out result) || IsPatternMatching(token, semanticModel, cancellationToken, out result)) { return result; } return default; } private static bool IsTupleTypeElement( SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken, out NameDeclarationInfo result) { result = IsFollowingTypeOrComma<TupleElementSyntax>( token, semanticModel, tupleElement => tupleElement.Type, _ => default(SyntaxTokenList), _ => ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Local)), cancellationToken); return result.Type != null; } private static bool IsTupleLiteralElement( SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken, out NameDeclarationInfo result) { // Incomplete code like // void Do() // { // (System.Array array, System.Action $$ // gets parsed as a tuple expression. We can figure out the type in such cases. // For a legit tuple expression we can't provide any completion. if (token.GetAncestor(node => node.IsKind(SyntaxKind.TupleExpression)) != null) { result = IsFollowingTypeOrComma<ArgumentSyntax>( token, semanticModel, GetNodeDenotingTheTypeOfTupleArgument, _ => default(SyntaxTokenList), _ => ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Local)), cancellationToken); return result.Type != null; } result = default; return false; } private static bool IsPossibleOutVariableDeclaration(SyntaxToken token, SemanticModel semanticModel, ITypeInferenceService typeInferenceService, CancellationToken cancellationToken, out NameDeclarationInfo result) { if (!token.IsKind(SyntaxKind.IdentifierToken) || !token.Parent.IsKind(SyntaxKind.IdentifierName)) { result = default; return false; } var argument = token.Parent.Parent as ArgumentSyntax // var is child of ArgumentSyntax, eg. Goo(out var $$ ?? token.Parent.Parent.Parent as ArgumentSyntax; // var is child of DeclarationExpression // under ArgumentSyntax, eg. Goo(out var a$$ if (argument == null || !argument.RefOrOutKeyword.IsKind(SyntaxKind.OutKeyword)) { result = default; return false; } var type = typeInferenceService.InferType(semanticModel, argument.SpanStart, objectAsDefault: false, cancellationToken: cancellationToken); if (type != null) { result = new NameDeclarationInfo( ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Local)), Accessibility.NotApplicable, new DeclarationModifiers(), type, alias: null); return true; } result = default; return false; } private static bool IsPossibleVariableOrLocalMethodDeclaration( SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken, out NameDeclarationInfo result) { result = IsLastTokenOfType<ExpressionStatementSyntax>( token, semanticModel, e => e.Expression, _ => default, _ => ImmutableArray.Create( new SymbolKindOrTypeKind(SymbolKind.Local), new SymbolKindOrTypeKind(MethodKind.LocalFunction)), cancellationToken); return result.Type != null; } private static bool IsPropertyDeclaration(SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken, out NameDeclarationInfo result) { result = IsLastTokenOfType<PropertyDeclarationSyntax>( token, semanticModel, m => m.Type, m => m.Modifiers, GetPossibleMemberDeclarations, cancellationToken); return result.Type != null; } private static bool IsMethodDeclaration(SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken, out NameDeclarationInfo result) { result = IsLastTokenOfType<MethodDeclarationSyntax>( token, semanticModel, m => m.ReturnType, m => m.Modifiers, GetPossibleMemberDeclarations, cancellationToken); return result.Type != null; } private static NameDeclarationInfo IsFollowingTypeOrComma<TSyntaxNode>(SyntaxToken token, SemanticModel semanticModel, Func<TSyntaxNode, SyntaxNode> typeSyntaxGetter, Func<TSyntaxNode, SyntaxTokenList?> modifierGetter, Func<DeclarationModifiers, ImmutableArray<SymbolKindOrTypeKind>> possibleDeclarationComputer, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode { if (!IsPossibleTypeToken(token) && !token.IsKind(SyntaxKind.CommaToken)) { return default; } var target = token.GetAncestor<TSyntaxNode>(); if (target == null) { return default; } if (token.IsKind(SyntaxKind.CommaToken) && token.Parent != target) { return default; } var typeSyntax = typeSyntaxGetter(target); if (typeSyntax == null) { return default; } if (!token.IsKind(SyntaxKind.CommaToken) && token != typeSyntax.GetLastToken()) { return default; } var modifiers = modifierGetter(target); if (modifiers == null) { return default; } var alias = semanticModel.GetAliasInfo(typeSyntax, cancellationToken); var type = semanticModel.GetTypeInfo(typeSyntax, cancellationToken).Type; return new NameDeclarationInfo( possibleDeclarationComputer(GetDeclarationModifiers(modifiers.Value)), GetAccessibility(modifiers.Value), GetDeclarationModifiers(modifiers.Value), type, alias); } private static NameDeclarationInfo IsLastTokenOfType<TSyntaxNode>( SyntaxToken token, SemanticModel semanticModel, Func<TSyntaxNode, SyntaxNode> typeSyntaxGetter, Func<TSyntaxNode, SyntaxTokenList> modifierGetter, Func<DeclarationModifiers, ImmutableArray<SymbolKindOrTypeKind>> possibleDeclarationComputer, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode { if (!IsPossibleTypeToken(token)) { return default; } var target = token.GetAncestor<TSyntaxNode>(); if (target == null) { return default; } var typeSyntax = typeSyntaxGetter(target); if (typeSyntax == null || token != typeSyntax.GetLastToken()) { return default; } var modifiers = modifierGetter(target); return new NameDeclarationInfo( possibleDeclarationComputer(GetDeclarationModifiers(modifiers)), GetAccessibility(modifiers), GetDeclarationModifiers(modifiers), semanticModel.GetTypeInfo(typeSyntax, cancellationToken).Type, semanticModel.GetAliasInfo(typeSyntax, cancellationToken)); } private static bool IsFieldDeclaration(SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken, out NameDeclarationInfo result) { result = IsFollowingTypeOrComma<VariableDeclarationSyntax>(token, semanticModel, v => v.Type, v => v.Parent is FieldDeclarationSyntax f ? f.Modifiers : (SyntaxTokenList?)null, GetPossibleMemberDeclarations, cancellationToken); return result.Type != null; } private static bool IsIncompleteMemberDeclaration(SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken, out NameDeclarationInfo result) { result = IsLastTokenOfType<IncompleteMemberSyntax>(token, semanticModel, i => i.Type, i => i.Modifiers, GetPossibleMemberDeclarations, cancellationToken); return result.Type != null; } private static bool IsLocalFunctionDeclaration(SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken, out NameDeclarationInfo result) { result = IsLastTokenOfType<LocalFunctionStatementSyntax>(token, semanticModel, typeSyntaxGetter: f => f.ReturnType, modifierGetter: f => f.Modifiers, possibleDeclarationComputer: GetPossibleLocalDeclarations, cancellationToken); return result.Type != null; } private static bool IsLocalVariableDeclaration(SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken, out NameDeclarationInfo result) { // If we only have a type, this can still end up being a local function (depending on the modifiers). var possibleDeclarationComputer = token.IsKind(SyntaxKind.CommaToken) ? (Func<DeclarationModifiers, ImmutableArray<SymbolKindOrTypeKind>>) (_ => ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Local))) : GetPossibleLocalDeclarations; result = IsFollowingTypeOrComma<VariableDeclarationSyntax>(token, semanticModel, typeSyntaxGetter: v => v.Type, modifierGetter: v => v.Parent is LocalDeclarationStatementSyntax localDeclaration ? localDeclaration.Modifiers : (SyntaxTokenList?)null, // Return null to bail out. possibleDeclarationComputer, cancellationToken); if (result.Type != null) { return true; } // If the type has a trailing question mark, we may parse it as a conditional access expression. // We will use the condition as the type to bind; we won't make the type we bind nullable // because we ignore nullability when generating names anyways if (token.IsKind(SyntaxKind.QuestionToken) && token.Parent is ConditionalExpressionSyntax conditionalExpressionSyntax) { var symbolInfo = semanticModel.GetSymbolInfo(conditionalExpressionSyntax.Condition); if (symbolInfo.GetAnySymbol() is ITypeSymbol type) { var alias = semanticModel.GetAliasInfo(conditionalExpressionSyntax.Condition, cancellationToken); result = new NameDeclarationInfo( possibleDeclarationComputer(default), accessibility: null, declarationModifiers: default, type, alias); return true; } } return false; } private static bool IsEmbeddedVariableDeclaration(SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken, out NameDeclarationInfo result) { result = IsFollowingTypeOrComma<VariableDeclarationSyntax>(token, semanticModel, typeSyntaxGetter: v => v.Type, modifierGetter: v => v.Parent is UsingStatementSyntax || v.Parent is ForStatementSyntax ? default(SyntaxTokenList) : (SyntaxTokenList?)null, // Return null to bail out. possibleDeclarationComputer: d => ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Local)), cancellationToken); return result.Type != null; } private static bool IsForEachVariableDeclaration(SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken, out NameDeclarationInfo result) { // This is parsed as ForEachVariableStatementSyntax: // foreach (int $$ result = IsLastTokenOfType<CommonForEachStatementSyntax>(token, semanticModel, typeSyntaxGetter: f => f is ForEachStatementSyntax forEachStatement ? forEachStatement.Type : f is ForEachVariableStatementSyntax forEachVariableStatement ? forEachVariableStatement.Variable : null, // Return null to bail out. modifierGetter: f => default, possibleDeclarationComputer: d => ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Local)), cancellationToken); return result.Type != null; } private static bool IsTypeParameterDeclaration(SyntaxToken token, out NameDeclarationInfo result) { if (token.IsKind(SyntaxKind.LessThanToken, SyntaxKind.CommaToken) && token.Parent.IsKind(SyntaxKind.TypeParameterList)) { result = new NameDeclarationInfo( ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.TypeParameter)), Accessibility.NotApplicable, new DeclarationModifiers(), type: null, alias: null); return true; } result = default; return false; } private static bool IsPrimaryConstructorParameter(SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken, out NameDeclarationInfo result) { result = IsLastTokenOfType<ParameterSyntax>( token, semanticModel, p => p.Type, _ => default, _ => s_propertySyntaxKind, cancellationToken); if (result.Type != null && token.GetAncestor<ParameterSyntax>().Parent.IsParentKind(SyntaxKind.RecordDeclaration, SyntaxKind.RecordStructDeclaration)) { return true; } result = default; return false; } private static bool IsParameterDeclaration(SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken, out NameDeclarationInfo result) { result = IsLastTokenOfType<ParameterSyntax>( token, semanticModel, p => p.Type, _ => default, _ => s_parameterSyntaxKind, cancellationToken); return result.Type != null; } private static bool IsPatternMatching(SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken, out NameDeclarationInfo result) { result = default; if (token.Parent.IsParentKind(SyntaxKind.IsExpression)) { result = IsLastTokenOfType<BinaryExpressionSyntax>( token, semanticModel, b => b.Right, _ => default, _ => s_parameterSyntaxKind, cancellationToken); } else if (token.Parent.IsParentKind(SyntaxKind.CaseSwitchLabel)) { result = IsLastTokenOfType<CaseSwitchLabelSyntax>( token, semanticModel, b => b.Value, _ => default, _ => s_parameterSyntaxKind, cancellationToken); } else if (token.Parent.IsParentKind(SyntaxKind.DeclarationPattern)) { result = IsLastTokenOfType<DeclarationPatternSyntax>( token, semanticModel, b => b.Type, _ => default, _ => s_parameterSyntaxKind, cancellationToken); } return result.Type != null; } private static bool IsPossibleTypeToken(SyntaxToken token) => token.IsKind( SyntaxKind.IdentifierToken, SyntaxKind.GreaterThanToken, SyntaxKind.CloseBracketToken, SyntaxKind.QuestionToken) || token.Parent.IsKind(SyntaxKind.PredefinedType); private static ImmutableArray<SymbolKindOrTypeKind> GetPossibleMemberDeclarations(DeclarationModifiers modifiers) { if (modifiers.IsConst || modifiers.IsReadOnly) { return ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Field)); } var possibleTypes = ImmutableArray.Create( new SymbolKindOrTypeKind(SymbolKind.Field), new SymbolKindOrTypeKind(SymbolKind.Property), new SymbolKindOrTypeKind(MethodKind.Ordinary)); if (modifiers.IsAbstract || modifiers.IsVirtual || modifiers.IsSealed || modifiers.IsOverride) { possibleTypes = possibleTypes.Remove(new SymbolKindOrTypeKind(SymbolKind.Field)); } if (modifiers.IsAsync || modifiers.IsPartial) { // Fields and properties cannot be async or partial. possibleTypes = possibleTypes.Remove(new SymbolKindOrTypeKind(SymbolKind.Field)); possibleTypes = possibleTypes.Remove(new SymbolKindOrTypeKind(SymbolKind.Property)); } return possibleTypes; } private static ImmutableArray<SymbolKindOrTypeKind> GetPossibleLocalDeclarations(DeclarationModifiers modifiers) { return modifiers.IsConst ? ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Local)) : modifiers.IsAsync || modifiers.IsUnsafe ? ImmutableArray.Create(new SymbolKindOrTypeKind(MethodKind.LocalFunction)) : ImmutableArray.Create( new SymbolKindOrTypeKind(SymbolKind.Local), new SymbolKindOrTypeKind(MethodKind.LocalFunction)); } private static DeclarationModifiers GetDeclarationModifiers(SyntaxTokenList modifiers) { var declarationModifiers = new DeclarationModifiers(); foreach (var modifer in modifiers) { switch (modifer.Kind()) { case SyntaxKind.StaticKeyword: declarationModifiers = declarationModifiers.WithIsStatic(true); continue; case SyntaxKind.AbstractKeyword: declarationModifiers = declarationModifiers.WithIsAbstract(true); continue; case SyntaxKind.NewKeyword: declarationModifiers = declarationModifiers.WithIsNew(true); continue; case SyntaxKind.UnsafeKeyword: declarationModifiers = declarationModifiers.WithIsUnsafe(true); continue; case SyntaxKind.ReadOnlyKeyword: declarationModifiers = declarationModifiers.WithIsReadOnly(true); continue; case SyntaxKind.VirtualKeyword: declarationModifiers = declarationModifiers.WithIsVirtual(true); continue; case SyntaxKind.OverrideKeyword: declarationModifiers = declarationModifiers.WithIsOverride(true); continue; case SyntaxKind.SealedKeyword: declarationModifiers = declarationModifiers.WithIsSealed(true); continue; case SyntaxKind.ConstKeyword: declarationModifiers = declarationModifiers.WithIsConst(true); continue; case SyntaxKind.AsyncKeyword: declarationModifiers = declarationModifiers.WithAsync(true); continue; case SyntaxKind.PartialKeyword: declarationModifiers = declarationModifiers.WithPartial(true); continue; } } return declarationModifiers; } private static Accessibility? GetAccessibility(SyntaxTokenList modifiers) { for (var i = modifiers.Count - 1; i >= 0; i--) { var modifier = modifiers[i]; switch (modifier.Kind()) { case SyntaxKind.PrivateKeyword: return Accessibility.Private; case SyntaxKind.PublicKeyword: return Accessibility.Public; case SyntaxKind.ProtectedKeyword: return Accessibility.Protected; case SyntaxKind.InternalKeyword: return Accessibility.Internal; } } return null; } private static SyntaxNode GetNodeDenotingTheTypeOfTupleArgument(ArgumentSyntax argumentSyntax) { switch (argumentSyntax.Expression?.Kind()) { case SyntaxKind.DeclarationExpression: // The parser found a declaration as in (System.Action action, System.Array a$$) // we need the type part of the declaration expression. return ((DeclarationExpressionSyntax)argumentSyntax.Expression).Type; default: // We assume the parser found something that represents something named, // e.g. a MemberAccessExpression as in (System.Action action, System.Array $$) // We also assume that this name could be resolved to a type. return argumentSyntax.Expression; } } } } }
// Licensed to the .NET Foundation under one or more 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; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { internal partial class DeclarationNameCompletionProvider { internal struct NameDeclarationInfo { private static readonly ImmutableArray<SymbolKindOrTypeKind> s_parameterSyntaxKind = ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Parameter)); private static readonly ImmutableArray<SymbolKindOrTypeKind> s_propertySyntaxKind = ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Property)); public NameDeclarationInfo( ImmutableArray<SymbolKindOrTypeKind> possibleSymbolKinds, Accessibility? accessibility, DeclarationModifiers declarationModifiers, ITypeSymbol type, IAliasSymbol alias) { PossibleSymbolKinds = possibleSymbolKinds; DeclaredAccessibility = accessibility; Modifiers = declarationModifiers; Type = type; Alias = alias; } public ImmutableArray<SymbolKindOrTypeKind> PossibleSymbolKinds { get; } public DeclarationModifiers Modifiers { get; } public ITypeSymbol Type { get; } public IAliasSymbol Alias { get; } public Accessibility? DeclaredAccessibility { get; } internal static async Task<NameDeclarationInfo> GetDeclarationInfoAsync(Document document, int position, CancellationToken cancellationToken) { var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var token = tree.FindTokenOnLeftOfPosition(position, cancellationToken).GetPreviousTokenIfTouchingWord(position); var semanticModel = await document.ReuseExistingSpeculativeModelAsync(token.SpanStart, cancellationToken).ConfigureAwait(false); var typeInferenceService = document.GetLanguageService<ITypeInferenceService>(); if (IsTupleTypeElement(token, semanticModel, cancellationToken, out var result) || IsPrimaryConstructorParameter(token, semanticModel, cancellationToken, out result) || IsParameterDeclaration(token, semanticModel, cancellationToken, out result) || IsTypeParameterDeclaration(token, out result) || IsLocalFunctionDeclaration(token, semanticModel, cancellationToken, out result) || IsLocalVariableDeclaration(token, semanticModel, cancellationToken, out result) || IsEmbeddedVariableDeclaration(token, semanticModel, cancellationToken, out result) || IsForEachVariableDeclaration(token, semanticModel, cancellationToken, out result) || IsIncompleteMemberDeclaration(token, semanticModel, cancellationToken, out result) || IsFieldDeclaration(token, semanticModel, cancellationToken, out result) || IsMethodDeclaration(token, semanticModel, cancellationToken, out result) || IsPropertyDeclaration(token, semanticModel, cancellationToken, out result) || IsPossibleOutVariableDeclaration(token, semanticModel, typeInferenceService, cancellationToken, out result) || IsTupleLiteralElement(token, semanticModel, cancellationToken, out result) || IsPossibleVariableOrLocalMethodDeclaration(token, semanticModel, cancellationToken, out result) || IsPatternMatching(token, semanticModel, cancellationToken, out result)) { return result; } return default; } private static bool IsTupleTypeElement( SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken, out NameDeclarationInfo result) { result = IsFollowingTypeOrComma<TupleElementSyntax>( token, semanticModel, tupleElement => tupleElement.Type, _ => default(SyntaxTokenList), _ => ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Local)), cancellationToken); return result.Type != null; } private static bool IsTupleLiteralElement( SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken, out NameDeclarationInfo result) { // Incomplete code like // void Do() // { // (System.Array array, System.Action $$ // gets parsed as a tuple expression. We can figure out the type in such cases. // For a legit tuple expression we can't provide any completion. if (token.GetAncestor(node => node.IsKind(SyntaxKind.TupleExpression)) != null) { result = IsFollowingTypeOrComma<ArgumentSyntax>( token, semanticModel, GetNodeDenotingTheTypeOfTupleArgument, _ => default(SyntaxTokenList), _ => ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Local)), cancellationToken); return result.Type != null; } result = default; return false; } private static bool IsPossibleOutVariableDeclaration(SyntaxToken token, SemanticModel semanticModel, ITypeInferenceService typeInferenceService, CancellationToken cancellationToken, out NameDeclarationInfo result) { if (!token.IsKind(SyntaxKind.IdentifierToken) || !token.Parent.IsKind(SyntaxKind.IdentifierName)) { result = default; return false; } var argument = token.Parent.Parent as ArgumentSyntax // var is child of ArgumentSyntax, eg. Goo(out var $$ ?? token.Parent.Parent.Parent as ArgumentSyntax; // var is child of DeclarationExpression // under ArgumentSyntax, eg. Goo(out var a$$ if (argument == null || !argument.RefOrOutKeyword.IsKind(SyntaxKind.OutKeyword)) { result = default; return false; } var type = typeInferenceService.InferType(semanticModel, argument.SpanStart, objectAsDefault: false, cancellationToken: cancellationToken); if (type != null) { result = new NameDeclarationInfo( ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Local)), Accessibility.NotApplicable, new DeclarationModifiers(), type, alias: null); return true; } result = default; return false; } private static bool IsPossibleVariableOrLocalMethodDeclaration( SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken, out NameDeclarationInfo result) { result = IsLastTokenOfType<ExpressionStatementSyntax>( token, semanticModel, e => e.Expression, _ => default, _ => ImmutableArray.Create( new SymbolKindOrTypeKind(SymbolKind.Local), new SymbolKindOrTypeKind(MethodKind.LocalFunction)), cancellationToken); return result.Type != null; } private static bool IsPropertyDeclaration(SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken, out NameDeclarationInfo result) { result = IsLastTokenOfType<PropertyDeclarationSyntax>( token, semanticModel, m => m.Type, m => m.Modifiers, GetPossibleMemberDeclarations, cancellationToken); return result.Type != null; } private static bool IsMethodDeclaration(SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken, out NameDeclarationInfo result) { result = IsLastTokenOfType<MethodDeclarationSyntax>( token, semanticModel, m => m.ReturnType, m => m.Modifiers, GetPossibleMemberDeclarations, cancellationToken); return result.Type != null; } private static NameDeclarationInfo IsFollowingTypeOrComma<TSyntaxNode>(SyntaxToken token, SemanticModel semanticModel, Func<TSyntaxNode, SyntaxNode> typeSyntaxGetter, Func<TSyntaxNode, SyntaxTokenList?> modifierGetter, Func<DeclarationModifiers, ImmutableArray<SymbolKindOrTypeKind>> possibleDeclarationComputer, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode { if (!IsPossibleTypeToken(token) && !token.IsKind(SyntaxKind.CommaToken)) { return default; } var target = token.GetAncestor<TSyntaxNode>(); if (target == null) { return default; } if (token.IsKind(SyntaxKind.CommaToken) && token.Parent != target) { return default; } var typeSyntax = typeSyntaxGetter(target); if (typeSyntax == null) { return default; } if (!token.IsKind(SyntaxKind.CommaToken) && token != typeSyntax.GetLastToken()) { return default; } var modifiers = modifierGetter(target); if (modifiers == null) { return default; } var alias = semanticModel.GetAliasInfo(typeSyntax, cancellationToken); var type = semanticModel.GetTypeInfo(typeSyntax, cancellationToken).Type; return new NameDeclarationInfo( possibleDeclarationComputer(GetDeclarationModifiers(modifiers.Value)), GetAccessibility(modifiers.Value), GetDeclarationModifiers(modifiers.Value), type, alias); } private static NameDeclarationInfo IsLastTokenOfType<TSyntaxNode>( SyntaxToken token, SemanticModel semanticModel, Func<TSyntaxNode, SyntaxNode> typeSyntaxGetter, Func<TSyntaxNode, SyntaxTokenList> modifierGetter, Func<DeclarationModifiers, ImmutableArray<SymbolKindOrTypeKind>> possibleDeclarationComputer, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode { if (!IsPossibleTypeToken(token)) { return default; } var target = token.GetAncestor<TSyntaxNode>(); if (target == null) { return default; } var typeSyntax = typeSyntaxGetter(target); if (typeSyntax == null || token != typeSyntax.GetLastToken()) { return default; } var modifiers = modifierGetter(target); return new NameDeclarationInfo( possibleDeclarationComputer(GetDeclarationModifiers(modifiers)), GetAccessibility(modifiers), GetDeclarationModifiers(modifiers), semanticModel.GetTypeInfo(typeSyntax, cancellationToken).Type, semanticModel.GetAliasInfo(typeSyntax, cancellationToken)); } private static bool IsFieldDeclaration(SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken, out NameDeclarationInfo result) { result = IsFollowingTypeOrComma<VariableDeclarationSyntax>(token, semanticModel, v => v.Type, v => v.Parent is FieldDeclarationSyntax f ? f.Modifiers : (SyntaxTokenList?)null, GetPossibleMemberDeclarations, cancellationToken); return result.Type != null; } private static bool IsIncompleteMemberDeclaration(SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken, out NameDeclarationInfo result) { result = IsLastTokenOfType<IncompleteMemberSyntax>(token, semanticModel, i => i.Type, i => i.Modifiers, GetPossibleMemberDeclarations, cancellationToken); return result.Type != null; } private static bool IsLocalFunctionDeclaration(SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken, out NameDeclarationInfo result) { result = IsLastTokenOfType<LocalFunctionStatementSyntax>(token, semanticModel, typeSyntaxGetter: f => f.ReturnType, modifierGetter: f => f.Modifiers, possibleDeclarationComputer: GetPossibleLocalDeclarations, cancellationToken); return result.Type != null; } private static bool IsLocalVariableDeclaration(SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken, out NameDeclarationInfo result) { // If we only have a type, this can still end up being a local function (depending on the modifiers). var possibleDeclarationComputer = token.IsKind(SyntaxKind.CommaToken) ? (Func<DeclarationModifiers, ImmutableArray<SymbolKindOrTypeKind>>) (_ => ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Local))) : GetPossibleLocalDeclarations; result = IsFollowingTypeOrComma<VariableDeclarationSyntax>(token, semanticModel, typeSyntaxGetter: v => v.Type, modifierGetter: v => v.Parent is LocalDeclarationStatementSyntax localDeclaration ? localDeclaration.Modifiers : (SyntaxTokenList?)null, // Return null to bail out. possibleDeclarationComputer, cancellationToken); if (result.Type != null) { return true; } // If the type has a trailing question mark, we may parse it as a conditional access expression. // We will use the condition as the type to bind; we won't make the type we bind nullable // because we ignore nullability when generating names anyways if (token.IsKind(SyntaxKind.QuestionToken) && token.Parent is ConditionalExpressionSyntax conditionalExpressionSyntax) { var symbolInfo = semanticModel.GetSymbolInfo(conditionalExpressionSyntax.Condition); if (symbolInfo.GetAnySymbol() is ITypeSymbol type) { var alias = semanticModel.GetAliasInfo(conditionalExpressionSyntax.Condition, cancellationToken); result = new NameDeclarationInfo( possibleDeclarationComputer(default), accessibility: null, declarationModifiers: default, type, alias); return true; } } return false; } private static bool IsEmbeddedVariableDeclaration(SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken, out NameDeclarationInfo result) { result = IsFollowingTypeOrComma<VariableDeclarationSyntax>(token, semanticModel, typeSyntaxGetter: v => v.Type, modifierGetter: v => v.Parent is UsingStatementSyntax || v.Parent is ForStatementSyntax ? default(SyntaxTokenList) : (SyntaxTokenList?)null, // Return null to bail out. possibleDeclarationComputer: d => ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Local)), cancellationToken); return result.Type != null; } private static bool IsForEachVariableDeclaration(SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken, out NameDeclarationInfo result) { // This is parsed as ForEachVariableStatementSyntax: // foreach (int $$ result = IsLastTokenOfType<CommonForEachStatementSyntax>(token, semanticModel, typeSyntaxGetter: f => f is ForEachStatementSyntax forEachStatement ? forEachStatement.Type : f is ForEachVariableStatementSyntax forEachVariableStatement ? forEachVariableStatement.Variable : null, // Return null to bail out. modifierGetter: f => default, possibleDeclarationComputer: d => ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Local)), cancellationToken); return result.Type != null; } private static bool IsTypeParameterDeclaration(SyntaxToken token, out NameDeclarationInfo result) { if (token.IsKind(SyntaxKind.LessThanToken, SyntaxKind.CommaToken) && token.Parent.IsKind(SyntaxKind.TypeParameterList)) { result = new NameDeclarationInfo( ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.TypeParameter)), Accessibility.NotApplicable, new DeclarationModifiers(), type: null, alias: null); return true; } result = default; return false; } private static bool IsPrimaryConstructorParameter(SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken, out NameDeclarationInfo result) { result = IsLastTokenOfType<ParameterSyntax>( token, semanticModel, p => p.Type, _ => default, _ => s_propertySyntaxKind, cancellationToken); if (result.Type != null && token.GetAncestor<ParameterSyntax>().Parent.IsParentKind(SyntaxKind.RecordDeclaration, SyntaxKind.RecordStructDeclaration)) { return true; } result = default; return false; } private static bool IsParameterDeclaration(SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken, out NameDeclarationInfo result) { result = IsLastTokenOfType<ParameterSyntax>( token, semanticModel, p => p.Type, _ => default, _ => s_parameterSyntaxKind, cancellationToken); return result.Type != null; } private static bool IsPatternMatching(SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken, out NameDeclarationInfo result) { result = default; if (token.Parent.IsParentKind(SyntaxKind.IsExpression)) { result = IsLastTokenOfType<BinaryExpressionSyntax>( token, semanticModel, b => b.Right, _ => default, _ => s_parameterSyntaxKind, cancellationToken); } else if (token.Parent.IsParentKind(SyntaxKind.CaseSwitchLabel)) { result = IsLastTokenOfType<CaseSwitchLabelSyntax>( token, semanticModel, b => b.Value, _ => default, _ => s_parameterSyntaxKind, cancellationToken); } else if (token.Parent.IsParentKind(SyntaxKind.DeclarationPattern)) { result = IsLastTokenOfType<DeclarationPatternSyntax>( token, semanticModel, b => b.Type, _ => default, _ => s_parameterSyntaxKind, cancellationToken); } return result.Type != null; } private static bool IsPossibleTypeToken(SyntaxToken token) => token.IsKind( SyntaxKind.IdentifierToken, SyntaxKind.GreaterThanToken, SyntaxKind.CloseBracketToken, SyntaxKind.QuestionToken) || token.Parent.IsKind(SyntaxKind.PredefinedType); private static ImmutableArray<SymbolKindOrTypeKind> GetPossibleMemberDeclarations(DeclarationModifiers modifiers) { if (modifiers.IsConst || modifiers.IsReadOnly) { return ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Field)); } var possibleTypes = ImmutableArray.Create( new SymbolKindOrTypeKind(SymbolKind.Field), new SymbolKindOrTypeKind(SymbolKind.Property), new SymbolKindOrTypeKind(MethodKind.Ordinary)); if (modifiers.IsAbstract || modifiers.IsVirtual || modifiers.IsSealed || modifiers.IsOverride) { possibleTypes = possibleTypes.Remove(new SymbolKindOrTypeKind(SymbolKind.Field)); } if (modifiers.IsAsync || modifiers.IsPartial) { // Fields and properties cannot be async or partial. possibleTypes = possibleTypes.Remove(new SymbolKindOrTypeKind(SymbolKind.Field)); possibleTypes = possibleTypes.Remove(new SymbolKindOrTypeKind(SymbolKind.Property)); } return possibleTypes; } private static ImmutableArray<SymbolKindOrTypeKind> GetPossibleLocalDeclarations(DeclarationModifiers modifiers) { return modifiers.IsConst ? ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Local)) : modifiers.IsAsync || modifiers.IsUnsafe ? ImmutableArray.Create(new SymbolKindOrTypeKind(MethodKind.LocalFunction)) : ImmutableArray.Create( new SymbolKindOrTypeKind(SymbolKind.Local), new SymbolKindOrTypeKind(MethodKind.LocalFunction)); } private static DeclarationModifiers GetDeclarationModifiers(SyntaxTokenList modifiers) { var declarationModifiers = new DeclarationModifiers(); foreach (var modifer in modifiers) { switch (modifer.Kind()) { case SyntaxKind.StaticKeyword: declarationModifiers = declarationModifiers.WithIsStatic(true); continue; case SyntaxKind.AbstractKeyword: declarationModifiers = declarationModifiers.WithIsAbstract(true); continue; case SyntaxKind.NewKeyword: declarationModifiers = declarationModifiers.WithIsNew(true); continue; case SyntaxKind.UnsafeKeyword: declarationModifiers = declarationModifiers.WithIsUnsafe(true); continue; case SyntaxKind.ReadOnlyKeyword: declarationModifiers = declarationModifiers.WithIsReadOnly(true); continue; case SyntaxKind.VirtualKeyword: declarationModifiers = declarationModifiers.WithIsVirtual(true); continue; case SyntaxKind.OverrideKeyword: declarationModifiers = declarationModifiers.WithIsOverride(true); continue; case SyntaxKind.SealedKeyword: declarationModifiers = declarationModifiers.WithIsSealed(true); continue; case SyntaxKind.ConstKeyword: declarationModifiers = declarationModifiers.WithIsConst(true); continue; case SyntaxKind.AsyncKeyword: declarationModifiers = declarationModifiers.WithAsync(true); continue; case SyntaxKind.PartialKeyword: declarationModifiers = declarationModifiers.WithPartial(true); continue; } } return declarationModifiers; } private static Accessibility? GetAccessibility(SyntaxTokenList modifiers) { for (var i = modifiers.Count - 1; i >= 0; i--) { var modifier = modifiers[i]; switch (modifier.Kind()) { case SyntaxKind.PrivateKeyword: return Accessibility.Private; case SyntaxKind.PublicKeyword: return Accessibility.Public; case SyntaxKind.ProtectedKeyword: return Accessibility.Protected; case SyntaxKind.InternalKeyword: return Accessibility.Internal; } } return null; } private static SyntaxNode GetNodeDenotingTheTypeOfTupleArgument(ArgumentSyntax argumentSyntax) { switch (argumentSyntax.Expression?.Kind()) { case SyntaxKind.DeclarationExpression: // The parser found a declaration as in (System.Action action, System.Array a$$) // we need the type part of the declaration expression. return ((DeclarationExpressionSyntax)argumentSyntax.Expression).Type; default: // We assume the parser found something that represents something named, // e.g. a MemberAccessExpression as in (System.Action action, System.Array $$) // We also assume that this name could be resolved to a type. return argumentSyntax.Expression; } } } } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/TextLineExtensions.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.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class TextLineExtensions { public static int? GetLastNonWhitespacePosition(this TextLine line) { var startPosition = line.Start; var text = line.ToString(); for (var i = text.Length - 1; i >= 0; i--) { if (!char.IsWhiteSpace(text[i])) { return startPosition + i; } } return null; } /// <summary> /// Returns the first non-whitespace position on the given line, or null if /// the line is empty or contains only whitespace. /// </summary> public static int? GetFirstNonWhitespacePosition(this TextLine line) { var firstNonWhitespaceOffset = line.GetFirstNonWhitespaceOffset(); return firstNonWhitespaceOffset.HasValue ? firstNonWhitespaceOffset + line.Start : null; } /// <summary> /// Returns the first non-whitespace position on the given line as an offset /// from the start of the line, or null if the line is empty or contains only /// whitespace. /// </summary> public static int? GetFirstNonWhitespaceOffset(this TextLine line) => line.ToString().GetFirstNonWhitespaceOffset(); public static string GetLeadingWhitespace(this TextLine line) => line.ToString().GetLeadingWhitespace(); /// <summary> /// Determines whether the specified line is empty or contains whitespace only. /// </summary> public static bool IsEmptyOrWhitespace(this TextLine line) { var text = line.Text; RoslynDebug.Assert(text is object); for (var i = line.Span.Start; i < line.Span.End; i++) { if (!char.IsWhiteSpace(text[i])) { return false; } } return true; } public static int GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(this TextLine line, int tabSize) => line.ToString().GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(tabSize); public static int GetColumnFromLineOffset(this TextLine line, int lineOffset, int tabSize) => line.ToString().GetColumnFromLineOffset(lineOffset, tabSize); public static int GetLineOffsetFromColumn(this TextLine line, int column, int tabSize) => line.ToString().GetLineOffsetFromColumn(column, tabSize); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class TextLineExtensions { public static int? GetLastNonWhitespacePosition(this TextLine line) { var startPosition = line.Start; var text = line.ToString(); for (var i = text.Length - 1; i >= 0; i--) { if (!char.IsWhiteSpace(text[i])) { return startPosition + i; } } return null; } /// <summary> /// Returns the first non-whitespace position on the given line, or null if /// the line is empty or contains only whitespace. /// </summary> public static int? GetFirstNonWhitespacePosition(this TextLine line) { var firstNonWhitespaceOffset = line.GetFirstNonWhitespaceOffset(); return firstNonWhitespaceOffset.HasValue ? firstNonWhitespaceOffset + line.Start : null; } /// <summary> /// Returns the first non-whitespace position on the given line as an offset /// from the start of the line, or null if the line is empty or contains only /// whitespace. /// </summary> public static int? GetFirstNonWhitespaceOffset(this TextLine line) => line.ToString().GetFirstNonWhitespaceOffset(); public static string GetLeadingWhitespace(this TextLine line) => line.ToString().GetLeadingWhitespace(); /// <summary> /// Determines whether the specified line is empty or contains whitespace only. /// </summary> public static bool IsEmptyOrWhitespace(this TextLine line) { var text = line.Text; RoslynDebug.Assert(text is object); for (var i = line.Span.Start; i < line.Span.End; i++) { if (!char.IsWhiteSpace(text[i])) { return false; } } return true; } public static int GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(this TextLine line, int tabSize) => line.ToString().GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(tabSize); public static int GetColumnFromLineOffset(this TextLine line, int lineOffset, int tabSize) => line.ToString().GetColumnFromLineOffset(lineOffset, tabSize); public static int GetLineOffsetFromColumn(this TextLine line, int column, int tabSize) => line.ToString().GetLineOffsetFromColumn(column, tabSize); } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/ExtractMethod/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.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractMethod { internal static class Extensions { public static bool Succeeded(this OperationStatus status) => status.Flag.Succeeded(); public static bool FailedWithNoBestEffortSuggestion(this OperationStatus status) => status.Flag.Failed() && !status.Flag.HasBestEffort(); public static bool Failed(this OperationStatus status) => status.Flag.Failed(); public static bool Succeeded(this OperationStatusFlag flag) => (flag & OperationStatusFlag.Succeeded) != 0; public static bool Failed(this OperationStatusFlag flag) => !flag.Succeeded(); public static bool HasBestEffort(this OperationStatusFlag flag) => (flag & OperationStatusFlag.BestEffort) != 0; public static bool HasSuggestion(this OperationStatusFlag flag) => (flag & OperationStatusFlag.Suggestion) != 0; public static bool HasMask(this OperationStatusFlag flag, OperationStatusFlag mask) => (flag & mask) != 0x0; public static OperationStatusFlag RemoveFlag(this OperationStatusFlag baseFlag, OperationStatusFlag flagToRemove) => baseFlag & ~flagToRemove; public static ITypeSymbol? GetLambdaOrAnonymousMethodReturnType(this SemanticModel binding, SyntaxNode node) { var info = binding.GetSymbolInfo(node); if (info.Symbol == null) { return null; } var methodSymbol = info.Symbol as IMethodSymbol; if (methodSymbol?.MethodKind != MethodKind.AnonymousFunction) { return null; } return methodSymbol.ReturnType; } public static Task<SemanticDocument> WithSyntaxRootAsync(this SemanticDocument semanticDocument, SyntaxNode root, CancellationToken cancellationToken) => SemanticDocument.CreateAsync(semanticDocument.Document.WithSyntaxRoot(root), cancellationToken); /// <summary> /// get tokens with given annotation in current document /// </summary> public static SyntaxToken GetTokenWithAnnotation(this SemanticDocument document, SyntaxAnnotation annotation) => document.Root.GetAnnotatedNodesAndTokens(annotation).Single().AsToken(); /// <summary> /// resolve the given symbol against compilation this snapshot has /// </summary> public static T ResolveType<T>(this SemanticModel semanticModel, T symbol) where T : class, ITypeSymbol { // Can be cleaned up when https://github.com/dotnet/roslyn/issues/38061 is resolved var typeSymbol = (T?)symbol.GetSymbolKey().Resolve(semanticModel.Compilation).GetAnySymbol(); Contract.ThrowIfNull(typeSymbol); return (T)typeSymbol.WithNullableAnnotation(symbol.NullableAnnotation); } /// <summary> /// check whether node contains error for itself but not from its child node /// </summary> public static bool HasDiagnostics(this SyntaxNode node) { var set = new HashSet<Diagnostic>(node.GetDiagnostics()); foreach (var child in node.ChildNodes()) { set.ExceptWith(child.GetDiagnostics()); } return set.Count > 0; } public static bool FromScript(this SyntaxNode node) { if (node.SyntaxTree == null) { return false; } return node.SyntaxTree.Options.Kind != SourceCodeKind.Regular; } } }
// Licensed to the .NET Foundation under one or more 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 System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractMethod { internal static class Extensions { public static bool Succeeded(this OperationStatus status) => status.Flag.Succeeded(); public static bool FailedWithNoBestEffortSuggestion(this OperationStatus status) => status.Flag.Failed() && !status.Flag.HasBestEffort(); public static bool Failed(this OperationStatus status) => status.Flag.Failed(); public static bool Succeeded(this OperationStatusFlag flag) => (flag & OperationStatusFlag.Succeeded) != 0; public static bool Failed(this OperationStatusFlag flag) => !flag.Succeeded(); public static bool HasBestEffort(this OperationStatusFlag flag) => (flag & OperationStatusFlag.BestEffort) != 0; public static bool HasSuggestion(this OperationStatusFlag flag) => (flag & OperationStatusFlag.Suggestion) != 0; public static bool HasMask(this OperationStatusFlag flag, OperationStatusFlag mask) => (flag & mask) != 0x0; public static OperationStatusFlag RemoveFlag(this OperationStatusFlag baseFlag, OperationStatusFlag flagToRemove) => baseFlag & ~flagToRemove; public static ITypeSymbol? GetLambdaOrAnonymousMethodReturnType(this SemanticModel binding, SyntaxNode node) { var info = binding.GetSymbolInfo(node); if (info.Symbol == null) { return null; } var methodSymbol = info.Symbol as IMethodSymbol; if (methodSymbol?.MethodKind != MethodKind.AnonymousFunction) { return null; } return methodSymbol.ReturnType; } public static Task<SemanticDocument> WithSyntaxRootAsync(this SemanticDocument semanticDocument, SyntaxNode root, CancellationToken cancellationToken) => SemanticDocument.CreateAsync(semanticDocument.Document.WithSyntaxRoot(root), cancellationToken); /// <summary> /// get tokens with given annotation in current document /// </summary> public static SyntaxToken GetTokenWithAnnotation(this SemanticDocument document, SyntaxAnnotation annotation) => document.Root.GetAnnotatedNodesAndTokens(annotation).Single().AsToken(); /// <summary> /// resolve the given symbol against compilation this snapshot has /// </summary> public static T ResolveType<T>(this SemanticModel semanticModel, T symbol) where T : class, ITypeSymbol { // Can be cleaned up when https://github.com/dotnet/roslyn/issues/38061 is resolved var typeSymbol = (T?)symbol.GetSymbolKey().Resolve(semanticModel.Compilation).GetAnySymbol(); Contract.ThrowIfNull(typeSymbol); return (T)typeSymbol.WithNullableAnnotation(symbol.NullableAnnotation); } /// <summary> /// check whether node contains error for itself but not from its child node /// </summary> public static bool HasDiagnostics(this SyntaxNode node) { var set = new HashSet<Diagnostic>(node.GetDiagnostics()); foreach (var child in node.ChildNodes()) { set.ExceptWith(child.GetDiagnostics()); } return set.Count > 0; } public static bool FromScript(this SyntaxNode node) { if (node.SyntaxTree == null) { return false; } return node.SyntaxTree.Options.Kind != SourceCodeKind.Regular; } } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/Workspace/Host/PersistentStorage/DocumentKey.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.Runtime.Serialization; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.PersistentStorage { /// <summary> /// Handle that can be used with <see cref="IChecksummedPersistentStorage"/> to read data for a /// <see cref="Document"/> without needing to have the entire <see cref="Document"/> snapshot available. /// This is useful for cases where acquiring an entire snapshot might be expensive (for example, during /// solution load), but querying the data is still desired. /// </summary> [DataContract] internal readonly struct DocumentKey : IEqualityComparer<DocumentKey> { [DataMember(Order = 0)] public readonly ProjectKey Project; [DataMember(Order = 1)] public readonly DocumentId Id; [DataMember(Order = 2)] public readonly string? FilePath; [DataMember(Order = 3)] public readonly string Name; public DocumentKey(ProjectKey project, DocumentId id, string? filePath, string name) { Project = project; Id = id; FilePath = filePath; Name = name; } public static DocumentKey ToDocumentKey(Document document) => ToDocumentKey(ProjectKey.ToProjectKey(document.Project), document.State); public static DocumentKey ToDocumentKey(ProjectKey projectKey, TextDocumentState state) => new(projectKey, state.Id, state.FilePath, state.Name); public bool Equals(DocumentKey x, DocumentKey y) => x.Id == y.Id; public int GetHashCode(DocumentKey obj) => obj.Id.GetHashCode(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Runtime.Serialization; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.PersistentStorage { /// <summary> /// Handle that can be used with <see cref="IChecksummedPersistentStorage"/> to read data for a /// <see cref="Document"/> without needing to have the entire <see cref="Document"/> snapshot available. /// This is useful for cases where acquiring an entire snapshot might be expensive (for example, during /// solution load), but querying the data is still desired. /// </summary> [DataContract] internal readonly struct DocumentKey : IEqualityComparer<DocumentKey> { [DataMember(Order = 0)] public readonly ProjectKey Project; [DataMember(Order = 1)] public readonly DocumentId Id; [DataMember(Order = 2)] public readonly string? FilePath; [DataMember(Order = 3)] public readonly string Name; public DocumentKey(ProjectKey project, DocumentId id, string? filePath, string name) { Project = project; Id = id; FilePath = filePath; Name = name; } public static DocumentKey ToDocumentKey(Document document) => ToDocumentKey(ProjectKey.ToProjectKey(document.Project), document.State); public static DocumentKey ToDocumentKey(ProjectKey projectKey, TextDocumentState state) => new(projectKey, state.Id, state.FilePath, state.Name); public bool Equals(DocumentKey x, DocumentKey y) => x.Id == y.Id; public int GetHashCode(DocumentKey obj) => obj.Id.GetHashCode(); } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/InternalUtilities/NonDefaultableAttribute.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Roslyn.Utilities { [AttributeUsage(AttributeTargets.Struct | AttributeTargets.GenericParameter)] internal sealed class NonDefaultableAttribute : Attribute { } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Roslyn.Utilities { [AttributeUsage(AttributeTargets.Struct | AttributeTargets.GenericParameter)] internal sealed class NonDefaultableAttribute : Attribute { } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/ReferenceManager/UnifiedAssembly.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Microsoft.CodeAnalysis.Symbols; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Assembly symbol referenced by a AssemblyRef for which we couldn't find a matching /// compilation reference but we found one that differs in version. /// Created only for assemblies that require runtime binding redirection policy, /// i.e. not for Framework assemblies. /// </summary> internal struct UnifiedAssembly<TAssemblySymbol> where TAssemblySymbol : class, IAssemblySymbolInternal { /// <summary> /// Original reference that was unified to the identity of the <see cref="TargetAssembly"/>. /// </summary> internal readonly AssemblyIdentity OriginalReference; internal readonly TAssemblySymbol TargetAssembly; public UnifiedAssembly(TAssemblySymbol targetAssembly, AssemblyIdentity originalReference) { Debug.Assert(originalReference != null); Debug.Assert(targetAssembly != null); this.OriginalReference = originalReference; this.TargetAssembly = targetAssembly; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Microsoft.CodeAnalysis.Symbols; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Assembly symbol referenced by a AssemblyRef for which we couldn't find a matching /// compilation reference but we found one that differs in version. /// Created only for assemblies that require runtime binding redirection policy, /// i.e. not for Framework assemblies. /// </summary> internal struct UnifiedAssembly<TAssemblySymbol> where TAssemblySymbol : class, IAssemblySymbolInternal { /// <summary> /// Original reference that was unified to the identity of the <see cref="TargetAssembly"/>. /// </summary> internal readonly AssemblyIdentity OriginalReference; internal readonly TAssemblySymbol TargetAssembly; public UnifiedAssembly(TAssemblySymbol targetAssembly, AssemblyIdentity originalReference) { Debug.Assert(originalReference != null); Debug.Assert(targetAssembly != null); this.OriginalReference = originalReference; this.TargetAssembly = targetAssembly; } } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/TodoComments/TodoCommentData.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.Runtime.Serialization; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.TodoComments { /// <summary> /// Serialization type used to pass information to/from OOP and VS. /// </summary> [DataContract] internal readonly struct TodoCommentData : IEquatable<TodoCommentData> { [DataMember(Order = 0)] public readonly int Priority; [DataMember(Order = 1)] public readonly string Message; [DataMember(Order = 2)] public readonly DocumentId DocumentId; [DataMember(Order = 3)] public readonly string? MappedFilePath; [DataMember(Order = 4)] public readonly string? OriginalFilePath; [DataMember(Order = 5)] public readonly int MappedLine; [DataMember(Order = 6)] public readonly int MappedColumn; [DataMember(Order = 7)] public readonly int OriginalLine; [DataMember(Order = 8)] public readonly int OriginalColumn; public TodoCommentData(int priority, string message, DocumentId documentId, string? mappedFilePath, string? originalFilePath, int mappedLine, int mappedColumn, int originalLine, int originalColumn) { Priority = priority; Message = message; DocumentId = documentId; MappedFilePath = mappedFilePath; OriginalFilePath = originalFilePath; MappedLine = mappedLine; MappedColumn = mappedColumn; OriginalLine = originalLine; OriginalColumn = originalColumn; } public override bool Equals(object? obj) => obj is TodoCommentData other && Equals(other); public override int GetHashCode() => GetHashCode(this); public override string ToString() => $"{Priority} {Message} {MappedFilePath ?? ""} ({MappedLine}, {MappedColumn}) [original: {OriginalFilePath ?? ""} ({OriginalLine}, {OriginalColumn})"; public bool Equals(TodoCommentData right) => DocumentId == right.DocumentId && Priority == right.Priority && Message == right.Message && OriginalLine == right.OriginalLine && OriginalColumn == right.OriginalColumn; public static int GetHashCode(TodoCommentData item) => Hash.Combine(item.DocumentId, Hash.Combine(item.Priority, Hash.Combine(item.Message, Hash.Combine(item.OriginalLine, Hash.Combine(item.OriginalColumn, 0))))); internal void WriteTo(ObjectWriter writer) { writer.WriteInt32(Priority); writer.WriteString(Message); DocumentId.WriteTo(writer); writer.WriteString(MappedFilePath); writer.WriteString(OriginalFilePath); writer.WriteInt32(MappedLine); writer.WriteInt32(MappedColumn); writer.WriteInt32(OriginalLine); writer.WriteInt32(OriginalColumn); } internal static TodoCommentData ReadFrom(ObjectReader reader) => new(priority: reader.ReadInt32(), message: reader.ReadString(), documentId: DocumentId.ReadFrom(reader), mappedFilePath: reader.ReadString(), originalFilePath: reader.ReadString(), mappedLine: reader.ReadInt32(), mappedColumn: reader.ReadInt32(), originalLine: reader.ReadInt32(), originalColumn: reader.ReadInt32()); } }
// Licensed to the .NET Foundation under one or more 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.Runtime.Serialization; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.TodoComments { /// <summary> /// Serialization type used to pass information to/from OOP and VS. /// </summary> [DataContract] internal readonly struct TodoCommentData : IEquatable<TodoCommentData> { [DataMember(Order = 0)] public readonly int Priority; [DataMember(Order = 1)] public readonly string Message; [DataMember(Order = 2)] public readonly DocumentId DocumentId; [DataMember(Order = 3)] public readonly string? MappedFilePath; [DataMember(Order = 4)] public readonly string? OriginalFilePath; [DataMember(Order = 5)] public readonly int MappedLine; [DataMember(Order = 6)] public readonly int MappedColumn; [DataMember(Order = 7)] public readonly int OriginalLine; [DataMember(Order = 8)] public readonly int OriginalColumn; public TodoCommentData(int priority, string message, DocumentId documentId, string? mappedFilePath, string? originalFilePath, int mappedLine, int mappedColumn, int originalLine, int originalColumn) { Priority = priority; Message = message; DocumentId = documentId; MappedFilePath = mappedFilePath; OriginalFilePath = originalFilePath; MappedLine = mappedLine; MappedColumn = mappedColumn; OriginalLine = originalLine; OriginalColumn = originalColumn; } public override bool Equals(object? obj) => obj is TodoCommentData other && Equals(other); public override int GetHashCode() => GetHashCode(this); public override string ToString() => $"{Priority} {Message} {MappedFilePath ?? ""} ({MappedLine}, {MappedColumn}) [original: {OriginalFilePath ?? ""} ({OriginalLine}, {OriginalColumn})"; public bool Equals(TodoCommentData right) => DocumentId == right.DocumentId && Priority == right.Priority && Message == right.Message && OriginalLine == right.OriginalLine && OriginalColumn == right.OriginalColumn; public static int GetHashCode(TodoCommentData item) => Hash.Combine(item.DocumentId, Hash.Combine(item.Priority, Hash.Combine(item.Message, Hash.Combine(item.OriginalLine, Hash.Combine(item.OriginalColumn, 0))))); internal void WriteTo(ObjectWriter writer) { writer.WriteInt32(Priority); writer.WriteString(Message); DocumentId.WriteTo(writer); writer.WriteString(MappedFilePath); writer.WriteString(OriginalFilePath); writer.WriteInt32(MappedLine); writer.WriteInt32(MappedColumn); writer.WriteInt32(OriginalLine); writer.WriteInt32(OriginalColumn); } internal static TodoCommentData ReadFrom(ObjectReader reader) => new(priority: reader.ReadInt32(), message: reader.ReadString(), documentId: DocumentId.ReadFrom(reader), mappedFilePath: reader.ReadString(), originalFilePath: reader.ReadString(), mappedLine: reader.ReadInt32(), mappedColumn: reader.ReadInt32(), originalLine: reader.ReadInt32(), originalColumn: reader.ReadInt32()); } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/DocumentationComments/VisualStudioDocumentationProvider.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.Globalization; using System.Threading; using System.Xml; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.DocumentationComments { internal class VisualStudioDocumentationProvider : DocumentationProvider { private readonly string _filePath; private readonly IVsXMLMemberIndexService _memberIndexService; private readonly Lazy<IVsXMLMemberIndex> _lazyMemberIndex; public VisualStudioDocumentationProvider(string filePath, IVsXMLMemberIndexService memberIndexService) { Contract.ThrowIfNull(memberIndexService); Contract.ThrowIfNull(filePath); _filePath = filePath; _memberIndexService = memberIndexService; _lazyMemberIndex = new Lazy<IVsXMLMemberIndex>(CreateXmlMemberIndex, isThreadSafe: true); } protected override string GetDocumentationForSymbol(string documentationMemberID, CultureInfo preferredCulture, CancellationToken token = default) { var memberIndex = _lazyMemberIndex.Value; if (memberIndex == null) { return ""; } if (ErrorHandler.Failed(memberIndex.ParseMemberSignature(documentationMemberID, out var methodID))) { return ""; } if (ErrorHandler.Failed(memberIndex.GetMemberXML(methodID, out var xml))) { return ""; } return xml; } private IVsXMLMemberIndex CreateXmlMemberIndex() { // This may fail if there is no XML file available for this assembly. We'll just leave // memberIndex null in this case. _memberIndexService.CreateXMLMemberIndex(_filePath, out var memberIndex); return memberIndex; } public override bool Equals(object obj) => obj is VisualStudioDocumentationProvider other && string.Equals(_filePath, other._filePath, StringComparison.OrdinalIgnoreCase); public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(_filePath); } }
// Licensed to the .NET Foundation under one or more 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.Globalization; using System.Threading; using System.Xml; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.DocumentationComments { internal class VisualStudioDocumentationProvider : DocumentationProvider { private readonly string _filePath; private readonly IVsXMLMemberIndexService _memberIndexService; private readonly Lazy<IVsXMLMemberIndex> _lazyMemberIndex; public VisualStudioDocumentationProvider(string filePath, IVsXMLMemberIndexService memberIndexService) { Contract.ThrowIfNull(memberIndexService); Contract.ThrowIfNull(filePath); _filePath = filePath; _memberIndexService = memberIndexService; _lazyMemberIndex = new Lazy<IVsXMLMemberIndex>(CreateXmlMemberIndex, isThreadSafe: true); } protected override string GetDocumentationForSymbol(string documentationMemberID, CultureInfo preferredCulture, CancellationToken token = default) { var memberIndex = _lazyMemberIndex.Value; if (memberIndex == null) { return ""; } if (ErrorHandler.Failed(memberIndex.ParseMemberSignature(documentationMemberID, out var methodID))) { return ""; } if (ErrorHandler.Failed(memberIndex.GetMemberXML(methodID, out var xml))) { return ""; } return xml; } private IVsXMLMemberIndex CreateXmlMemberIndex() { // This may fail if there is no XML file available for this assembly. We'll just leave // memberIndex null in this case. _memberIndexService.CreateXMLMemberIndex(_filePath, out var memberIndex); return memberIndex; } public override bool Equals(object obj) => obj is VisualStudioDocumentationProvider other && string.Equals(_filePath, other._filePath, StringComparison.OrdinalIgnoreCase); public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(_filePath); } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/ExtractMethod/ExtractMethodTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.ExtractMethod; using Microsoft.CodeAnalysis.Editor.CSharp.ExtractMethod; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ExtractMethod { public partial class ExtractMethodTests : ExtractMethodBase { [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod1() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { [|int i; i = 10;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { NewMethod(); } private static void NewMethod() { int i = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod2() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { [|int i = 10; int i2 = 10;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { NewMethod(); } private static void NewMethod() { int i = 10; int i2 = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod3() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i = 10; [|int i2 = i;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i = 10; NewMethod(i); } private static void NewMethod(int i) { int i2 = i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod4() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i = 10; int i2 = i; [|i2 += i;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i = 10; int i2 = i; i2 = NewMethod(i); } private static int NewMethod(int i, int i2) { i2 += i; return i2; } }"; // compoundaction not supported yet. await TestExtractMethodAsync(code, expected, temporaryFailing: true); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod5() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i = 10; int i2 = i; [|i2 = i;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i = 10; int i2 = i; i2 = NewMethod(i); } private static int NewMethod(int i) { return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod6() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { int field; void Test(string[] args) { int i = 10; [|field = i;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { int field; void Test(string[] args) { int i = 10; NewMethod(i); } private void NewMethod(int i) { field = i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod7() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { string [] a = null; [|Test(a);|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { string[] a = null; NewMethod(a); } private void NewMethod(string[] a) { Test(a); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod8() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Test(string[] args) { string [] a = null; [|Test(a);|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Test(string[] args) { string[] a = null; NewMethod(a); } private static void NewMethod(string[] a) { Test(a); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod9() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i; string s; [|i = 10; s = args[0] + i.ToString();|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i; string s; NewMethod(args, out i, out s); } private static void NewMethod(string[] args, out int i, out string s) { i = 10; s = args[0] + i.ToString(); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod10() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { [|int i; i = 10; string s; s = args[0] + i.ToString();|] Console.WriteLine(s); } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { string s = NewMethod(args); Console.WriteLine(s); } private static string NewMethod(string[] args) { int i = 10; string s; s = args[0] + i.ToString(); return s; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod11() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { [|int i; int i2 = 10;|] i = 10; } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i; NewMethod(); i = 10; } private static void NewMethod() { int i2 = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod11_1() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { [|int i; int i2 = 10;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { NewMethod(); } private static void NewMethod() { int i; int i2 = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod12() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i = 10; [|i = i + 1;|] Console.WriteLine(i); } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i = 10; i = NewMethod(i); Console.WriteLine(i); } private static int NewMethod(int i) { i = i + 1; return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ControlVariableInForeachStatement() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { foreach (var s in args) { [|Console.WriteLine(s);|] } } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { foreach (var s in args) { NewMethod(s); } } private static void NewMethod(string s) { Console.WriteLine(s); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod14() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { for(var i = 1; i < 10; i++) { [|Console.WriteLine(i);|] } } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { for (var i = 1; i < 10; i++) { NewMethod(i); } } private static void NewMethod(int i) { Console.WriteLine(i); } }"; // var in for loop doesn't get bound yet await TestExtractMethodAsync(code, expected, temporaryFailing: true); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod15() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { [|int s = 10, i = 1; int b = s + i;|] System.Console.WriteLine(s); System.Console.WriteLine(i); } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int s, i; NewMethod(out s, out i); System.Console.WriteLine(s); System.Console.WriteLine(i); } private static void NewMethod(out int s, out int i) { s = 10; i = 1; int b = s + i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod16() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { [|int i = 1;|] System.Console.WriteLine(i); } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i = NewMethod(); System.Console.WriteLine(i); } private static int NewMethod() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538932, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538932")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod17() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test<T>(out T t) where T : class, new() { [|T t1; Test(out t1); t = t1;|] System.Console.WriteLine(t1.ToString()); } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test<T>(out T t) where T : class, new() { T t1; NewMethod(out t, out t1); System.Console.WriteLine(t1.ToString()); } private void NewMethod<T>(out T t, out T t1) where T : class, new() { Test(out t1); t = t1; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod18() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test<T>(out T t) where T : class, new() { [|T t1 = GetValue(out t);|] System.Console.WriteLine(t1.ToString()); } private T GetValue<T>(out T t) where T : class, new() { return t = new T(); } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test<T>(out T t) where T : class, new() { T t1; NewMethod(out t, out t1); System.Console.WriteLine(t1.ToString()); } private void NewMethod<T>(out T t, out T t1) where T : class, new() { t1 = GetValue(out t); } private T GetValue<T>(out T t) where T : class, new() { return t = new T(); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod19() { var code = @"using System; using System.Collections.Generic; using System.Linq; unsafe class Program { void Test() { [|int i = 1;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; unsafe class Program { void Test() { NewMethod(); } private static void NewMethod() { int i = 1; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod20() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { unsafe void Test() { [|int i = 1;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { unsafe void Test() { NewMethod(); } private static unsafe void NewMethod() { int i = 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542677")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod21() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test() { unsafe { [|int i = 1;|] } } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test() { unsafe { NewMethod(); } } private static unsafe void NewMethod() { int i = 1; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod22() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test() { int i; [|int b = 10; if (b < 10) { i = 5; }|] i = 6; Console.WriteLine(i); } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test() { int i; i = NewMethod(i); i = 6; Console.WriteLine(i); } private static int NewMethod(int i) { int b = 10; if (b < 10) { i = 5; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod23() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { if (true) [|Console.WriteLine(args[0].ToString());|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { if (true) NewMethod(args); } private static void NewMethod(string[] args) { Console.WriteLine(args[0].ToString()); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod24() { var code = @"using System; class Program { static void Main(string[] args) { int y = [|int.Parse(args[0].ToString())|]; } }"; var expected = @"using System; class Program { static void Main(string[] args) { int y = GetY(args); } private static int GetY(string[] args) { return int.Parse(args[0].ToString()); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod25() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { if (([|new int[] { 1, 2, 3 }|]).Any()) { return; } } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { if ((NewMethod()).Any()) { return; } } private static int[] NewMethod() { return new int[] { 1, 2, 3 }; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod26() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { if ([|(new int[] { 1, 2, 3 })|].Any()) { return; } } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { if (NewMethod().Any()) { return; } } private static int[] NewMethod() { return (new int[] { 1, 2, 3 }); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod27() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test() { int i = 1; [|int b = 10; if (b < 10) { i = 5; }|] i = 6; Console.WriteLine(i); } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test() { int i = 1; i = NewMethod(i); i = 6; Console.WriteLine(i); } private static int NewMethod(int i) { int b = 10; if (b < 10) { i = 5; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod28() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { int Test() { [|return 1;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { int Test() { return NewMethod(); } private static int NewMethod() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod29() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { int Test() { int i = 0; [|if (i < 0) { return 1; } else { return 0; }|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { int Test() { int i = 0; return NewMethod(i); } private static int NewMethod(int i) { if (i < 0) { return 1; } else { return 0; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod30() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(out int i) { [|i = 10;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(out int i) { i = NewMethod(); } private static int NewMethod() { return 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod31() { var code = @"using System; using System.Collections.Generic; using System.Text; class Program { void Test() { StringBuilder builder = new StringBuilder(); [|builder.Append(""Hello""); builder.Append("" From ""); builder.Append("" Roslyn"");|] return builder.ToString(); } }"; var expected = @"using System; using System.Collections.Generic; using System.Text; class Program { void Test() { StringBuilder builder = new StringBuilder(); NewMethod(builder); return builder.ToString(); } private static void NewMethod(StringBuilder builder) { builder.Append(""Hello""); builder.Append("" From ""); builder.Append("" Roslyn""); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod32() { var code = @"using System; class Program { void Test() { int v = 0; Console.Write([|v|]); } }"; var expected = @"using System; class Program { void Test() { int v = 0; Console.Write(GetV(v)); } private static int GetV(int v) { return v; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(3792, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod33() { var code = @"using System; class Program { void Test() { int v = 0; while (true) { Console.Write([|v++|]); } } }"; var expected = @"using System; class Program { void Test() { int v = 0; while (true) { Console.Write(NewMethod(ref v)); } } private static int NewMethod(ref int v) { return v++; } }"; // this bug has two issues. one is "v" being not in the dataFlowIn and ReadInside collection (hence no method parameter) // and the other is binding not working for "v++" (hence object as return type) await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod34() { var code = @"using System; class Program { static void Main(string[] args) { int x = 1; int y = 2; int z = [|x + y|]; } } "; var expected = @"using System; class Program { static void Main(string[] args) { int x = 1; int y = 2; int z = GetZ(x, y); } private static int GetZ(int x, int y) { return x + y; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(538239, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538239")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod35() { var code = @"using System; class Program { static void Main(string[] args) { int[] r = [|new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }|]; } }"; var expected = @"using System; class Program { static void Main(string[] args) { int[] r = GetR(); } private static int[] GetR() { return new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod36() { var code = @"using System; class Program { static void Main(ref int i) { [|i = 1;|] } }"; var expected = @"using System; class Program { static void Main(ref int i) { i = NewMethod(); } private static int NewMethod() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod37() { var code = @"using System; class Program { static void Main(out int i) { [|i = 1;|] } }"; var expected = @"using System; class Program { static void Main(out int i) { i = NewMethod(); } private static int NewMethod() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538231, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538231")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod38() { var code = @"using System; class Program { static void Main(string[] args) { // int v = 0; // while (true) // { // NewMethod(v++); // NewMethod(ReturnVal(v++)); // } int unassigned; // extract // unassigned = ReturnVal(0); [|unassigned = unassigned + 10;|] // read // int newVar = unassigned; // write // unassigned = 0; } }"; var expected = @"using System; class Program { static void Main(string[] args) { // int v = 0; // while (true) // { // NewMethod(v++); // NewMethod(ReturnVal(v++)); // } int unassigned; // extract // unassigned = ReturnVal(0); unassigned = NewMethod(unassigned); // read // int newVar = unassigned; // write // unassigned = 0; } private static int NewMethod(int unassigned) { unassigned = unassigned + 10; return unassigned; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538231, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538231")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod39() { var code = @"using System; class Program { static void Main(string[] args) { // int v = 0; // while (true) // { // NewMethod(v++); // NewMethod(ReturnVal(v++)); // } int unassigned; // extract [|// unassigned = ReturnVal(0); unassigned = unassigned + 10; // read|] // int newVar = unassigned; // write // unassigned = 0; } }"; var expected = @"using System; class Program { static void Main(string[] args) { // int v = 0; // while (true) // { // NewMethod(v++); // NewMethod(ReturnVal(v++)); // } int unassigned; // extract unassigned = NewMethod(unassigned); // int newVar = unassigned; // write // unassigned = 0; } private static int NewMethod(int unassigned) { // unassigned = ReturnVal(0); unassigned = unassigned + 10; // read return unassigned; } }"; // current bottom-up re-writer makes re-attaching trivia half belongs to previous token // and half belongs to next token very hard. // for now, it won't be able to re-associate trivia belongs to next token. await TestExtractMethodAsync(code, expected); } [WorkItem(538303, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538303")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod40() { var code = @"class Program { static void Main(string[] args) { [|int x;|] } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(868414, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/868414")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodWithLeadingTrivia() { // ensure that the extraction doesn't result in trivia moving up a line: // // a //b // NewMethod(); await TestExtractMethodAsync( @"class C { void M() { // a // b [|System.Console.WriteLine();|] } }", @"class C { void M() { // a // b NewMethod(); } private static void NewMethod() { System.Console.WriteLine(); } }"); } [WorkItem(632351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/632351")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodFailForTypeInFromClause() { var code = @"class Program { static void Main(string[] args) { var z = from [|T|] x in e; } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(632351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/632351")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodFailForTypeInFromClause_1() { var code = @"class Program { static void Main(string[] args) { var z = from [|W.T|] x in e; } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(538314, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538314")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod41() { var code = @"class Program { static void Main(string[] args) { int x = 10; [|int y; if (x == 10) y = 5;|] Console.WriteLine(y); } }"; var expected = @"class Program { static void Main(string[] args) { int x = 10; int y = NewMethod(x); Console.WriteLine(y); } private static int NewMethod(int x) { int y; if (x == 10) y = 5; return y; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538327, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538327")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod42() { var code = @"using System; class Program { static void Main(string[] args) { int a, b; [|a = 5; b = 7;|] Console.Write(a + b); } }"; var expected = @"using System; class Program { static void Main(string[] args) { int a, b; NewMethod(out a, out b); Console.Write(a + b); } private static void NewMethod(out int a, out int b) { a = 5; b = 7; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538327, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538327")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod43() { var code = @"using System; class Program { static void Main(string[] args) { int a, b; [|a = 5; b = 7; int c; int d; int e, f; c = 1; d = 1; e = 1; f = 1;|] Console.Write(a + b); } }"; var expected = @"using System; class Program { static void Main(string[] args) { int a, b; NewMethod(out a, out b); Console.Write(a + b); } private static void NewMethod(out int a, out int b) { a = 5; b = 7; int c; int d; int e, f; c = 1; d = 1; e = 1; f = 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538328, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538328")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod44() { var code = @"using System; class Program { static void Main(string[] args) { int a; //modified in [|a = 1;|] /*data flow out*/ Console.Write(a); } }"; var expected = @"using System; class Program { static void Main(string[] args) { int a; //modified in a = NewMethod(); /*data flow out*/ Console.Write(a); } private static int NewMethod() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538393, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538393")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod45() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { /**/[|;|]/**/ } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { /**/ NewMethod();/**/ } private static void NewMethod() { ; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538393, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538393")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod46() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int x = 1; [|Goo(ref x);|] Console.WriteLine(x); } static void Goo(ref int x) { x = x + 1; } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int x = 1; x = NewMethod(x); Console.WriteLine(x); } private static int NewMethod(int x) { Goo(ref x); return x; } static void Goo(ref int x) { x = x + 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538399, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538399")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod47() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int x = 1; [|while (true) Console.WriteLine(x);|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int x = 1; NewMethod(x); } private static void NewMethod(int x) { while (true) Console.WriteLine(x); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538401")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod48() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int[] x = [|{ 1, 2, 3 }|]; } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int[] x = GetX(); } private static int[] GetX() { return new int[] { 1, 2, 3 }; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538405")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod49() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Goo(int GetX) { int x = [|1|]; } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Goo(int GetX) { int x = GetX1(); } private static int GetX1() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodNormalProperty() { var code = @" class Class { private static string name; public static string Names { get { return ""1""; } set { name = value; } } static void Goo(int i) { string str = [|Class.Names|]; } }"; var expected = @" class Class { private static string name; public static string Names { get { return ""1""; } set { name = value; } } static void Goo(int i) { string str = GetStr(); } private static string GetStr() { return Class.Names; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538932, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538932")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodAutoProperty() { var code = @" class Class { public string Name { get; set; } static void Main() { string str = new Class().[|Name|]; } }"; // given span is not an expression // selection validator should take care of this case var expected = @" class Class { public string Name { get; set; } static void Main() { string str = GetStr(); } private static string GetStr() { return new Class().Name; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538402, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538402")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix3994() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { byte x = [|1|]; } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { byte x = GetX(); } private static byte GetX() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538404, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538404")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix3996() { var code = @"class A<T> { class D : A<T> { } class B { } static D.B Goo() { return null; } class C<T2> { static void Bar() { D.B x = [|Goo()|]; } } }"; var expected = @"class A<T> { class D : A<T> { } class B { } static D.B Goo() { return null; } class C<T2> { static void Bar() { D.B x = GetX(); } private static B GetX() { return Goo(); } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task InsertionPoint() { var code = @"class Test { void Method(string i) { int y2 = [|1|]; } void Method(int i) { } }"; var expected = @"class Test { void Method(string i) { int y2 = GetY2(); } private static int GetY2() { return 1; } void Method(int i) { } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538980, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538980")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4757() { var code = @"class GenericMethod { void Method<T>(T t) { T a; [|a = t;|] } }"; var expected = @"class GenericMethod { void Method<T>(T t) { T a; a = NewMethod(t); } private static T NewMethod<T>(T t) { return t; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538980, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538980")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4757_2() { var code = @"class GenericMethod<T1> { void Method<T>(T t) { T a; T1 b; [|a = t; b = default(T1);|] } }"; var expected = @"class GenericMethod<T1> { void Method<T>(T t) { T a; T1 b; NewMethod(t, out a, out b); } private static void NewMethod<T>(T t, out T a, out T1 b) { a = t; b = default(T1); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538980, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538980")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4757_3() { var code = @"class GenericMethod { void Method<T, T1>(T t) { T1 a1; T a; [|a = t; a1 = default(T);|] } }"; var expected = @"class GenericMethod { void Method<T, T1>(T t) { T1 a1; T a; NewMethod(t, out a1, out a); } private static void NewMethod<T, T1>(T t, out T1 a1, out T a) { a = t; a1 = default(T); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538422, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538422")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4758() { var code = @"using System; class TestOutParameter { void Method(out int x) { x = 5; Console.Write([|x|]); } }"; var expected = @"using System; class TestOutParameter { void Method(out int x) { x = 5; Console.Write(GetX(x)); } private static int GetX(int x) { return x; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538422, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538422")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4758_2() { var code = @"class TestOutParameter { void Method(out int x) { x = 5; Console.Write([|x|]); } }"; var expected = @"class TestOutParameter { void Method(out int x) { x = 5; Console.Write(GetX(x)); } private static int GetX(int x) { return x; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538984, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538984")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4761() { var code = @"using System; class A { void Method() { System.Func<int, int> a = x => [|x * x|]; } }"; var expected = @"using System; class A { void Method() { System.Func<int, int> a = x => NewMethod(x); } private static int NewMethod(int x) { return x * x; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538997, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538997")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4779() { var code = @"using System; class Program { static void Main() { string s = ""; Func<string> f = [|s|].ToString; } } "; var expected = @"using System; class Program { static void Main() { string s = ""; Func<string> f = GetS(s).ToString; } private static string GetS(string s) { return s; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(538997, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538997")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4779_2() { var code = @"using System; class Program { static void Main() { string s = ""; var f = [|s|].ToString(); } } "; var expected = @"using System; class Program { static void Main() { string s = ""; var f = GetS(s).ToString(); } private static string GetS(string s) { return s; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(4780, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4780() { var code = @"using System; class Program { static void Main() { string s = ""; object f = (Func<string>)[|s.ToString|]; } }"; var expected = @"using System; class Program { static void Main() { string s = ""; object f = (Func<string>)GetToString(s); } private static Func<string> GetToString(string s) { return s.ToString; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(4780, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4780_2() { var code = @"using System; class Program { static void Main() { string s = ""; object f = (string)[|s.ToString()|]; } }"; var expected = @"using System; class Program { static void Main() { string s = ""; object f = (string)NewMethod(s); } private static string NewMethod(string s) { return s.ToString(); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(4782, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4782() { var code = @"class A<T> { class D : A<T[]> { } class B { } class C<T> { static void Goo<T>(T a) { T t = [|default(T)|]; } } }"; var expected = @"class A<T> { class D : A<T[]> { } class B { } class C<T> { static void Goo<T>(T a) { T t = GetT<T>(); } private static T GetT<T>() { return default(T); } } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(4782, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4782_2() { var code = @"class A<T> { class D : A<T[]> { } class B { } class C<T> { static void Goo() { D.B x = [|new D.B()|]; } } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(4791, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4791() { var code = @"class Program { delegate int Func(int a); static void Main(string[] args) { Func v = (int a) => [|a|]; } }"; var expected = @"class Program { delegate int Func(int a); static void Main(string[] args) { Func v = (int a) => GetA(a); } private static int GetA(int a) { return a; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539019, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539019")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4809() { var code = @"class Program { public Program() { [|int x = 2;|] } }"; var expected = @"class Program { public Program() { NewMethod(); } private static void NewMethod() { int x = 2; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539029, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539029")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4813() { var code = @"using System; class Program { public Program() { object o = [|new Program()|]; } }"; var expected = @"using System; class Program { public Program() { object o = GetO(); } private static Program GetO() { return new Program(); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538425")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4031() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { bool x = true, y = true, z = true; if (x) while (y) { } else [|while (z) { }|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { bool x = true, y = true, z = true; if (x) while (y) { } else NewMethod(z); } private static void NewMethod(bool z) { while (z) { } } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(527499, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527499")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix3992() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int x = 1; [|while (false) Console.WriteLine(x);|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int x = 1; NewMethod(x); } private static void NewMethod(int x) { while (false) Console.WriteLine(x); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539029, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539029")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4823() { var code = @"class Program { private double area = 1.0; public double Area { get { return area; } } public override string ToString() { return string.Format(""{0:F2}"", [|Area|]); } }"; var expected = @"class Program { private double area = 1.0; public double Area { get { return area; } } public override string ToString() { return string.Format(""{0:F2}"", GetArea()); } private double GetArea() { return Area; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538985, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538985")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4762() { var code = @"class Program { static void Main(string[] args) { //comments [|int x = 2;|] } } "; var expected = @"class Program { static void Main(string[] args) { //comments NewMethod(); } private static void NewMethod() { int x = 2; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(538966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538966")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4744() { var code = @"class Program { static void Main(string[] args) { [|int x = 2; //comments|] } } "; var expected = @"class Program { static void Main(string[] args) { NewMethod(); } private static void NewMethod() { int x = 2; //comments } } "; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoNoNoYesNoNo() { var code = @"using System; class Program { void Test1() { int i; [| if (int.Parse(""1"") > 0) { i = 10; } |] } }"; var expected = @"using System; class Program { void Test1() { int i; i = NewMethod(i); } private static int NewMethod(int i) { if (int.Parse(""1"") > 0) { i = 10; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoNoNoYesNoYes() { var code = @"using System; class Program { void Test2() { int i = 0; [| if (int.Parse(""1"") > 0) { i = 10; } |] } }"; var expected = @"using System; class Program { void Test2() { int i = 0; i = NewMethod(i); } private static int NewMethod(int i) { if (int.Parse(""1"") > 0) { i = 10; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoNoNoYesYesNo() { var code = @"using System; class Program { void Test3() { int i; while (i > 10) ; [| if (int.Parse(""1"") > 0) { i = 10; } |] } }"; var expected = @"using System; class Program { void Test3() { int i; while (i > 10) ; i = NewMethod(i); } private static int NewMethod(int i) { if (int.Parse(""1"") > 0) { i = 10; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoNoNoYesYesYes() { var code = @"using System; class Program { void Test4() { int i = 10; while (i > 10) ; [| if (int.Parse(""1"") > 0) { i = 10; } |] } }"; var expected = @"using System; class Program { void Test4() { int i = 10; while (i > 10) ; i = NewMethod(i); } private static int NewMethod(int i) { if (int.Parse(""1"") > 0) { i = 10; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoNoYesYesNoNo() { var code = @"using System; class Program { void Test4_1() { int i; [| if (int.Parse(""1"") > 0) { i = 10; Console.WriteLine(i); } |] } }"; var expected = @"using System; class Program { void Test4_1() { int i; i = NewMethod(); } private static int NewMethod() { int i; if (int.Parse(""1"") > 0) { i = 10; Console.WriteLine(i); } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoNoYesYesNoYes() { var code = @"using System; class Program { void Test4_2() { int i = 10; [| if (int.Parse(""1"") > 0) { i = 10; Console.WriteLine(i); } |] } }"; var expected = @"using System; class Program { void Test4_2() { int i = 10; i = NewMethod(i); } private static int NewMethod(int i) { if (int.Parse(""1"") > 0) { i = 10; Console.WriteLine(i); } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoNoYesYesYesNo() { var code = @"using System; class Program { void Test4_3() { int i; Console.WriteLine(i); [| if (int.Parse(""1"") > 0) { i = 10; Console.WriteLine(i); } |] } }"; var expected = @"using System; class Program { void Test4_3() { int i; Console.WriteLine(i); i = NewMethod(); } private static int NewMethod() { int i; if (int.Parse(""1"") > 0) { i = 10; Console.WriteLine(i); } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoNoYesYesYesYes() { var code = @"using System; class Program { void Test4_4() { int i = 10; Console.WriteLine(i); [| if (int.Parse(""1"") > 0) { i = 10; Console.WriteLine(i); } |] } }"; var expected = @"using System; class Program { void Test4_4() { int i = 10; Console.WriteLine(i); i = NewMethod(i); } private static int NewMethod(int i) { if (int.Parse(""1"") > 0) { i = 10; Console.WriteLine(i); } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoYesNoNoNoNo() { var code = @"using System; class Program { void Test5() { [| int i; |] } }"; await ExpectExtractMethodToFailAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoYesNoNoNoYes() { var code = @"using System; class Program { void Test6() { [| int i; |] i = 1; } }"; await ExpectExtractMethodToFailAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoYesNoYesNoNo() { var code = @"using System; class Program { void Test7() { [| int i; if (int.Parse(""1"") > 0) { i = 10; } |] } }"; var expected = @"using System; class Program { void Test7() { NewMethod(); } private static void NewMethod() { int i; if (int.Parse(""1"") > 0) { i = 10; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoYesNoYesNoYes() { var code = @"using System; class Program { void Test8() { [| int i; if (int.Parse(""1"") > 0) { i = 10; } |] i = 2; } }"; var expected = @"using System; class Program { void Test8() { int i = NewMethod(); i = 2; } private static int NewMethod() { int i; if (int.Parse(""1"") > 0) { i = 10; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoYesYesNoNoNo() { var code = @"using System; class Program { void Test9() { [| int i; Console.WriteLine(i); |] } }"; var expected = @"using System; class Program { void Test9() { NewMethod(); } private static void NewMethod() { int i; Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoYesYesNoNoYes() { var code = @"using System; class Program { void Test10() { [| int i; Console.WriteLine(i); |] i = 10; } }"; var expected = @"using System; class Program { void Test10() { int i; NewMethod(); i = 10; } private static void NewMethod() { int i; Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoYesYesYesNoNo() { var code = @"using System; class Program { void Test11() { [| int i; if (int.Parse(""1"") > 0) { i = 10; } Console.WriteLine(i); |] } }"; var expected = @"using System; class Program { void Test11() { NewMethod(); } private static void NewMethod() { int i; if (int.Parse(""1"") > 0) { i = 10; } Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoYesYesYesNoYes() { var code = @"using System; class Program { void Test12() { [| int i; if (int.Parse(""1"") > 0) { i = 10; } Console.WriteLine(i); |] i = 10; } }"; var expected = @"using System; class Program { void Test12() { int i = NewMethod(); i = 10; } private static int NewMethod() { int i; if (int.Parse(""1"") > 0) { i = 10; } Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesNoNoYesNoNo() { var code = @"using System; class Program { void Test13() { int i; [| i = 10; |] } }"; var expected = @"using System; class Program { void Test13() { int i; i = NewMethod(); } private static int NewMethod() { return 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesNoNoYesNoYes() { var code = @"using System; class Program { void Test14() { int i; [| i = 10; |] i = 1; } }"; var expected = @"using System; class Program { void Test14() { int i; i = NewMethod(); i = 1; } private static int NewMethod() { return 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesNoNoYesYesNo() { var code = @"using System; class Program { void Test15() { int i; Console.WriteLine(i); [| i = 10; |] } }"; var expected = @"using System; class Program { void Test15() { int i; Console.WriteLine(i); i = NewMethod(); } private static int NewMethod() { return 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesNoNoYesYesYes() { var code = @"using System; class Program { void Test16() { int i; [| i = 10; |] i = 10; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test16() { int i; i = NewMethod(); i = 10; Console.WriteLine(i); } private static int NewMethod() { return 10; } }"; await TestExtractMethodAsync(code, expected); } // dataflow in and out can be false for symbols in unreachable code // boolean indicates // dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: false, readOutside: false, writtenOutside: true [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesNoYesNoNoYes() { var code = @"using System.Collections.Generic; using System.Linq; namespace ConsoleApp1 { class Test { IEnumerable<object> Crash0(IEnumerable<object> enumerable) { [|while (true) ; enumerable.Select(e => """"); return enumerable;|] } } }"; var expected = @"using System.Collections.Generic; using System.Linq; namespace ConsoleApp1 { class Test { IEnumerable<object> Crash0(IEnumerable<object> enumerable) { return NewMethod(enumerable); } private static IEnumerable<object> NewMethod(IEnumerable<object> enumerable) { while (true) ; enumerable.Select(e => """"); return enumerable; } } }"; await TestExtractMethodAsync(code, expected); } // dataflow in and out can be false for symbols in unreachable code // boolean indicates // dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: false, readOutside: true, writtenOutside: true [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesNoYesNoYesYes() { var code = @"using System.Collections.Generic; using System.Linq; namespace ConsoleApp1 { class Test { IEnumerable<object> Crash0(IEnumerable<object> enumerable) { [|while (true) ; enumerable.Select(e => """");|] return enumerable; } } }"; var expected = @"using System.Collections.Generic; using System.Linq; namespace ConsoleApp1 { class Test { IEnumerable<object> Crash0(IEnumerable<object> enumerable) { enumerable = NewMethod(enumerable); return enumerable; } private static IEnumerable<object> NewMethod(IEnumerable<object> enumerable) { while (true) ; enumerable.Select(e => """"); return enumerable; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesNoYesYesNoNo() { var code = @"using System; class Program { void Test16_1() { int i; [| i = 10; Console.WriteLine(i); |] } }"; var expected = @"using System; class Program { void Test16_1() { int i; i = NewMethod(); } private static int NewMethod() { int i = 10; Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesNoYesYesNoYes() { var code = @"using System; class Program { void Test16_2() { int i = 10; [| i = 10; Console.WriteLine(i); |] } }"; var expected = @"using System; class Program { void Test16_2() { int i = 10; i = NewMethod(); } private static int NewMethod() { int i = 10; Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesNoYesYesYesNo() { var code = @"using System; class Program { void Test16_3() { int i; Console.WriteLine(i); [| i = 10; Console.WriteLine(i); |] } }"; var expected = @"using System; class Program { void Test16_3() { int i; Console.WriteLine(i); i = NewMethod(); } private static int NewMethod() { int i = 10; Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesNoYesYesYesYes() { var code = @"using System; class Program { void Test16_4() { int i = 10; Console.WriteLine(i); [| i = 10; Console.WriteLine(i); |] } }"; var expected = @"using System; class Program { void Test16_4() { int i = 10; Console.WriteLine(i); i = NewMethod(); } private static int NewMethod() { int i = 10; Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesYesNoYesNoNo() { var code = @"using System; class Program { void Test17() { [| int i = 10; |] } }"; var expected = @"using System; class Program { void Test17() { NewMethod(); } private static void NewMethod() { int i = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesYesNoYesNoYes() { var code = @"using System; class Program { void Test18() { [| int i = 10; |] i = 10; } }"; var expected = @"using System; class Program { void Test18() { int i = NewMethod(); i = 10; } private static int NewMethod() { return 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesYesYesYesNoNo() { var code = @"using System; class Program { void Test19() { [| int i = 10; Console.WriteLine(i); |] } }"; var expected = @"using System; class Program { void Test19() { NewMethod(); } private static void NewMethod() { int i = 10; Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesYesYesYesNoYes() { var code = @"using System; class Program { void Test20() { [| int i = 10; Console.WriteLine(i); |] i = 10; } }"; var expected = @"using System; class Program { void Test20() { int i; NewMethod(); i = 10; } private static void NewMethod() { int i = 10; Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoNoNoYesYesNo() { var code = @"using System; class Program { void Test21() { int i; [| if (int.Parse(""1"") > 10) { i = 1; } |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test21() { int i; i = NewMethod(i); Console.WriteLine(i); } private static int NewMethod(int i) { if (int.Parse(""1"") > 10) { i = 1; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoNoNoYesYesYes() { var code = @"using System; class Program { void Test22() { int i = 10; [| if (int.Parse(""1"") > 10) { i = 1; } |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test22() { int i = 10; i = NewMethod(i); Console.WriteLine(i); } private static int NewMethod(int i) { if (int.Parse(""1"") > 10) { i = 1; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoNoYesYesYesNo() { var code = @"using System; class Program { void Test22_1() { int i; [| if (int.Parse(""1"") > 10) { i = 1; Console.WriteLine(i); } |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test22_1() { int i; i = NewMethod(i); Console.WriteLine(i); } private static int NewMethod(int i) { if (int.Parse(""1"") > 10) { i = 1; Console.WriteLine(i); } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoNoYesYesYesYes() { var code = @"using System; class Program { void Test22_2() { int i = 10; [| if (int.Parse(""1"") > 10) { i = 1; Console.WriteLine(i); } |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test22_2() { int i = 10; i = NewMethod(i); Console.WriteLine(i); } private static int NewMethod(int i) { if (int.Parse(""1"") > 10) { i = 1; Console.WriteLine(i); } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoYesNoNoYesNo() { var code = @"using System; class Program { void Test23() { [| int i; |] Console.WriteLine(i); } }"; await ExpectExtractMethodToFailAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoYesNoNoYesYes() { var code = @"using System; class Program { void Test24() { [| int i; |] Console.WriteLine(i); i = 10; } }"; await ExpectExtractMethodToFailAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoYesNoYesYesNo() { var code = @"using System; class Program { void Test25() { [| int i; if (int.Parse(""1"") > 9) { i = 10; } |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test25() { int i = NewMethod(); Console.WriteLine(i); } private static int NewMethod() { int i; if (int.Parse(""1"") > 9) { i = 10; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoYesNoYesYesYes() { var code = @"using System; class Program { void Test26() { [| int i; if (int.Parse(""1"") > 9) { i = 10; } |] Console.WriteLine(i); i = 10; } }"; var expected = @"using System; class Program { void Test26() { int i = NewMethod(); Console.WriteLine(i); i = 10; } private static int NewMethod() { int i; if (int.Parse(""1"") > 9) { i = 10; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoYesYesNoYesNo() { var code = @"using System; class Program { void Test27() { [| int i; Console.WriteLine(i); |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test27() { int i = NewMethod(); Console.WriteLine(i); } private static int NewMethod() { int i; Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoYesYesNoYesYes() { var code = @"using System; class Program { void Test28() { [| int i; Console.WriteLine(i); |] Console.WriteLine(i); i = 10; } }"; var expected = @"using System; class Program { void Test28() { int i = NewMethod(); Console.WriteLine(i); i = 10; } private static int NewMethod() { int i; Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoYesYesYesYesNo() { var code = @"using System; class Program { void Test29() { [| int i; if (int.Parse(""1"") > 0) { i = 10; } Console.WriteLine(i); |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test29() { int i = NewMethod(); Console.WriteLine(i); } private static int NewMethod() { int i; if (int.Parse(""1"") > 0) { i = 10; } Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoYesYesYesYesYes() { var code = @"using System; class Program { void Test30() { [| int i; if (int.Parse(""1"") > 0) { i = 10; } Console.WriteLine(i); |] Console.WriteLine(i); i = 10; } }"; var expected = @"using System; class Program { void Test30() { int i = NewMethod(); Console.WriteLine(i); i = 10; } private static int NewMethod() { int i; if (int.Parse(""1"") > 0) { i = 10; } Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesYesNoNoYesYesNo() { var code = @"using System; class Program { void Test31() { int i; [| i = 10; |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test31() { int i; i = NewMethod(); Console.WriteLine(i); } private static int NewMethod() { return 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesYesNoNoYesYesYes() { var code = @"using System; class Program { void Test32() { int i; [| i = 10; |] Console.WriteLine(i); i = 10; } }"; var expected = @"using System; class Program { void Test32() { int i; i = NewMethod(); Console.WriteLine(i); i = 10; } private static int NewMethod() { return 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesYesNoYesYesYesNo() { var code = @"using System; class Program { void Test32_1() { int i; [| i = 10; Console.WriteLine(i); |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test32_1() { int i; i = NewMethod(); Console.WriteLine(i); } private static int NewMethod() { int i = 10; Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesYesNoYesYesYesYes() { var code = @"using System; class Program { void Test32_2() { int i = 10; [| i = 10; Console.WriteLine(i); |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test32_2() { int i = 10; i = NewMethod(); Console.WriteLine(i); } private static int NewMethod() { int i = 10; Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesYesYesNoYesYesNo() { var code = @"using System; class Program { void Test33() { [| int i = 10; |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test33() { int i = NewMethod(); Console.WriteLine(i); } private static int NewMethod() { return 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesYesYesNoYesYesYes() { var code = @"using System; class Program { void Test34() { [| int i = 10; |] Console.WriteLine(i); i = 10; } }"; var expected = @"using System; class Program { void Test34() { int i = NewMethod(); Console.WriteLine(i); i = 10; } private static int NewMethod() { return 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesYesYesYesYesYesNo() { var code = @"using System; class Program { void Test35() { [| int i = 10; Console.WriteLine(i); |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test35() { int i = NewMethod(); Console.WriteLine(i); } private static int NewMethod() { int i = 10; Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesYesYesYesYesYesYes() { var code = @"using System; class Program { void Test36() { [| int i = 10; Console.WriteLine(i); |] Console.WriteLine(i); i = 10; } }"; var expected = @"using System; class Program { void Test36() { int i = NewMethod(); Console.WriteLine(i); i = 10; } private static int NewMethod() { int i = 10; Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoNoNoYesNoNoNo() { var code = @"using System; class Program { void Test37() { int i; [| Console.WriteLine(i); |] } }"; var expected = @"using System; class Program { void Test37() { int i; NewMethod(i); } private static void NewMethod(int i) { Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoNoNoYesNoNoYes() { var code = @"using System; class Program { void Test38() { int i = 10; [| Console.WriteLine(i); |] } }"; var expected = @"using System; class Program { void Test38() { int i = 10; NewMethod(i); } private static void NewMethod(int i) { Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoNoNoYesNoYesNo() { var code = @"using System; class Program { void Test39() { int i; [| Console.WriteLine(i); |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test39() { int i; NewMethod(i); Console.WriteLine(i); } private static void NewMethod(int i) { Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoNoNoYesNoYesYes() { var code = @"using System; class Program { void Test40() { int i = 10; [| Console.WriteLine(i); |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test40() { int i = 10; NewMethod(i); Console.WriteLine(i); } private static void NewMethod(int i) { Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoNoNoYesYesNoNo() { var code = @"using System; class Program { void Test41() { int i; [| Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } |] } }"; var expected = @"using System; class Program { void Test41() { int i; i = NewMethod(i); } private static int NewMethod(int i) { Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoNoNoYesYesNoYes() { var code = @"using System; class Program { void Test42() { int i = 10; [| Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } |] } }"; var expected = @"using System; class Program { void Test42() { int i = 10; i = NewMethod(i); } private static int NewMethod(int i) { Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoNoNoYesYesYesNo() { var code = @"using System; class Program { void Test43() { int i; Console.WriteLine(i); [| Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } |] } }"; var expected = @"using System; class Program { void Test43() { int i; Console.WriteLine(i); i = NewMethod(i); } private static int NewMethod(int i) { Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoNoNoYesYesYesYes() { var code = @"using System; class Program { void Test44() { int i = 10; Console.WriteLine(i); [| Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } |] } }"; var expected = @"using System; class Program { void Test44() { int i = 10; Console.WriteLine(i); i = NewMethod(i); } private static int NewMethod(int i) { Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoYesNoYesYesNoNo() { var code = @"using System; class Program { void Test45() { int i; [| Console.WriteLine(i); i = 10; |] } }"; var expected = @"using System; class Program { void Test45() { int i; i = NewMethod(i); } private static int NewMethod(int i) { Console.WriteLine(i); i = 10; return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoYesNoYesYesNoYes() { var code = @"using System; class Program { void Test46() { int i = 10; [| Console.WriteLine(i); i = 10; |] } }"; var expected = @"using System; class Program { void Test46() { int i = 10; i = NewMethod(i); } private static int NewMethod(int i) { Console.WriteLine(i); i = 10; return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoYesNoYesYesYesNo() { var code = @"using System; class Program { void Test47() { int i; Console.WriteLine(i); [| Console.WriteLine(i); i = 10; |] } }"; var expected = @"using System; class Program { void Test47() { int i; Console.WriteLine(i); i = NewMethod(i); } private static int NewMethod(int i) { Console.WriteLine(i); i = 10; return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoYesNoYesYesYesYes() { var code = @"using System; class Program { void Test48() { int i = 10; Console.WriteLine(i); [| Console.WriteLine(i); i = 10; |] } }"; var expected = @"using System; class Program { void Test48() { int i = 10; Console.WriteLine(i); i = NewMethod(i); } private static int NewMethod(int i) { Console.WriteLine(i); i = 10; return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesYesNoNoYesYesYesNo() { var code = @"using System; class Program { void Test49() { int i; [| Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test49() { int i; i = NewMethod(i); Console.WriteLine(i); } private static int NewMethod(int i) { Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesYesNoNoYesYesYesYes() { var code = @"using System; class Program { void Test50() { int i = 10; [| Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test50() { int i = 10; i = NewMethod(i); Console.WriteLine(i); } private static int NewMethod(int i) { Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesYesYesNoYesYesYesNo() { var code = @"using System; class Program { void Test51() { int i; [| Console.WriteLine(i); i = 10; |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test51() { int i; i = NewMethod(i); Console.WriteLine(i); } private static int NewMethod(int i) { Console.WriteLine(i); i = 10; return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesYesYesNoYesYesYesYes() { var code = @"using System; class Program { void Test52() { int i = 10; [| Console.WriteLine(i); i = 10; |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test52() { int i = 10; i = NewMethod(i); Console.WriteLine(i); } private static int NewMethod(int i) { Console.WriteLine(i); i = 10; return i; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539049, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539049")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodInProperty1() { var code = @"class C2 { static public int Area { get { return 1; } } } class C3 { public static int Area { get { return [|C2.Area|]; } } } "; var expected = @"class C2 { static public int Area { get { return 1; } } } class C3 { public static int Area { get { return GetArea(); } } private static int GetArea() { return C2.Area; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(539049, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539049")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodInProperty2() { var code = @"class C3 { public static int Area { get { [|int i = 10; return i;|] } } } "; var expected = @"class C3 { public static int Area { get { return NewMethod(); } } private static int NewMethod() { return 10; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(539049, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539049")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodInProperty3() { var code = @"class C3 { public static int Area { set { [|int i = value;|] } } } "; var expected = @"class C3 { public static int Area { set { NewMethod(value); } } private static void NewMethod(int value) { int i = value; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(539029, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539029")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodProperty() { var code = @"class Program { private double area = 1.0; public double Area { get { return area; } } public override string ToString() { return string.Format(""{0:F2}"", [|Area|]); } } "; var expected = @"class Program { private double area = 1.0; public double Area { get { return area; } } public override string ToString() { return string.Format(""{0:F2}"", GetArea()); } private double GetArea() { return Area; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(539196, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539196")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodWithDeclareOneMoreVariablesInSameLineBeUsedAfter() { var code = @"class C { void M() { [|int x, y = 1;|] x = 4; Console.Write(x + y); } }"; var expected = @"class C { void M() { int x; int y = NewMethod(); x = 4; Console.Write(x + y); } private static int NewMethod() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539196, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539196")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodWithDeclareOneMoreVariablesInSameLineNotBeUsedAfter() { var code = @"class C { void M() { [|int x, y = 1;|] } }"; var expected = @"class C { void M() { NewMethod(); } private static void NewMethod() { int x, y = 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539214, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539214")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodForSplitOutStatementWithComments() { var code = @"class C { void M() { //start [|int x, y; x = 5; y = 10;|] //end Console.Write(x + y); } }"; var expected = @"class C { void M() { //start int x, y; NewMethod(out x, out y); //end Console.Write(x + y); } private static void NewMethod(out int x, out int y) { x = 5; y = 10; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539225")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug5098() { var code = @"class Program { static void Main(string[] args) { [|return;|] Console.Write(4); } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(539229, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539229")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug5107() { var code = @"class Program { static void Main(string[] args) { int i = 10; [|int j = j + i;|] Console.Write(i); Console.Write(j); } }"; var expected = @"class Program { static void Main(string[] args) { int i = 10; int j = NewMethod(i); Console.Write(i); Console.Write(j); } private static int NewMethod(int i) { return j + i; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539500")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task LambdaLiftedVariable1() { var code = @"class Program { delegate void Func(ref int i, int r); static void Main(string[] args) { int temp = 2; Func fnc = (ref int arg, int arg2) => { [|temp = arg = arg2;|] }; temp = 4; fnc(ref temp, 2); System.Console.WriteLine(temp); } }"; var expected = @"class Program { delegate void Func(ref int i, int r); static void Main(string[] args) { int temp = 2; Func fnc = (ref int arg, int arg2) => { NewMethod(out arg, arg2, out temp); }; temp = 4; fnc(ref temp, 2); System.Console.WriteLine(temp); } private static void NewMethod(out int arg, int arg2, out int temp) { temp = arg = arg2; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539488, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539488")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task LambdaLiftedVariable2() { var code = @"class Program { delegate void Action(); static void Main(string[] args) { int i = 0; Action query = null; if (i == 0) { query = () => { System.Console.WriteLine(i); }; } [|i = 3;|] query(); } }"; var expected = @"class Program { delegate void Action(); static void Main(string[] args) { int i = 0; Action query = null; if (i == 0) { query = () => { System.Console.WriteLine(i); }; } i = NewMethod(); query(); } private static int NewMethod() { return 3; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539531")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug5533() { var code = @"using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { [|TestDelegate testDel = (ref int x) => { x = 10; };|] int p = 2; testDel(ref p); Console.WriteLine(p); } }"; var expected = @"using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { TestDelegate testDel = NewMethod(); int p = 2; testDel(ref p); Console.WriteLine(p); } private static TestDelegate NewMethod() { return (ref int x) => { x = 10; }; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539531")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug5533_1() { var code = @"using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { [|TestDelegate testDel = (ref int x) => { int y = x; x = 10; };|] int p = 2; testDel(ref p); Console.WriteLine(p); } }"; var expected = @"using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { TestDelegate testDel = NewMethod(); int p = 2; testDel(ref p); Console.WriteLine(p); } private static TestDelegate NewMethod() { return (ref int x) => { int y = x; x = 10; }; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539531")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug5533_2() { var code = @"using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { TestDelegate testDel = (ref int x) => { [|int y = x; x = 10;|] }; int p = 2; testDel(ref p); Console.WriteLine(p); } }"; var expected = @"using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { TestDelegate testDel = (ref int x) => { x = NewMethod(x); }; int p = 2; testDel(ref p); Console.WriteLine(p); } private static int NewMethod(int x) { int y = x; x = 10; return x; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539531")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug5533_3() { var code = @"using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { [|TestDelegate testDel = delegate (ref int x) { x = 10; };|] int p = 2; testDel(ref p); Console.WriteLine(p); } }"; var expected = @"using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { TestDelegate testDel = NewMethod(); int p = 2; testDel(ref p); Console.WriteLine(p); } private static TestDelegate NewMethod() { return delegate (ref int x) { x = 10; }; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539859, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539859")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task LambdaLiftedVariable3() { var code = @"using System; class Program { static void Main(string[] args) { Action<int> F = x => { Action<int> F2 = x2 => { [|Console.WriteLine(args.Length + x2 + x);|] }; F2(x); }; F(args.Length); } }"; var expected = @"using System; class Program { static void Main(string[] args) { Action<int> F = x => { Action<int> F2 = x2 => { NewMethod(args, x, x2); }; F2(x); }; F(args.Length); } private static void NewMethod(string[] args, int x, int x2) { Console.WriteLine(args.Length + x2 + x); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539882, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539882")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug5982() { var code = @"using System; using System.Collections.Generic; class Program { static void Main(string[] args) { List<int> list = new List<int>(); Console.WriteLine([|list.Capacity|]); } }"; var expected = @"using System; using System.Collections.Generic; class Program { static void Main(string[] args) { List<int> list = new List<int>(); Console.WriteLine(GetCapacity(list)); } private static int GetCapacity(List<int> list) { return list.Capacity; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539932, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539932")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6041() { var code = @"using System; class Program { delegate R Del<in T, out R>(T arg); public void Goo() { Del<Exception, ArgumentException> d = (arg) => { return new ArgumentException(); }; [|d(new ArgumentException());|] } }"; var expected = @"using System; class Program { delegate R Del<in T, out R>(T arg); public void Goo() { Del<Exception, ArgumentException> d = (arg) => { return new ArgumentException(); }; NewMethod(d); } private static void NewMethod(Del<Exception, ArgumentException> d) { d(new ArgumentException()); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540183, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540183")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod50() { var code = @"class C { void Method() { while (true) { [|int i = 1; while (false) { int j = 1;|] } } } }"; var expected = @"class C { void Method() { while (true) { NewMethod(); } } private static void NewMethod() { int i = 1; while (false) { int j = 1; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod51() { var code = @"class C { void Method() { while (true) { switch(1) { case 1: [|int i = 10; break; case 2: int i2 = 20;|] break; } } } }"; var expected = @"class C { void Method() { while (true) { NewMethod(); } } private static void NewMethod() { switch (1) { case 1: int i = 10; break; case 2: int i2 = 20; break; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod52() { var code = @"class C { void Method() { [|int i = 1; while (false) { int j = 1;|] } } }"; var expected = @"class C { void Method() { NewMethod(); } private static void NewMethod() { int i = 1; while (false) { int j = 1; } } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539963, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539963")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod53() { var code = @"class Class { void Main() { Enum e = Enum.[|Field|]; } } enum Enum { }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(539964, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539964")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod54() { var code = @"class Class { void Main([|string|][] args) { } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(540072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540072")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6220() { var code = @"class C { void Main() { [| float f = 1.2f; |] System.Console.WriteLine(); } }"; var expected = @"class C { void Main() { NewMethod(); System.Console.WriteLine(); } private static void NewMethod() { float f = 1.2f; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540072")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6220_1() { var code = @"class C { void Main() { [| float f = 1.2f; // test |] System.Console.WriteLine(); } }"; var expected = @"class C { void Main() { NewMethod(); System.Console.WriteLine(); } private static void NewMethod() { float f = 1.2f; // test } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540071, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540071")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6219() { var code = @"class C { void Main() { float @float = 1.2f; [|@float = 1.44F;|] } }"; var expected = @"class C { void Main() { float @float = 1.2f; @float = NewMethod(); } private static float NewMethod() { return 1.44F; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540080, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540080")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6230() { var code = @"class C { void M() { int v =[| /**/1 + 2|]; System.Console.WriteLine(); } }"; var expected = @"class C { void M() { int v = GetV(); System.Console.WriteLine(); } private static int GetV() { return /**/1 + 2; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540080, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540080")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6230_1() { var code = @"class C { void M() { int v [|= /**/1 + 2|]; System.Console.WriteLine(); } }"; var expected = @"class C { void M() { NewMethod(); System.Console.WriteLine(); } private static void NewMethod() { int v = /**/1 + 2; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540052, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540052")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6197() { var code = @"using System; class Program { static void Main(string[] args) { Func<int, int> d = [|NewMethod|]; d.Invoke(2); } private static int NewMethod(int x) { return x * 2; } }"; var expected = @"using System; class Program { static void Main(string[] args) { Func<int, int> d = GetD(); d.Invoke(2); } private static Func<int, int> GetD() { return NewMethod; } private static int NewMethod(int x) { return x * 2; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(6277, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6277() { var code = @"using System; class Program { static void Main(string[] args) { [|int x; x = 1;|] return; int y = x; } }"; var expected = @"using System; class Program { static void Main(string[] args) { int x = NewMethod(); return; int y = x; } private static int NewMethod() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540151, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540151")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ArgumentlessReturnWithConstIfExpression() { var code = @"using System; class Program { void Test() { [|if (true) return;|] Console.WriteLine(); } }"; var expected = @"using System; class Program { void Test() { NewMethod(); return; Console.WriteLine(); } private static void NewMethod() { if (true) return; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540151, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540151")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ArgumentlessReturnWithConstIfExpression_1() { var code = @"using System; class Program { void Test() { if (true) [|if (true) return;|] Console.WriteLine(); } }"; var expected = @"using System; class Program { void Test() { if (true) { NewMethod(); return; } Console.WriteLine(); } private static void NewMethod() { if (true) return; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540151, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540151")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ArgumentlessReturnWithConstIfExpression_2() { var code = @"using System; class Program { void Test() { [|if (true) return;|] } }"; var expected = @"using System; class Program { void Test() { NewMethod(); } private static void NewMethod() { if (true) return; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540151, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540151")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ArgumentlessReturnWithConstIfExpression_3() { var code = @"using System; class Program { void Test() { if (true) [|if (true) return;|] } }"; var expected = @"using System; class Program { void Test() { if (true) { NewMethod(); return; } } private static void NewMethod() { if (true) return; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6313() { var code = @"using System; class Program { void Test(bool b) { [|if (b) { return; } Console.WriteLine();|] } }"; var expected = @"using System; class Program { void Test(bool b) { NewMethod(b); } private static void NewMethod(bool b) { if (b) { return; } Console.WriteLine(); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6313_1() { var code = @"using System; class Program { void Test(bool b) { [|if (b) { return; }|] Console.WriteLine(); } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6313_2() { var code = @"using System; class Program { int Test(bool b) { [|if (b) { return 1; } Console.WriteLine();|] } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6313_3() { var code = @"using System; class Program { void Test() { [|bool b = true; if (b) { return; } Action d = () => { if (b) { return; } Console.WriteLine(1); };|] } }"; var expected = @"using System; class Program { void Test() { NewMethod(); } private static void NewMethod() { bool b = true; if (b) { return; } Action d = () => { if (b) { return; } Console.WriteLine(1); }; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6313_4() { var code = @"using System; class Program { void Test() { [|Action d = () => { int i = 1; if (i > 10) { return; } Console.WriteLine(1); }; Action d2 = () => { int i = 1; if (i > 10) { return; } Console.WriteLine(1); };|] Console.WriteLine(1); } }"; var expected = @"using System; class Program { void Test() { NewMethod(); Console.WriteLine(1); } private static void NewMethod() { Action d = () => { int i = 1; if (i > 10) { return; } Console.WriteLine(1); }; Action d2 = () => { int i = 1; if (i > 10) { return; } Console.WriteLine(1); }; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6313_5() { var code = @"using System; class Program { void Test() { Action d = () => { [|int i = 1; if (i > 10) { return; } Console.WriteLine(1);|] }; } }"; var expected = @"using System; class Program { void Test() { Action d = () => { NewMethod(); }; } private static void NewMethod() { int i = 1; if (i > 10) { return; } Console.WriteLine(1); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6313_6() { var code = @"using System; class Program { void Test() { Action d = () => { [|int i = 1; if (i > 10) { return; }|] Console.WriteLine(1); }; } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(540170, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540170")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6333() { var code = @"using System; class Program { void Test() { Program p; [|p = new Program()|]; } }"; var expected = @"using System; class Program { void Test() { Program p; p = NewMethod(); } private static Program NewMethod() { return new Program(); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540216")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6393() { var code = @"using System; class Program { object Test<T>() { T abcd; [|abcd = new T()|]; return abcd; } }"; var expected = @"using System; class Program { object Test<T>() { T abcd; abcd = NewMethod<T>(); return abcd; } private static T NewMethod<T>() { return new T(); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540184, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540184")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6351() { var code = @"class Test { void method() { if (true) { for (int i = 0; i < 5; i++) { /*Begin*/ [|System.Console.WriteLine(); } System.Console.WriteLine();|] /*End*/ } } }"; var expected = @"class Test { void method() { if (true) { NewMethod(); /*End*/ } } private static void NewMethod() { for (int i = 0; i < 5; i++) { /*Begin*/ System.Console.WriteLine(); } System.Console.WriteLine(); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540184, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540184")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6351_1() { var code = @"class Test { void method() { if (true) { for (int i = 0; i < 5; i++) { /*Begin*/ [|System.Console.WriteLine(); } System.Console.WriteLine(); /*End*/|] } } }"; var expected = @"class Test { void method() { if (true) { NewMethod(); } } private static void NewMethod() { for (int i = 0; i < 5; i++) { /*Begin*/ System.Console.WriteLine(); } System.Console.WriteLine(); /*End*/ } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540184, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540184")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6351_2() { var code = @"class Test { void method() { if (true) [|{ for (int i = 0; i < 5; i++) { /*Begin*/ System.Console.WriteLine(); } System.Console.WriteLine(); /*End*/ }|] } }"; var expected = @"class Test { void method() { if (true) NewMethod(); } private static void NewMethod() { for (int i = 0; i < 5; i++) { /*Begin*/ System.Console.WriteLine(); } System.Console.WriteLine(); /*End*/ } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540333, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540333")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6560() { var code = @"using System; class Program { static void Main(string[] args) { string S = [|null|]; int Y = S.Length; } }"; var expected = @"using System; class Program { static void Main(string[] args) { string S = GetS(); int Y = S.Length; } private static string GetS() { return null; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540335")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6562() { var code = @"using System; class Program { int y = [|10|]; }"; var expected = @"using System; class Program { int y = GetY(); private static int GetY() { return 10; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540335")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6562_1() { var code = @"using System; class Program { const int i = [|10|]; }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(540335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540335")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6562_2() { var code = @"using System; class Program { Func<string> f = [|() => ""test""|]; }"; var expected = @"using System; class Program { Func<string> f = GetF(); private static Func<string> GetF() { return () => ""test""; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540335")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6562_3() { var code = @"using System; class Program { Func<string> f = () => [|""test""|]; }"; var expected = @"using System; class Program { Func<string> f = () => NewMethod(); private static string NewMethod() { return ""test""; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540361")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6598() { var code = @"using System; using System.Collections.Generic; using System.Linq; class { static void Main(string[] args) { [|Program|] } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(540372, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540372")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6613() { var code = @"#define A using System; class Program { static void Main(string[] args) { #if A [|Console.Write(5);|] #endif } }"; var expected = @"#define A using System; class Program { static void Main(string[] args) { #if A NewMethod(); #endif } private static void NewMethod() { Console.Write(5); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540396")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task InvalidSelection_MethodBody() { var code = @"using System; class Program { static void Main(string[] args) { void Method5(bool b1, bool b2) [|{ if (b1) { if (b2) return; Console.WriteLine(); } Console.WriteLine(); }|] } } "; await ExpectExtractMethodToFailAsync(code); } [WorkItem(541586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541586")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task StructThis() { var code = @"struct S { void Goo() { [|this = new S();|] } }"; var expected = @"struct S { void Goo() { NewMethod(); } private void NewMethod() { this = new S(); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(541627, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541627")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task DontUseConvertedTypeForImplicitNumericConversion() { var code = @"class T { void Goo() { int x1 = 5; long x2 = [|x1|]; } }"; var expected = @"class T { void Goo() { int x1 = 5; long x2 = GetX2(x1); } private static int GetX2(int x1) { return x1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(541668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541668")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BreakInSelection() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { string x1 = ""Hello""; switch (x1) { case null: int i1 = 10; break; default: switch (x1) { default: switch (x1) { [|default: int j1 = 99; i1 = 45; x1 = ""t""; string j2 = i1.ToString() + j1.ToString() + x1; break; } break; } break;|] } } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(541671, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541671")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task UnreachableCodeWithReturnStatement() { var code = @"class Program { static void Main(string[] args) { return; [|int i1 = 45; i1 = i1 + 10;|] return; } }"; var expected = @"class Program { static void Main(string[] args) { return; NewMethod(); return; } private static void NewMethod() { int i1 = 45; i1 = i1 + 10; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539862, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539862")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task DontBlindlyPutCapturedVariable1() { var code = @"using System; class Program { private static readonly int v = 5; delegate int Del(int i); static void Main(string[] args) { Ros.A a = new Ros.A(); Del d = (int x) => { [|a.F(x)|]; return x * v; }; d(3); } } namespace Ros { partial class A { public void F(int s) { } } }"; var expected = @"using System; class Program { private static readonly int v = 5; delegate int Del(int i); static void Main(string[] args) { Ros.A a = new Ros.A(); Del d = (int x) => { NewMethod(x, a); return x * v; }; d(3); } private static void NewMethod(int x, Ros.A a) { a.F(x); } } namespace Ros { partial class A { public void F(int s) { } } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539862, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539862")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task DontBlindlyPutCapturedVariable2() { var code = @"using System; class Program { private static readonly int v = 5; delegate int Del(int i); static void Main(string[] args) { Program p; Del d = (int x) => { [|p = null;|]; return x * v; }; d(3); } }"; var expected = @"using System; class Program { private static readonly int v = 5; delegate int Del(int i); static void Main(string[] args) { Program p; Del d = (int x) => { p = NewMethod(); ; return x * v; }; d(3); } private static Program NewMethod() { return null; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(541889, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541889")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task DontCrashOnRangeVariableSymbol() { var code = @"class Test { public void Linq1() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var lowNums = [|from|] n in numbers where n < 5 select n; } }"; await ExpectExtractMethodToFailAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractRangeVariable() { var code = @"using System.Linq; class Test { public void Linq1() { string[] array = null; var q = from string s in array select [|s|]; } }"; var expected = @"using System.Linq; class Test { public void Linq1() { string[] array = null; var q = from string s in array select GetS(s); } private static string GetS(string s) { return s; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542155, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542155")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task GenericWithErrorType() { var code = @"using Goo.Utilities; class Goo<T> { } class Bar { void gibberish() { Goo<[|Integer|]> x = null; x.IsEmpty(); } } namespace Goo.Utilities { internal static class GooExtensions { public static bool IsEmpty<T>(this Goo<T> source) { return false; } } }"; var expected = @"using Goo.Utilities; class Goo<T> { } class Bar { void gibberish() { Goo<Integer> x = NewMethod(); x.IsEmpty(); } private static Goo<Integer> NewMethod() { return null; } } namespace Goo.Utilities { internal static class GooExtensions { public static bool IsEmpty<T>(this Goo<T> source) { return false; } } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542105, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542105")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task NamedArgument() { var code = @"using System; class C { int this[int x = 5, int y = 7] { get { return 0; } set { } } void Goo() { var y = this[[|y|]: 1]; } }"; var expected = @"using System; class C { int this[int x = 5, int y = 7] { get { return 0; } set { } } void Goo() { var y = GetY(); } private int GetY() { return this[y: 1]; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542213, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542213")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task QueryExpressionVariable() { var code = @"using System; using System.Linq; using System.Collections.Generic; class Program { static void Main(string[] args) { var q2 = from a in Enumerable.Range(1, 2) from b in Enumerable.Range(1, 2) where ([|a == b|]) select a; } }"; var expected = @"using System; using System.Linq; using System.Collections.Generic; class Program { static void Main(string[] args) { var q2 = from a in Enumerable.Range(1, 2) from b in Enumerable.Range(1, 2) where (NewMethod(a, b)) select a; } private static bool NewMethod(int a, int b) { return a == b; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542465, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542465")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task IsExpression() { var code = @"using System; class Class1 { } class IsTest { static void Test(Class1 o) { var b = new Class1() is [|Class1|]; } static void Main() { } }"; var expected = @"using System; class Class1 { } class IsTest { static void Test(Class1 o) { var b = GetB(); } private static bool GetB() { return new Class1() is Class1; } static void Main() { } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542526, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542526")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TypeParametersInConstraint() { var code = @"using System; using System.Collections.Generic; class A { static void Goo<T, S>(T x) where T : IList<S> { var y = [|x.Count|]; } }"; var expected = @"using System; using System.Collections.Generic; class A { static void Goo<T, S>(T x) where T : IList<S> { var y = GetY<T, S>(x); } private static int GetY<T, S>(T x) where T : IList<S> { return x.Count; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542619")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task GlobalNamespaceInReturnType() { var code = @"class Program { class System { class Action { } } static global::System.Action a = () => { global::System.Console.WriteLine(); [|}|]; }"; var expected = @"class Program { class System { class Action { } } static global::System.Action a = GetA(); private static global::System.Action GetA() { return () => { global::System.Console.WriteLine(); }; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542582, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542582")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodExpandSelectionOnFor() { var code = @"using System; class Program { static void Main(string[] args) { for (int i = 0; i < 10; i++) [|{ Console.WriteLine(i);|] } } }"; var expected = @"using System; class Program { static void Main(string[] args) { for (int i = 0; i < 10; i++) NewMethod(i); } private static void NewMethod(int i) { Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodNotContainerOnFor() { var code = @"using System; class Program { static void Main(string[] args) { for (int i = 0; i < [|10|]; i++) ; } }"; var expected = @"using System; class Program { static void Main(string[] args) { for (int i = 0; i < NewMethod(); i++) ; } private static int NewMethod() { return 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodExpandSelectionOnForeach() { var code = @"using System; class Program { static void Main(string[] args) { foreach (var c in ""123"") [|{ Console.Write(c);|] } } }"; var expected = @"using System; class Program { static void Main(string[] args) { foreach (var c in ""123"") NewMethod(c); } private static void NewMethod(char c) { Console.Write(c); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodNotContainerOnForeach() { var code = @"using System; class Program { static void Main(string[] args) { foreach (var c in [|""123""|]) { Console.Write(c); } } }"; var expected = @"using System; class Program { static void Main(string[] args) { foreach (var c in NewMethod()) { Console.Write(c); } } private static string NewMethod() { return ""123""; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodNotContainerOnElseClause() { var code = @"using System; class Program { static void Main(string[] args) { if ([|true|]) { } else { } } }"; var expected = @"using System; class Program { static void Main(string[] args) { if (NewMethod()) { } else { } } private static bool NewMethod() { return true; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodExpandSelectionOnLabel() { var code = @"using System; class Program { static void Main(string[] args) { repeat: Console.WriteLine(""Roslyn"")[|;|] if (true) goto repeat; } }"; var expected = @"using System; class Program { static void Main(string[] args) { repeat: NewMethod(); if (true) goto repeat; } private static void NewMethod() { Console.WriteLine(""Roslyn""); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodNotContainerOnLabel() { var code = @"using System; class Program { static void Main(string[] args) { repeat: Console.WriteLine(""Roslyn""); if ([|true|]) goto repeat; } }"; var expected = @"using System; class Program { static void Main(string[] args) { repeat: Console.WriteLine(""Roslyn""); if (NewMethod()) goto repeat; } private static bool NewMethod() { return true; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodExpandSelectionOnSwitch() { var code = @"using System; class Program { static void Main(string[] args) { switch (args[0]) { case ""1"": Console.WriteLine(""one"")[|;|] break; default: Console.WriteLine(""other""); break; } } }"; var expected = @"using System; class Program { static void Main(string[] args) { switch (args[0]) { case ""1"": NewMethod(); break; default: Console.WriteLine(""other""); break; } } private static void NewMethod() { Console.WriteLine(""one""); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodNotContainerOnSwitch() { var code = @"using System; class Program { static void Main(string[] args) { switch ([|args[0]|]) { case ""1"": Console.WriteLine(""one""); break; default: Console.WriteLine(""other""); break; } } }"; var expected = @"using System; class Program { static void Main(string[] args) { switch (NewMethod(args)) { case ""1"": Console.WriteLine(""one""); break; default: Console.WriteLine(""other""); break; } } private static string NewMethod(string[] args) { return args[0]; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodExpandSelectionOnDo() { var code = @"using System; class Program { static void Main(string[] args) { do [|{ Console.WriteLine(""I don't like"");|] } while (DateTime.Now.DayOfWeek == DayOfWeek.Monday); } }"; var expected = @"using System; class Program { static void Main(string[] args) { do NewMethod(); while (DateTime.Now.DayOfWeek == DayOfWeek.Monday); } private static void NewMethod() { Console.WriteLine(""I don't like""); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodNotContainerOnDo() { var code = @"using System; class Program { static void Main(string[] args) { do { Console.WriteLine(""I don't like""); } while ([|DateTime.Now.DayOfWeek == DayOfWeek.Monday|]); } }"; var expected = @"using System; class Program { static void Main(string[] args) { do { Console.WriteLine(""I don't like""); } while (NewMethod()); } private static bool NewMethod() { return DateTime.Now.DayOfWeek == DayOfWeek.Monday; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodExpandSelectionOnWhile() { var code = @"using System; class Program { static void Main(string[] args) { while (true) [|{ ;|] } } }"; var expected = @"using System; class Program { static void Main(string[] args) { while (true) NewMethod(); } private static void NewMethod() { ; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodExpandSelectionOnStruct() { var code = @"using System; struct Goo { static Action a = () => { Console.WriteLine(); [|}|]; }"; var expected = @"using System; struct Goo { static Action a = GetA(); private static Action GetA() { return () => { Console.WriteLine(); }; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542619")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodIncludeGlobal() { var code = @"class Program { class System { class Action { } } static global::System.Action a = () => { global::System.Console.WriteLine(); [|}|]; static void Main(string[] args) { } }"; var expected = @"class Program { class System { class Action { } } static global::System.Action a = GetA(); private static global::System.Action GetA() { return () => { global::System.Console.WriteLine(); }; } static void Main(string[] args) { } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542582, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542582")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodExpandSelection() { var code = @"class Program { static void Main(string[] args) { for (int i = 0; i < 10; i++) [|{ System.Console.WriteLine(i);|] } } }"; var expected = @"class Program { static void Main(string[] args) { for (int i = 0; i < 10; i++) NewMethod(i); } private static void NewMethod(int i) { System.Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542594, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542594")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodRename1() { var code = @"class Program { static void Main() { [|var i = 42;|] var j = 42; } private static void NewMethod() { } private static void NewMethod2() { } }"; var expected = @"class Program { static void Main() { NewMethod1(); var j = 42; } private static void NewMethod1() { var i = 42; } private static void NewMethod() { } private static void NewMethod2() { } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542594, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542594")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodRename2() { var code = @"class Program { static void Main() { NewMethod1(); [|var j = 42;|] } private static void NewMethod1() { var i = 42; } private static void NewMethod() { } private static void NewMethod2() { } }"; var expected = @"class Program { static void Main() { NewMethod1(); NewMethod3(); } private static void NewMethod3() { var j = 42; } private static void NewMethod1() { var i = 42; } private static void NewMethod() { } private static void NewMethod2() { } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542632")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodInInteractive1() { var code = @"int i; [|i = 2|]; i = 3;"; var expected = @"int i; i = NewMethod(); int NewMethod() { return 2; } i = 3;"; await TestExtractMethodAsync(code, expected, parseOptions: Options.Script); } [WorkItem(542670, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542670")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TypeParametersInConstraint1() { var code = @"using System; using System.Collections.Generic; class A { static void Goo<T, S, U>(T x) where T : IList<S> where S : IList<U> { var y = [|x.Count|]; } }"; var expected = @"using System; using System.Collections.Generic; class A { static void Goo<T, S, U>(T x) where T : IList<S> where S : IList<U> { var y = GetY<T, S>(x); } private static int GetY<T, S>(T x) where T : IList<S> { return x.Count; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(706894, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/706894")] [WorkItem(543012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543012")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TypeParametersInConstraint2() { var code = @" using System; interface I<T> where T : IComparable<T> { int Count { get; } } class A { static void Goo<T, S>(S x) where S : I<T> where T : IComparable<T> { var y = [|x.Count|]; } } "; var expected = @" using System; interface I<T> where T : IComparable<T> { int Count { get; } } class A { static void Goo<T, S>(S x) where S : I<T> where T : IComparable<T> { var y = GetY<T, S>(x); } private static int GetY<T, S>(S x) where T : IComparable<T> where S : I<T> { return x.Count; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(706894, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/706894")] [WorkItem(543012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543012")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TypeParametersInConstraint3() { var code = @" using System; interface I<T> where T : class { int Count { get; } } class A { static void Goo<T, S>(S x) where S : I<T> where T : class { var y = [|x.Count|]; } } "; var expected = @" using System; interface I<T> where T : class { int Count { get; } } class A { static void Goo<T, S>(S x) where S : I<T> where T : class { var y = GetY<T, S>(x); } private static int GetY<T, S>(S x) where T : class where S : I<T> { return x.Count; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(543012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543012")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TypeParametersInConstraint4() { var code = @" using System; using System.Collections.Generic; interface I<T> where T : class { } interface I2<T1, T2> : I<T1> where T1 : class, IEnumerable<T2> where T2 : struct { int Count { get; } } class A { public virtual void Goo<T, S>(S x) where S : IList<I2<IEnumerable<T>, T>> where T : struct { } } class B : A { public override void Goo<T, S>(S x) { var y = [|x.Count|]; } } "; var expected = @" using System; using System.Collections.Generic; interface I<T> where T : class { } interface I2<T1, T2> : I<T1> where T1 : class, IEnumerable<T2> where T2 : struct { int Count { get; } } class A { public virtual void Goo<T, S>(S x) where S : IList<I2<IEnumerable<T>, T>> where T : struct { } } class B : A { public override void Goo<T, S>(S x) { var y = GetY<T, S>(x); } private static int GetY<T, S>(S x) where T : struct where S : IList<I2<IEnumerable<T>, T>> { return x.Count; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(543012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543012")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TypeParametersInConstraintBestEffort() { var code = @" using System; using System.Collections.Generic; using System.Linq; class A<T> { public virtual void Test<S>(S s) where S : T { } } class B : A<string> { public override void Test<S>(S s) { var t = [|s.ToString()|]; } } "; var expected = @" using System; using System.Collections.Generic; using System.Linq; class A<T> { public virtual void Test<S>(S s) where S : T { } } class B : A<string> { public override void Test<S>(S s) { var t = GetT(s); } private static string GetT<S>(S s) where S : string { return s.ToString(); } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(542672, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542672")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ConstructedTypes() { var code = @"using System; using System.Collections.Generic; class Program { static void Goo<T>() { List<T> x = new List<T>(); Action a = () => Console.WriteLine([|x.Count|]); } }"; var expected = @"using System; using System.Collections.Generic; class Program { static void Goo<T>() { List<T> x = new List<T>(); Action a = () => Console.WriteLine(GetCount(x)); } private static int GetCount<T>(List<T> x) { return x.Count; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542792, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542792")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TypeInDefault() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { Node<int, Exception> node = new Node<int, Exception>(); } } class Node<K, T> where T : new() { public K Key; public T Item; public Node<K, T> NextNode; public Node() { Key = default([|K|]); Item = new T(); NextNode = null; Console.WriteLine(Key); } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { Node<int, Exception> node = new Node<int, Exception>(); } } class Node<K, T> where T : new() { public K Key; public T Item; public Node<K, T> NextNode; public Node() { Key = NewMethod(); Item = new T(); NextNode = null; Console.WriteLine(Key); } private static K NewMethod() { return default(K); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542708, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542708")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Script_ArgumentException() { var code = @"using System; public static void GetNonVirtualMethod<TDelegate>( Type type, string name) { Type delegateType = typeof(TDelegate); var invoke = [|delegateType|].GetMethod(""Invoke""); }"; var expected = @"using System; public static void GetNonVirtualMethod<TDelegate>( Type type, string name) { Type delegateType = typeof(TDelegate); var invoke = GetDelegateType(delegateType).GetMethod(""Invoke""); } Type GetDelegateType(Type delegateType) { return delegateType; }"; await TestExtractMethodAsync(code, expected, parseOptions: Options.Script); } [WorkItem(529008, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529008")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ReadOutSideIsUnReachable() { var code = @"class Test { public static void Main() { string str = string.Empty; object obj; [|lock (new string[][] { new string[] { str }, new string[] { str } }) { obj = new object(); return; }|] System.Console.Write(obj); } }"; var expected = @"class Test { public static void Main() { string str = string.Empty; object obj; NewMethod(str, out obj); return; System.Console.Write(obj); } private static void NewMethod(string str, out object obj) { lock (new string[][] { new string[] { str }, new string[] { str } }) { obj = new object(); return; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(543186, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543186")] public async Task AnonymousTypePropertyName() { var code = @"class C { void M() { var x = new { [|String|] = true }; } }"; var expected = @"class C { void M() { NewMethod(); } private static void NewMethod() { var x = new { String = true }; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(543662, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543662")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ArgumentOfBaseConstrInit() { var code = @"class O { public O(int t) : base([|t|]) { } }"; var expected = @"class O { public O(int t) : base(GetT(t)) { } private static int GetT(int t) { return t; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task UnsafeType() { var code = @" unsafe class O { unsafe public O(int t) { [|t = 1;|] } }"; var expected = @" unsafe class O { unsafe public O(int t) { t = NewMethod(); } private static int NewMethod() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(544144, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544144")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task CastExpressionWithImplicitUserDefinedConversion() { var code = @" class C { static public implicit operator long(C i) { return 5; } static void Main() { C c = new C(); int y1 = [|(int)c|]; } }"; var expected = @" class C { static public implicit operator long(C i) { return 5; } static void Main() { C c = new C(); int y1 = GetY1(c); } private static int GetY1(C c) { return (int)c; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(544387, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544387")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task FixedPointerVariable() { var code = @" class Test { static int x = 0; unsafe static void Main() { fixed (int* p1 = &x) { int a1 = [|*p1|]; } } }"; var expected = @" class Test { static int x = 0; unsafe static void Main() { fixed (int* p1 = &x) { int a1 = GetA1(p1); } } private static unsafe int GetA1(int* p1) { return *p1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(544444, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544444")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task PointerDeclarationStatement() { var code = @" class Program { unsafe static void Main() { int* p1 = null; [|int* p2 = p1;|] } }"; var expected = @" class Program { unsafe static void Main() { int* p1 = null; NewMethod(p1); } private static unsafe void NewMethod(int* p1) { int* p2 = p1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(544446, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544446")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task PrecededByCastExpr() { var code = @" class Program { static void Main() { int i1 = (int)[|5L|]; } }"; var expected = @" class Program { static void Main() { int i1 = (int)NewMethod(); } private static long NewMethod() { return 5L; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542944")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExpressionWithLocalConst() { var code = @"class Program { static void Main(string[] args) { const string a = null; [|a = null;|] } }"; var expected = @"class Program { static void Main(string[] args) { const string a = null; a = NewMethod(a); } private static string NewMethod(string a) { a = null; return a; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542944")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExpressionWithLocalConst2() { var code = @"class Program { static void Main(string[] args) { const string a = null; [|a = null;|] } }"; var expected = @"class Program { static void Main(string[] args) { const string a = null; a = NewMethod(a); } private static string NewMethod(string a) { a = null; return a; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(544675, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544675")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task HiddenPosition() { var code = @"class Program { static void Main(string[] args) { const string a = null; [|a = null;|] } #line default #line hidden }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(530609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530609")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task NoCrashInteractive() { var code = @"[|if (true) { }|]"; var expected = @"NewMethod(); void NewMethod() { if (true) { } }"; await TestExtractMethodAsync(code, expected, parseOptions: new CSharpParseOptions(kind: SourceCodeKind.Script)); } [WorkItem(530322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530322")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodShouldNotBreakFormatting() { var code = @"class C { void M(int i, int j, int k) { M(0, [|1|], 2); } }"; var expected = @"class C { void M(int i, int j, int k) { M(0, NewMethod(), 2); } private static int NewMethod() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(604389, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/604389")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestExtractLiteralExpression() { var code = @"class Program { static void Main() { var c = new C { X = { Y = { [|1|] } } }; } } class C { public dynamic X; }"; var expected = @"class Program { static void Main() { var c = new C { X = { Y = { NewMethod() } } }; } private static int NewMethod() { return 1; } } class C { public dynamic X; }"; await TestExtractMethodAsync(code, expected); } [WorkItem(604389, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/604389")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestExtractCollectionInitializer() { var code = @"class Program { static void Main() { var c = new C { X = { Y = [|{ 1 }|] } }; } } class C { public dynamic X; }"; var expected = @"class Program { static void Main() { var c = GetC(); } private static C GetC() { return new C { X = { Y = { 1 } } }; } } class C { public dynamic X; }"; await TestExtractMethodAsync(code, expected); } [WorkItem(854662, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/854662")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestExtractCollectionInitializer2() { var code = @"using System; using System.Collections.Generic; class Program { public Dictionary<int, int> A { get; private set; } static int Main(string[] args) { int a = 0; return new Program { A = { { [|a + 2|], 0 } } }.A.Count; } }"; var expected = @"using System; using System.Collections.Generic; class Program { public Dictionary<int, int> A { get; private set; } static int Main(string[] args) { int a = 0; return new Program { A = { { NewMethod(a), 0 } } }.A.Count; } private static int NewMethod(int a) { return a + 2; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(530267, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530267")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestCoClassImplicitConversion() { var code = @"using System; using System.Runtime.InteropServices; [CoClass(typeof(C))] [ComImport] [Guid(""8D3A7A55-A8F5-4669-A5AD-996A3EB8F2ED"")] interface I { } class C : I { static void Main() { [|new I()|]; // Extract Method } }"; var expected = @"using System; using System.Runtime.InteropServices; [CoClass(typeof(C))] [ComImport] [Guid(""8D3A7A55-A8F5-4669-A5AD-996A3EB8F2ED"")] interface I { } class C : I { static void Main() { NewMethod(); // Extract Method } private static I NewMethod() { return new I(); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(530710, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530710")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestOverloadResolution() { var code = @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(object y, Action<string> x) { Console.WriteLine(1); } static void Outer(string y, Action<int> x) { Console.WriteLine(2); } static void Main() { Outer(null, y => Inner(x => { [|x|].Ex(); }, y)); // Prints 1 } } static class E { public static void Ex(this int x) { } }"; var expected = @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(object y, Action<string> x) { Console.WriteLine(1); } static void Outer(string y, Action<int> x) { Console.WriteLine(2); } static void Main() { Outer(null, (Action<string>)(y => Inner(x => { GetX(x).Ex(); }, y))); // Prints 1 } private static string GetX(string x) { return x; } } static class E { public static void Ex(this int x) { } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(530710, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530710")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestOverloadResolution1() { var code = @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(object y, Action<string> x) { Console.WriteLine(1); } static void Outer(string y, Action<int> x) { Console.WriteLine(2); } static void Main() { Outer(null, y => Inner(x => { [|x.Ex()|]; }, y)); // Prints 1 } } static class E { public static void Ex(this int x) { } }"; var expected = @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(object y, Action<string> x) { Console.WriteLine(1); } static void Outer(string y, Action<int> x) { Console.WriteLine(2); } static void Main() { Outer(null, (Action<string>)(y => Inner(x => { NewMethod(x); }, y))); // Prints 1 } private static void NewMethod(string x) { x.Ex(); } } static class E { public static void Ex(this int x) { } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(530710, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530710")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestOverloadResolution2() { var code = @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(object y, Action<string> x) { Console.WriteLine(1); } static void Outer(string y, Action<int> x) { Console.WriteLine(2); } static void Main() { Outer(null, y => Inner(x => { [|x.Ex();|] }, y)); // Prints 1 } } static class E { public static void Ex(this int x) { } }"; var expected = @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(object y, Action<string> x) { Console.WriteLine(1); } static void Outer(string y, Action<int> x) { Console.WriteLine(2); } static void Main() { Outer(null, (Action<string>)(y => Inner(x => { NewMethod(x); }, y))); // Prints 1 } private static void NewMethod(string x) { x.Ex(); } } static class E { public static void Ex(this int x) { } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(731924, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/731924")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestTreatEnumSpecial() { var code = @"using System; class Program { public enum A { A1, A2 } static void Main(string[] args) { A a = A.A1; [|Console.WriteLine(a);|] } }"; var expected = @"using System; class Program { public enum A { A1, A2 } static void Main(string[] args) { A a = A.A1; NewMethod(a); } private static void NewMethod(A a) { Console.WriteLine(a); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(756222, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756222")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestReturnStatementInAsyncMethod() { var code = @"using System.Threading.Tasks; class C { async Task<int> M() { await Task.Yield(); [|return 3;|] } }"; var expected = @"using System.Threading.Tasks; class C { async Task<int> M() { await Task.Yield(); return NewMethod(); } private static int NewMethod() { return 3; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(574576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/574576")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestAsyncMethodWithRefOrOutParameters() { var code = @"using System.Threading.Tasks; class C { public async void Goo() { [|var q = 1; var p = 2; await Task.Yield();|] var r = q; var s = p; } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(1025272, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1025272")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestAsyncMethodWithWellKnownValueType() { var code = @"using System; using System.Threading; using System.Threading.Tasks; class Program { public async Task Hello() { var cancellationToken = CancellationToken.None; [|var i = await Task.Run(() => { Console.WriteLine(); cancellationToken.ThrowIfCancellationRequested(); return 1; }, cancellationToken);|] cancellationToken.ThrowIfCancellationRequested(); Console.WriteLine(i); } }"; var expected = @"using System; using System.Threading; using System.Threading.Tasks; class Program { public async Task Hello() { var cancellationToken = CancellationToken.None; int i = await NewMethod(ref cancellationToken); cancellationToken.ThrowIfCancellationRequested(); Console.WriteLine(i); } private static async Task<int> NewMethod(ref CancellationToken cancellationToken) { return await Task.Run(() => { Console.WriteLine(); cancellationToken.ThrowIfCancellationRequested(); return 1; }, cancellationToken); } }"; await ExpectExtractMethodToFailAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestAsyncMethodWithWellKnownValueType1() { var code = @"using System; using System.Threading; using System.Threading.Tasks; class Program { public async Task Hello() { var cancellationToken = CancellationToken.None; [|var i = await Task.Run(() => { Console.WriteLine(); cancellationToken = CancellationToken.None; return 1; }, cancellationToken);|] cancellationToken.ThrowIfCancellationRequested(); Console.WriteLine(i); } }"; await ExpectExtractMethodToFailAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestDontPutOutOrRefForStructOff() { var code = @"using System.Threading.Tasks; namespace ClassLibrary9 { public struct S { public int I; } public class Class1 { private async Task<int> Test() { S s = new S(); s.I = 10; [|int i = await Task.Run(() => { var i2 = s.I; return Test(); });|] return i; } } }"; await ExpectExtractMethodToFailAsync(code, dontPutOutOrRefOnStruct: false); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestDontPutOutOrRefForStructOn() { var code = @"using System.Threading.Tasks; namespace ClassLibrary9 { public struct S { public int I; } public class Class1 { private async Task<int> Test() { S s = new S(); s.I = 10; [|int i = await Task.Run(() => { var i2 = s.I; return Test(); });|] return i; } } }"; var expected = @"using System.Threading.Tasks; namespace ClassLibrary9 { public struct S { public int I; } public class Class1 { private async Task<int> Test() { S s = new S(); s.I = 10; int i = await NewMethod(s); return i; } private async Task<int> NewMethod(S s) { return await Task.Run(() => { var i2 = s.I; return Test(); }); } } }"; await TestExtractMethodAsync(code, expected, dontPutOutOrRefOnStruct: true); } [Theory] [InlineData("add", "remove")] [InlineData("remove", "add")] [WorkItem(17474, "https://github.com/dotnet/roslyn/issues/17474")] [Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestExtractMethodEventAccessorUnresolvedName(string testedAccessor, string untestedAccessor) { // This code intentionally omits a 'using System;' var code = $@"namespace ClassLibrary9 {{ public class Class {{ public event EventHandler Event {{ {testedAccessor} {{ [|throw new NotImplementedException();|] }} {untestedAccessor} {{ throw new NotImplementedException(); }} }} }} }}"; var expected = $@"namespace ClassLibrary9 {{ public class Class {{ public event EventHandler Event {{ {testedAccessor} {{ NewMethod(); }} {untestedAccessor} {{ throw new NotImplementedException(); }} }} private static void NewMethod() {{ throw new NotImplementedException(); }} }} }}"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(19958, "https://github.com/dotnet/roslyn/issues/19958")] public async Task TestExtractMethodRefPassThrough() { var code = @"using System; namespace ClassLibrary9 { internal class ClassExtensions { public static int OtherMethod(ref int x) => x; public static void Method(ref int x) => Console.WriteLine(OtherMethod(ref [|x|])); } }"; var expected = @"using System; namespace ClassLibrary9 { internal class ClassExtensions { public static int OtherMethod(ref int x) => x; public static void Method(ref int x) => Console.WriteLine(OtherMethod(ref $x$)); public static ref int NewMethod(ref int x) { return ref x; } } }"; await TestExtractMethodAsync(code, expected, temporaryFailing: true); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(19958, "https://github.com/dotnet/roslyn/issues/19958")] public async Task TestExtractMethodRefPassThroughDuplicateVariable() { var code = @"using System; namespace ClassLibrary9 { internal interface IClass { bool InterfaceMethod(ref Guid x, out IOtherClass y); } internal interface IOtherClass { bool OtherInterfaceMethod(); } internal static class ClassExtensions { public static void Method(this IClass instance, Guid guid) { var r = instance.InterfaceMethod(ref [|guid|], out IOtherClass guid); if (!r) return; r = guid.OtherInterfaceMethod(); if (r) throw null; } } }"; var expected = @"using System; namespace ClassLibrary9 { internal interface IClass { bool InterfaceMethod(ref Guid x, out IOtherClass y); } internal interface IOtherClass { bool OtherInterfaceMethod(); } internal static class ClassExtensions { public static void Method(this IClass instance, Guid guid) { var r = instance.InterfaceMethod(ref NewMethod(ref guid), out IOtherClass guid); if (!r) return; r = guid.OtherInterfaceMethod(); if (r) throw null; } public static ref Guid NewMethod(ref Guid guid) { return ref guid; } } }"; await TestExtractMethodAsync(code, expected, temporaryFailing: true); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod_Argument1() { var service = new CSharpExtractMethodService(); Assert.NotNull(await Record.ExceptionAsync(async () => { var tree = await service.ExtractMethodAsync(document: null, textSpan: default, localFunction: false, options: null, CancellationToken.None); })); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod_Argument2() { var solution = new AdhocWorkspace().CurrentSolution; var projectId = ProjectId.CreateNewId(); var project = solution.AddProject(projectId, "Project", "Project.dll", LanguageNames.CSharp).GetProject(projectId); var document = project.AddMetadataReference(TestMetadata.Net451.mscorlib) .AddDocument("Document", SourceText.From("")); var service = new CSharpExtractMethodService() as IExtractMethodService; await service.ExtractMethodAsync(document, textSpan: default, localFunction: false); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ExtractMethod)] [Trait(Traits.Feature, Traits.Features.Interactive)] public void ExtractMethodCommandDisabledInSubmission() { using var workspace = TestWorkspace.Create(XElement.Parse(@" <Workspace> <Submission Language=""C#"" CommonReferences=""true""> typeof(string).$$Name </Submission> </Workspace> "), workspaceKind: WorkspaceKind.Interactive, composition: EditorTestCompositions.EditorFeaturesWpf); // Force initialization. workspace.GetOpenDocumentIds().Select(id => workspace.GetTestDocument(id).GetTextView()).ToList(); var textView = workspace.Documents.Single().GetTextView(); var handler = workspace.ExportProvider.GetCommandHandler<ExtractMethodCommandHandler>(PredefinedCommandHandlerNames.ExtractMethod, ContentTypeNames.CSharpContentType); var state = handler.GetCommandState(new ExtractMethodCommandArgs(textView, textView.TextBuffer)); Assert.True(state.IsUnspecified); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(18347, "https://github.com/dotnet/roslyn/issues/18347")] public async Task ExtractMethodUnreferencedLocalFunction1() { var code = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { [|int localValue = arg;|] int LocalCapture() => arg; } } }"; var expected = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { NewMethod(arg); int LocalCapture() => arg; } private static void NewMethod(int arg) { int localValue = arg; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(18347, "https://github.com/dotnet/roslyn/issues/18347")] public async Task ExtractMethodUnreferencedLocalFunction2() { var code = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { int LocalCapture() => arg; [|int localValue = arg;|] } } }"; var expected = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { int LocalCapture() => arg; NewMethod(arg); } private static void NewMethod(int arg) { int localValue = arg; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(18347, "https://github.com/dotnet/roslyn/issues/18347")] public async Task ExtractMethodUnreferencedLocalFunction3() { var code = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { [|arg = arg + 3;|] int LocalCapture() => arg; } } }"; var expected = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { arg = NewMethod(arg); int LocalCapture() => arg; } private static int NewMethod(int arg) { arg = arg + 3; return arg; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(18347, "https://github.com/dotnet/roslyn/issues/18347")] public async Task ExtractMethodUnreferencedLocalFunction4() { var code = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { int LocalCapture() => arg; [|arg = arg + 3;|] } } }"; var expected = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { int LocalCapture() => arg; arg = NewMethod(arg); } private static int NewMethod(int arg) { arg = arg + 3; return arg; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(18347, "https://github.com/dotnet/roslyn/issues/18347")] public async Task ExtractMethodUnreferencedLocalFunction5() { var code = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { [|arg = arg + 3;|] arg = 1; int LocalCapture() => arg; } } }"; var expected = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { arg = NewMethod(arg); arg = 1; int LocalCapture() => arg; } private static int NewMethod(int arg) { arg = arg + 3; return arg; } } }"; await TestExtractMethodAsync(code, expected); } [Theory] [InlineData("LocalCapture();")] [InlineData("System.Func<int> function = LocalCapture;")] [InlineData("System.Func<int> function = () => LocalCapture();")] [Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(18347, "https://github.com/dotnet/roslyn/issues/18347")] public async Task ExtractMethodFlowsToLocalFunction1(string usageSyntax) { var code = $@"namespace ExtractMethodCrashRepro {{ public static class SomeClass {{ private static void Repro( int arg ) {{ [|arg = arg + 3;|] {usageSyntax} int LocalCapture() => arg; }} }} }}"; var expected = $@"namespace ExtractMethodCrashRepro {{ public static class SomeClass {{ private static void Repro( int arg ) {{ arg = NewMethod(arg); {usageSyntax} int LocalCapture() => arg; }} private static int NewMethod(int arg) {{ arg = arg + 3; return arg; }} }} }}"; await TestExtractMethodAsync(code, expected); } [Theory] [InlineData("LocalCapture();")] [InlineData("System.Func<int> function = LocalCapture;")] [InlineData("System.Func<int> function = () => LocalCapture();")] [Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(18347, "https://github.com/dotnet/roslyn/issues/18347")] public async Task ExtractMethodFlowsToLocalFunction2(string usageSyntax) { var code = $@"namespace ExtractMethodCrashRepro {{ public static class SomeClass {{ private static void Repro( int arg ) {{ int LocalCapture() => arg; [|arg = arg + 3;|] {usageSyntax} }} }} }}"; var expected = $@"namespace ExtractMethodCrashRepro {{ public static class SomeClass {{ private static void Repro( int arg ) {{ int LocalCapture() => arg; arg = NewMethod(arg); {usageSyntax} }} private static int NewMethod(int arg) {{ arg = arg + 3; return arg; }} }} }}"; await TestExtractMethodAsync(code, expected); } /// <summary> /// This test verifies that Extract Method works properly when the region to extract references a local /// function, the local function uses an unassigned but wholly local variable. /// </summary> [Theory] [InlineData("LocalCapture();")] [InlineData("System.Func<int> function = LocalCapture;")] [InlineData("System.Func<int> function = () => LocalCapture();")] [Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(18347, "https://github.com/dotnet/roslyn/issues/18347")] public async Task ExtractMethodFlowsToLocalFunctionWithUnassignedLocal(string usageSyntax) { var code = $@"namespace ExtractMethodCrashRepro {{ public static class SomeClass {{ private static void Repro( int arg ) {{ int local; int LocalCapture() => arg + local; [|arg = arg + 3;|] {usageSyntax} }} }} }}"; var expected = $@"namespace ExtractMethodCrashRepro {{ public static class SomeClass {{ private static void Repro( int arg ) {{ int local; int LocalCapture() => arg + local; arg = NewMethod(arg); {usageSyntax} }} private static int NewMethod(int arg) {{ arg = arg + 3; return arg; }} }} }}"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(18347, "https://github.com/dotnet/roslyn/issues/18347")] public async Task ExtractMethodDoesNotFlowToLocalFunction1() { var code = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { [|arg = arg + 3;|] arg = 1; int LocalCapture() => arg; } } }"; var expected = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { arg = NewMethod(arg); arg = 1; int LocalCapture() => arg; } private static int NewMethod(int arg) { arg = arg + 3; return arg; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestUnreachableCodeModifiedInside() { var code = @"using System.Collections.Generic; using System.Linq; namespace ConsoleApp1 { class Test { IEnumerable<object> Crash0(IEnumerable<object> enumerable) { [|while (true) ; enumerable = null; var i = enumerable.Any(); return enumerable;|] } } }"; var expected = @"using System.Collections.Generic; using System.Linq; namespace ConsoleApp1 { class Test { IEnumerable<object> Crash0(IEnumerable<object> enumerable) { return NewMethod(ref enumerable); } private static IEnumerable<object> NewMethod(ref IEnumerable<object> enumerable) { while (true) ; enumerable = null; var i = enumerable.Any(); return enumerable; } } }"; // allowMovingDeclaration: false is default behavior on VS. // it doesn't affect result mostly but it does affect for symbols in unreachable code since // data flow in and out for the symbol is always set to false await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestUnreachableCodeModifiedOutside() { var code = @"using System.Collections.Generic; using System.Linq; namespace ConsoleApp1 { class Test { IEnumerable<object> Crash0(IEnumerable<object> enumerable) { [|while (true) ; var i = enumerable.Any();|] enumerable = null; return enumerable; } } }"; var expected = @"using System.Collections.Generic; using System.Linq; namespace ConsoleApp1 { class Test { IEnumerable<object> Crash0(IEnumerable<object> enumerable) { NewMethod(enumerable); enumerable = null; return enumerable; } private static void NewMethod(IEnumerable<object> enumerable) { while (true) ; var i = enumerable.Any(); } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestUnreachableCodeModifiedBoth() { var code = @"using System.Collections.Generic; using System.Linq; namespace ConsoleApp1 { class Test { IEnumerable<object> Crash0(IEnumerable<object> enumerable) { [|while (true) ; enumerable = null; var i = enumerable.Any();|] enumerable = null; return enumerable; } } }"; var expected = @"using System.Collections.Generic; using System.Linq; namespace ConsoleApp1 { class Test { IEnumerable<object> Crash0(IEnumerable<object> enumerable) { enumerable = NewMethod(enumerable); enumerable = null; return enumerable; } private static IEnumerable<object> NewMethod(IEnumerable<object> enumerable) { while (true) ; enumerable = null; var i = enumerable.Any(); return enumerable; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestLocalFunctionParameters() { var code = @"using System.Collections.Generic; using System.Linq; namespace ConsoleApp1 { class Test { public void Bar(int value) { void Local(int value2) { [|Bar(value, value2);|] } } } }"; var expected = @"using System.Collections.Generic; using System.Linq; namespace ConsoleApp1 { class Test { public void Bar(int value) { void Local(int value2) { NewMethod(value, value2); } } private void NewMethod(int value, int value2) { Bar(value, value2); } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestDataFlowInButNoReadInside() { var code = @"using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp39 { class Program { void Method(out object test) { test = null; var a = test != null; [|if (a) { return; } if (A == a) { test = new object(); }|] } } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp39 { class Program { void Method(out object test) { test = null; var a = test != null; NewMethod(ref test, a); } private static void NewMethod(ref object test, bool a) { if (a) { return; } if (A == a) { test = new object(); } } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task AllowBestEffortForUnknownVariableDataFlow() { var code = @" class Program { void Method(out object test) { test = null; var a = test != null; [|if (a) { return; } if (A == a) { test = new object(); }|] } }"; var expected = @" class Program { void Method(out object test) { test = null; var a = test != null; NewMethod(ref test, a); } private static void NewMethod(ref object test, bool a) { if (a) { return; } if (A == a) { test = new object(); } } }"; await TestExtractMethodAsync(code, expected, allowBestEffort: true); } [WorkItem(30750, "https://github.com/dotnet/roslyn/issues/30750")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodInInterface() { var code = @" interface Program { void Goo(); void Test() { [|Goo();|] } }"; var expected = @" interface Program { void Goo(); void Test() { NewMethod(); } void NewMethod() { Goo(); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(33242, "https://github.com/dotnet/roslyn/issues/33242")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodInExpressionBodiedConstructors() { var code = @" class Goo { private readonly string _bar; private Goo(string bar) => _bar = [|bar|]; }"; var expected = @" class Goo { private readonly string _bar; private Goo(string bar) => _bar = GetBar(bar); private static string GetBar(string bar) { return bar; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(33242, "https://github.com/dotnet/roslyn/issues/33242")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodInExpressionBodiedFinalizers() { var code = @" class Goo { bool finalized; ~Goo() => finalized = [|true|]; }"; var expected = @" class Goo { bool finalized; ~Goo() => finalized = NewMethod(); private static bool NewMethod() { return true; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodInvolvingFunctionPointer() { var code = @" class C { void M(delegate*<delegate*<ref string, ref readonly int>> ptr1) { string s = null; _ = [|ptr1()|](ref s); } }"; var expected = @" class C { void M(delegate*<delegate*<ref string, ref readonly int>> ptr1) { string s = null; _ = NewMethod(ptr1)(ref s); } private static delegate*<ref string, ref readonly int> NewMethod(delegate*<delegate*<ref string, ref readonly int>> ptr1) { return ptr1(); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodInvolvingFunctionPointerWithTypeParameter() { var code = @" class C { void M<T1, T2>(delegate*<T1, T2> ptr1) { _ = [|ptr1|](); } }"; var expected = @" class C { void M<T1, T2>(delegate*<T1, T2> ptr1) { _ = GetPtr1(ptr1)(); } private static delegate*<T1, T2> GetPtr1<T1, T2>(delegate*<T1, T2> ptr1) { return ptr1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(44260, "https://github.com/dotnet/roslyn/issues/44260")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TopLevelStatement_ValueInAssignment() { var code = @" bool local; local = [|true|]; "; var expected = @" bool local; bool NewMethod() { return true; } local = NewMethod(); "; await TestExtractMethodAsync(code, expected); } [WorkItem(44260, "https://github.com/dotnet/roslyn/issues/44260")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TopLevelStatement_ArgumentInInvocation() { // Note: the cast should be simplified // https://github.com/dotnet/roslyn/issues/44260 var code = @" System.Console.WriteLine([|""string""|]); "; var expected = @" System.Console.WriteLine((string)NewMethod()); string NewMethod() { return ""string""; }"; await TestExtractMethodAsync(code, expected); } [Theory] [InlineData("unsafe")] [InlineData("checked")] [InlineData("unchecked")] [Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(4950, "https://github.com/dotnet/roslyn/issues/4950")] public async Task ExtractMethodInvolvingUnsafeBlock(string keyword) { var code = $@" using System; class Program {{ static void Main(string[] args) {{ object value = args; [| IntPtr p; {keyword} {{ object t = value; p = IntPtr.Zero; }} |] Console.WriteLine(p); }} }} "; var expected = $@" using System; class Program {{ static void Main(string[] args) {{ object value = args; IntPtr p = NewMethod(value); Console.WriteLine(p); }} private static IntPtr NewMethod(object value) {{ IntPtr p; {keyword} {{ object t = value; p = IntPtr.Zero; }} return p; }} }} "; await TestExtractMethodAsync(code, expected); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.ExtractMethod; using Microsoft.CodeAnalysis.Editor.CSharp.ExtractMethod; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ExtractMethod { public partial class ExtractMethodTests : ExtractMethodBase { [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod1() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { [|int i; i = 10;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { NewMethod(); } private static void NewMethod() { int i = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod2() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { [|int i = 10; int i2 = 10;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { NewMethod(); } private static void NewMethod() { int i = 10; int i2 = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod3() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i = 10; [|int i2 = i;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i = 10; NewMethod(i); } private static void NewMethod(int i) { int i2 = i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod4() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i = 10; int i2 = i; [|i2 += i;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i = 10; int i2 = i; i2 = NewMethod(i); } private static int NewMethod(int i, int i2) { i2 += i; return i2; } }"; // compoundaction not supported yet. await TestExtractMethodAsync(code, expected, temporaryFailing: true); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod5() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i = 10; int i2 = i; [|i2 = i;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i = 10; int i2 = i; i2 = NewMethod(i); } private static int NewMethod(int i) { return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod6() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { int field; void Test(string[] args) { int i = 10; [|field = i;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { int field; void Test(string[] args) { int i = 10; NewMethod(i); } private void NewMethod(int i) { field = i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod7() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { string [] a = null; [|Test(a);|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { string[] a = null; NewMethod(a); } private void NewMethod(string[] a) { Test(a); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod8() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Test(string[] args) { string [] a = null; [|Test(a);|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Test(string[] args) { string[] a = null; NewMethod(a); } private static void NewMethod(string[] a) { Test(a); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod9() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i; string s; [|i = 10; s = args[0] + i.ToString();|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i; string s; NewMethod(args, out i, out s); } private static void NewMethod(string[] args, out int i, out string s) { i = 10; s = args[0] + i.ToString(); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod10() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { [|int i; i = 10; string s; s = args[0] + i.ToString();|] Console.WriteLine(s); } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { string s = NewMethod(args); Console.WriteLine(s); } private static string NewMethod(string[] args) { int i = 10; string s; s = args[0] + i.ToString(); return s; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod11() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { [|int i; int i2 = 10;|] i = 10; } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i; NewMethod(); i = 10; } private static void NewMethod() { int i2 = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod11_1() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { [|int i; int i2 = 10;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { NewMethod(); } private static void NewMethod() { int i; int i2 = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod12() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i = 10; [|i = i + 1;|] Console.WriteLine(i); } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i = 10; i = NewMethod(i); Console.WriteLine(i); } private static int NewMethod(int i) { i = i + 1; return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ControlVariableInForeachStatement() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { foreach (var s in args) { [|Console.WriteLine(s);|] } } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { foreach (var s in args) { NewMethod(s); } } private static void NewMethod(string s) { Console.WriteLine(s); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod14() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { for(var i = 1; i < 10; i++) { [|Console.WriteLine(i);|] } } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { for (var i = 1; i < 10; i++) { NewMethod(i); } } private static void NewMethod(int i) { Console.WriteLine(i); } }"; // var in for loop doesn't get bound yet await TestExtractMethodAsync(code, expected, temporaryFailing: true); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod15() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { [|int s = 10, i = 1; int b = s + i;|] System.Console.WriteLine(s); System.Console.WriteLine(i); } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int s, i; NewMethod(out s, out i); System.Console.WriteLine(s); System.Console.WriteLine(i); } private static void NewMethod(out int s, out int i) { s = 10; i = 1; int b = s + i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod16() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { [|int i = 1;|] System.Console.WriteLine(i); } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i = NewMethod(); System.Console.WriteLine(i); } private static int NewMethod() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538932, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538932")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod17() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test<T>(out T t) where T : class, new() { [|T t1; Test(out t1); t = t1;|] System.Console.WriteLine(t1.ToString()); } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test<T>(out T t) where T : class, new() { T t1; NewMethod(out t, out t1); System.Console.WriteLine(t1.ToString()); } private void NewMethod<T>(out T t, out T t1) where T : class, new() { Test(out t1); t = t1; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod18() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test<T>(out T t) where T : class, new() { [|T t1 = GetValue(out t);|] System.Console.WriteLine(t1.ToString()); } private T GetValue<T>(out T t) where T : class, new() { return t = new T(); } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test<T>(out T t) where T : class, new() { T t1; NewMethod(out t, out t1); System.Console.WriteLine(t1.ToString()); } private void NewMethod<T>(out T t, out T t1) where T : class, new() { t1 = GetValue(out t); } private T GetValue<T>(out T t) where T : class, new() { return t = new T(); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod19() { var code = @"using System; using System.Collections.Generic; using System.Linq; unsafe class Program { void Test() { [|int i = 1;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; unsafe class Program { void Test() { NewMethod(); } private static void NewMethod() { int i = 1; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod20() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { unsafe void Test() { [|int i = 1;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { unsafe void Test() { NewMethod(); } private static unsafe void NewMethod() { int i = 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542677")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod21() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test() { unsafe { [|int i = 1;|] } } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test() { unsafe { NewMethod(); } } private static unsafe void NewMethod() { int i = 1; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod22() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test() { int i; [|int b = 10; if (b < 10) { i = 5; }|] i = 6; Console.WriteLine(i); } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test() { int i; i = NewMethod(i); i = 6; Console.WriteLine(i); } private static int NewMethod(int i) { int b = 10; if (b < 10) { i = 5; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod23() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { if (true) [|Console.WriteLine(args[0].ToString());|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { if (true) NewMethod(args); } private static void NewMethod(string[] args) { Console.WriteLine(args[0].ToString()); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod24() { var code = @"using System; class Program { static void Main(string[] args) { int y = [|int.Parse(args[0].ToString())|]; } }"; var expected = @"using System; class Program { static void Main(string[] args) { int y = GetY(args); } private static int GetY(string[] args) { return int.Parse(args[0].ToString()); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod25() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { if (([|new int[] { 1, 2, 3 }|]).Any()) { return; } } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { if ((NewMethod()).Any()) { return; } } private static int[] NewMethod() { return new int[] { 1, 2, 3 }; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod26() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { if ([|(new int[] { 1, 2, 3 })|].Any()) { return; } } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { if (NewMethod().Any()) { return; } } private static int[] NewMethod() { return (new int[] { 1, 2, 3 }); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod27() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test() { int i = 1; [|int b = 10; if (b < 10) { i = 5; }|] i = 6; Console.WriteLine(i); } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test() { int i = 1; i = NewMethod(i); i = 6; Console.WriteLine(i); } private static int NewMethod(int i) { int b = 10; if (b < 10) { i = 5; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod28() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { int Test() { [|return 1;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { int Test() { return NewMethod(); } private static int NewMethod() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod29() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { int Test() { int i = 0; [|if (i < 0) { return 1; } else { return 0; }|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { int Test() { int i = 0; return NewMethod(i); } private static int NewMethod(int i) { if (i < 0) { return 1; } else { return 0; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod30() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(out int i) { [|i = 10;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(out int i) { i = NewMethod(); } private static int NewMethod() { return 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod31() { var code = @"using System; using System.Collections.Generic; using System.Text; class Program { void Test() { StringBuilder builder = new StringBuilder(); [|builder.Append(""Hello""); builder.Append("" From ""); builder.Append("" Roslyn"");|] return builder.ToString(); } }"; var expected = @"using System; using System.Collections.Generic; using System.Text; class Program { void Test() { StringBuilder builder = new StringBuilder(); NewMethod(builder); return builder.ToString(); } private static void NewMethod(StringBuilder builder) { builder.Append(""Hello""); builder.Append("" From ""); builder.Append("" Roslyn""); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod32() { var code = @"using System; class Program { void Test() { int v = 0; Console.Write([|v|]); } }"; var expected = @"using System; class Program { void Test() { int v = 0; Console.Write(GetV(v)); } private static int GetV(int v) { return v; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(3792, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod33() { var code = @"using System; class Program { void Test() { int v = 0; while (true) { Console.Write([|v++|]); } } }"; var expected = @"using System; class Program { void Test() { int v = 0; while (true) { Console.Write(NewMethod(ref v)); } } private static int NewMethod(ref int v) { return v++; } }"; // this bug has two issues. one is "v" being not in the dataFlowIn and ReadInside collection (hence no method parameter) // and the other is binding not working for "v++" (hence object as return type) await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod34() { var code = @"using System; class Program { static void Main(string[] args) { int x = 1; int y = 2; int z = [|x + y|]; } } "; var expected = @"using System; class Program { static void Main(string[] args) { int x = 1; int y = 2; int z = GetZ(x, y); } private static int GetZ(int x, int y) { return x + y; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(538239, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538239")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod35() { var code = @"using System; class Program { static void Main(string[] args) { int[] r = [|new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }|]; } }"; var expected = @"using System; class Program { static void Main(string[] args) { int[] r = GetR(); } private static int[] GetR() { return new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod36() { var code = @"using System; class Program { static void Main(ref int i) { [|i = 1;|] } }"; var expected = @"using System; class Program { static void Main(ref int i) { i = NewMethod(); } private static int NewMethod() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod37() { var code = @"using System; class Program { static void Main(out int i) { [|i = 1;|] } }"; var expected = @"using System; class Program { static void Main(out int i) { i = NewMethod(); } private static int NewMethod() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538231, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538231")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod38() { var code = @"using System; class Program { static void Main(string[] args) { // int v = 0; // while (true) // { // NewMethod(v++); // NewMethod(ReturnVal(v++)); // } int unassigned; // extract // unassigned = ReturnVal(0); [|unassigned = unassigned + 10;|] // read // int newVar = unassigned; // write // unassigned = 0; } }"; var expected = @"using System; class Program { static void Main(string[] args) { // int v = 0; // while (true) // { // NewMethod(v++); // NewMethod(ReturnVal(v++)); // } int unassigned; // extract // unassigned = ReturnVal(0); unassigned = NewMethod(unassigned); // read // int newVar = unassigned; // write // unassigned = 0; } private static int NewMethod(int unassigned) { unassigned = unassigned + 10; return unassigned; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538231, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538231")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod39() { var code = @"using System; class Program { static void Main(string[] args) { // int v = 0; // while (true) // { // NewMethod(v++); // NewMethod(ReturnVal(v++)); // } int unassigned; // extract [|// unassigned = ReturnVal(0); unassigned = unassigned + 10; // read|] // int newVar = unassigned; // write // unassigned = 0; } }"; var expected = @"using System; class Program { static void Main(string[] args) { // int v = 0; // while (true) // { // NewMethod(v++); // NewMethod(ReturnVal(v++)); // } int unassigned; // extract unassigned = NewMethod(unassigned); // int newVar = unassigned; // write // unassigned = 0; } private static int NewMethod(int unassigned) { // unassigned = ReturnVal(0); unassigned = unassigned + 10; // read return unassigned; } }"; // current bottom-up re-writer makes re-attaching trivia half belongs to previous token // and half belongs to next token very hard. // for now, it won't be able to re-associate trivia belongs to next token. await TestExtractMethodAsync(code, expected); } [WorkItem(538303, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538303")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod40() { var code = @"class Program { static void Main(string[] args) { [|int x;|] } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(868414, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/868414")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodWithLeadingTrivia() { // ensure that the extraction doesn't result in trivia moving up a line: // // a //b // NewMethod(); await TestExtractMethodAsync( @"class C { void M() { // a // b [|System.Console.WriteLine();|] } }", @"class C { void M() { // a // b NewMethod(); } private static void NewMethod() { System.Console.WriteLine(); } }"); } [WorkItem(632351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/632351")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodFailForTypeInFromClause() { var code = @"class Program { static void Main(string[] args) { var z = from [|T|] x in e; } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(632351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/632351")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodFailForTypeInFromClause_1() { var code = @"class Program { static void Main(string[] args) { var z = from [|W.T|] x in e; } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(538314, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538314")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod41() { var code = @"class Program { static void Main(string[] args) { int x = 10; [|int y; if (x == 10) y = 5;|] Console.WriteLine(y); } }"; var expected = @"class Program { static void Main(string[] args) { int x = 10; int y = NewMethod(x); Console.WriteLine(y); } private static int NewMethod(int x) { int y; if (x == 10) y = 5; return y; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538327, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538327")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod42() { var code = @"using System; class Program { static void Main(string[] args) { int a, b; [|a = 5; b = 7;|] Console.Write(a + b); } }"; var expected = @"using System; class Program { static void Main(string[] args) { int a, b; NewMethod(out a, out b); Console.Write(a + b); } private static void NewMethod(out int a, out int b) { a = 5; b = 7; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538327, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538327")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod43() { var code = @"using System; class Program { static void Main(string[] args) { int a, b; [|a = 5; b = 7; int c; int d; int e, f; c = 1; d = 1; e = 1; f = 1;|] Console.Write(a + b); } }"; var expected = @"using System; class Program { static void Main(string[] args) { int a, b; NewMethod(out a, out b); Console.Write(a + b); } private static void NewMethod(out int a, out int b) { a = 5; b = 7; int c; int d; int e, f; c = 1; d = 1; e = 1; f = 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538328, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538328")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod44() { var code = @"using System; class Program { static void Main(string[] args) { int a; //modified in [|a = 1;|] /*data flow out*/ Console.Write(a); } }"; var expected = @"using System; class Program { static void Main(string[] args) { int a; //modified in a = NewMethod(); /*data flow out*/ Console.Write(a); } private static int NewMethod() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538393, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538393")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod45() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { /**/[|;|]/**/ } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { /**/ NewMethod();/**/ } private static void NewMethod() { ; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538393, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538393")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod46() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int x = 1; [|Goo(ref x);|] Console.WriteLine(x); } static void Goo(ref int x) { x = x + 1; } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int x = 1; x = NewMethod(x); Console.WriteLine(x); } private static int NewMethod(int x) { Goo(ref x); return x; } static void Goo(ref int x) { x = x + 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538399, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538399")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod47() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int x = 1; [|while (true) Console.WriteLine(x);|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int x = 1; NewMethod(x); } private static void NewMethod(int x) { while (true) Console.WriteLine(x); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538401")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod48() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int[] x = [|{ 1, 2, 3 }|]; } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int[] x = GetX(); } private static int[] GetX() { return new int[] { 1, 2, 3 }; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538405")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod49() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Goo(int GetX) { int x = [|1|]; } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Goo(int GetX) { int x = GetX1(); } private static int GetX1() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodNormalProperty() { var code = @" class Class { private static string name; public static string Names { get { return ""1""; } set { name = value; } } static void Goo(int i) { string str = [|Class.Names|]; } }"; var expected = @" class Class { private static string name; public static string Names { get { return ""1""; } set { name = value; } } static void Goo(int i) { string str = GetStr(); } private static string GetStr() { return Class.Names; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538932, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538932")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodAutoProperty() { var code = @" class Class { public string Name { get; set; } static void Main() { string str = new Class().[|Name|]; } }"; // given span is not an expression // selection validator should take care of this case var expected = @" class Class { public string Name { get; set; } static void Main() { string str = GetStr(); } private static string GetStr() { return new Class().Name; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538402, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538402")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix3994() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { byte x = [|1|]; } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { byte x = GetX(); } private static byte GetX() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538404, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538404")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix3996() { var code = @"class A<T> { class D : A<T> { } class B { } static D.B Goo() { return null; } class C<T2> { static void Bar() { D.B x = [|Goo()|]; } } }"; var expected = @"class A<T> { class D : A<T> { } class B { } static D.B Goo() { return null; } class C<T2> { static void Bar() { D.B x = GetX(); } private static B GetX() { return Goo(); } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task InsertionPoint() { var code = @"class Test { void Method(string i) { int y2 = [|1|]; } void Method(int i) { } }"; var expected = @"class Test { void Method(string i) { int y2 = GetY2(); } private static int GetY2() { return 1; } void Method(int i) { } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538980, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538980")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4757() { var code = @"class GenericMethod { void Method<T>(T t) { T a; [|a = t;|] } }"; var expected = @"class GenericMethod { void Method<T>(T t) { T a; a = NewMethod(t); } private static T NewMethod<T>(T t) { return t; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538980, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538980")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4757_2() { var code = @"class GenericMethod<T1> { void Method<T>(T t) { T a; T1 b; [|a = t; b = default(T1);|] } }"; var expected = @"class GenericMethod<T1> { void Method<T>(T t) { T a; T1 b; NewMethod(t, out a, out b); } private static void NewMethod<T>(T t, out T a, out T1 b) { a = t; b = default(T1); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538980, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538980")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4757_3() { var code = @"class GenericMethod { void Method<T, T1>(T t) { T1 a1; T a; [|a = t; a1 = default(T);|] } }"; var expected = @"class GenericMethod { void Method<T, T1>(T t) { T1 a1; T a; NewMethod(t, out a1, out a); } private static void NewMethod<T, T1>(T t, out T1 a1, out T a) { a = t; a1 = default(T); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538422, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538422")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4758() { var code = @"using System; class TestOutParameter { void Method(out int x) { x = 5; Console.Write([|x|]); } }"; var expected = @"using System; class TestOutParameter { void Method(out int x) { x = 5; Console.Write(GetX(x)); } private static int GetX(int x) { return x; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538422, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538422")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4758_2() { var code = @"class TestOutParameter { void Method(out int x) { x = 5; Console.Write([|x|]); } }"; var expected = @"class TestOutParameter { void Method(out int x) { x = 5; Console.Write(GetX(x)); } private static int GetX(int x) { return x; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538984, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538984")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4761() { var code = @"using System; class A { void Method() { System.Func<int, int> a = x => [|x * x|]; } }"; var expected = @"using System; class A { void Method() { System.Func<int, int> a = x => NewMethod(x); } private static int NewMethod(int x) { return x * x; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538997, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538997")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4779() { var code = @"using System; class Program { static void Main() { string s = ""; Func<string> f = [|s|].ToString; } } "; var expected = @"using System; class Program { static void Main() { string s = ""; Func<string> f = GetS(s).ToString; } private static string GetS(string s) { return s; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(538997, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538997")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4779_2() { var code = @"using System; class Program { static void Main() { string s = ""; var f = [|s|].ToString(); } } "; var expected = @"using System; class Program { static void Main() { string s = ""; var f = GetS(s).ToString(); } private static string GetS(string s) { return s; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(4780, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4780() { var code = @"using System; class Program { static void Main() { string s = ""; object f = (Func<string>)[|s.ToString|]; } }"; var expected = @"using System; class Program { static void Main() { string s = ""; object f = (Func<string>)GetToString(s); } private static Func<string> GetToString(string s) { return s.ToString; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(4780, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4780_2() { var code = @"using System; class Program { static void Main() { string s = ""; object f = (string)[|s.ToString()|]; } }"; var expected = @"using System; class Program { static void Main() { string s = ""; object f = (string)NewMethod(s); } private static string NewMethod(string s) { return s.ToString(); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(4782, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4782() { var code = @"class A<T> { class D : A<T[]> { } class B { } class C<T> { static void Goo<T>(T a) { T t = [|default(T)|]; } } }"; var expected = @"class A<T> { class D : A<T[]> { } class B { } class C<T> { static void Goo<T>(T a) { T t = GetT<T>(); } private static T GetT<T>() { return default(T); } } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(4782, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4782_2() { var code = @"class A<T> { class D : A<T[]> { } class B { } class C<T> { static void Goo() { D.B x = [|new D.B()|]; } } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(4791, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4791() { var code = @"class Program { delegate int Func(int a); static void Main(string[] args) { Func v = (int a) => [|a|]; } }"; var expected = @"class Program { delegate int Func(int a); static void Main(string[] args) { Func v = (int a) => GetA(a); } private static int GetA(int a) { return a; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539019, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539019")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4809() { var code = @"class Program { public Program() { [|int x = 2;|] } }"; var expected = @"class Program { public Program() { NewMethod(); } private static void NewMethod() { int x = 2; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539029, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539029")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4813() { var code = @"using System; class Program { public Program() { object o = [|new Program()|]; } }"; var expected = @"using System; class Program { public Program() { object o = GetO(); } private static Program GetO() { return new Program(); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538425")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4031() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { bool x = true, y = true, z = true; if (x) while (y) { } else [|while (z) { }|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { bool x = true, y = true, z = true; if (x) while (y) { } else NewMethod(z); } private static void NewMethod(bool z) { while (z) { } } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(527499, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527499")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix3992() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int x = 1; [|while (false) Console.WriteLine(x);|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int x = 1; NewMethod(x); } private static void NewMethod(int x) { while (false) Console.WriteLine(x); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539029, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539029")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4823() { var code = @"class Program { private double area = 1.0; public double Area { get { return area; } } public override string ToString() { return string.Format(""{0:F2}"", [|Area|]); } }"; var expected = @"class Program { private double area = 1.0; public double Area { get { return area; } } public override string ToString() { return string.Format(""{0:F2}"", GetArea()); } private double GetArea() { return Area; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538985, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538985")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4762() { var code = @"class Program { static void Main(string[] args) { //comments [|int x = 2;|] } } "; var expected = @"class Program { static void Main(string[] args) { //comments NewMethod(); } private static void NewMethod() { int x = 2; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(538966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538966")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4744() { var code = @"class Program { static void Main(string[] args) { [|int x = 2; //comments|] } } "; var expected = @"class Program { static void Main(string[] args) { NewMethod(); } private static void NewMethod() { int x = 2; //comments } } "; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoNoNoYesNoNo() { var code = @"using System; class Program { void Test1() { int i; [| if (int.Parse(""1"") > 0) { i = 10; } |] } }"; var expected = @"using System; class Program { void Test1() { int i; i = NewMethod(i); } private static int NewMethod(int i) { if (int.Parse(""1"") > 0) { i = 10; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoNoNoYesNoYes() { var code = @"using System; class Program { void Test2() { int i = 0; [| if (int.Parse(""1"") > 0) { i = 10; } |] } }"; var expected = @"using System; class Program { void Test2() { int i = 0; i = NewMethod(i); } private static int NewMethod(int i) { if (int.Parse(""1"") > 0) { i = 10; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoNoNoYesYesNo() { var code = @"using System; class Program { void Test3() { int i; while (i > 10) ; [| if (int.Parse(""1"") > 0) { i = 10; } |] } }"; var expected = @"using System; class Program { void Test3() { int i; while (i > 10) ; i = NewMethod(i); } private static int NewMethod(int i) { if (int.Parse(""1"") > 0) { i = 10; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoNoNoYesYesYes() { var code = @"using System; class Program { void Test4() { int i = 10; while (i > 10) ; [| if (int.Parse(""1"") > 0) { i = 10; } |] } }"; var expected = @"using System; class Program { void Test4() { int i = 10; while (i > 10) ; i = NewMethod(i); } private static int NewMethod(int i) { if (int.Parse(""1"") > 0) { i = 10; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoNoYesYesNoNo() { var code = @"using System; class Program { void Test4_1() { int i; [| if (int.Parse(""1"") > 0) { i = 10; Console.WriteLine(i); } |] } }"; var expected = @"using System; class Program { void Test4_1() { int i; i = NewMethod(); } private static int NewMethod() { int i; if (int.Parse(""1"") > 0) { i = 10; Console.WriteLine(i); } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoNoYesYesNoYes() { var code = @"using System; class Program { void Test4_2() { int i = 10; [| if (int.Parse(""1"") > 0) { i = 10; Console.WriteLine(i); } |] } }"; var expected = @"using System; class Program { void Test4_2() { int i = 10; i = NewMethod(i); } private static int NewMethod(int i) { if (int.Parse(""1"") > 0) { i = 10; Console.WriteLine(i); } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoNoYesYesYesNo() { var code = @"using System; class Program { void Test4_3() { int i; Console.WriteLine(i); [| if (int.Parse(""1"") > 0) { i = 10; Console.WriteLine(i); } |] } }"; var expected = @"using System; class Program { void Test4_3() { int i; Console.WriteLine(i); i = NewMethod(); } private static int NewMethod() { int i; if (int.Parse(""1"") > 0) { i = 10; Console.WriteLine(i); } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoNoYesYesYesYes() { var code = @"using System; class Program { void Test4_4() { int i = 10; Console.WriteLine(i); [| if (int.Parse(""1"") > 0) { i = 10; Console.WriteLine(i); } |] } }"; var expected = @"using System; class Program { void Test4_4() { int i = 10; Console.WriteLine(i); i = NewMethod(i); } private static int NewMethod(int i) { if (int.Parse(""1"") > 0) { i = 10; Console.WriteLine(i); } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoYesNoNoNoNo() { var code = @"using System; class Program { void Test5() { [| int i; |] } }"; await ExpectExtractMethodToFailAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoYesNoNoNoYes() { var code = @"using System; class Program { void Test6() { [| int i; |] i = 1; } }"; await ExpectExtractMethodToFailAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoYesNoYesNoNo() { var code = @"using System; class Program { void Test7() { [| int i; if (int.Parse(""1"") > 0) { i = 10; } |] } }"; var expected = @"using System; class Program { void Test7() { NewMethod(); } private static void NewMethod() { int i; if (int.Parse(""1"") > 0) { i = 10; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoYesNoYesNoYes() { var code = @"using System; class Program { void Test8() { [| int i; if (int.Parse(""1"") > 0) { i = 10; } |] i = 2; } }"; var expected = @"using System; class Program { void Test8() { int i = NewMethod(); i = 2; } private static int NewMethod() { int i; if (int.Parse(""1"") > 0) { i = 10; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoYesYesNoNoNo() { var code = @"using System; class Program { void Test9() { [| int i; Console.WriteLine(i); |] } }"; var expected = @"using System; class Program { void Test9() { NewMethod(); } private static void NewMethod() { int i; Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoYesYesNoNoYes() { var code = @"using System; class Program { void Test10() { [| int i; Console.WriteLine(i); |] i = 10; } }"; var expected = @"using System; class Program { void Test10() { int i; NewMethod(); i = 10; } private static void NewMethod() { int i; Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoYesYesYesNoNo() { var code = @"using System; class Program { void Test11() { [| int i; if (int.Parse(""1"") > 0) { i = 10; } Console.WriteLine(i); |] } }"; var expected = @"using System; class Program { void Test11() { NewMethod(); } private static void NewMethod() { int i; if (int.Parse(""1"") > 0) { i = 10; } Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoYesYesYesNoYes() { var code = @"using System; class Program { void Test12() { [| int i; if (int.Parse(""1"") > 0) { i = 10; } Console.WriteLine(i); |] i = 10; } }"; var expected = @"using System; class Program { void Test12() { int i = NewMethod(); i = 10; } private static int NewMethod() { int i; if (int.Parse(""1"") > 0) { i = 10; } Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesNoNoYesNoNo() { var code = @"using System; class Program { void Test13() { int i; [| i = 10; |] } }"; var expected = @"using System; class Program { void Test13() { int i; i = NewMethod(); } private static int NewMethod() { return 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesNoNoYesNoYes() { var code = @"using System; class Program { void Test14() { int i; [| i = 10; |] i = 1; } }"; var expected = @"using System; class Program { void Test14() { int i; i = NewMethod(); i = 1; } private static int NewMethod() { return 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesNoNoYesYesNo() { var code = @"using System; class Program { void Test15() { int i; Console.WriteLine(i); [| i = 10; |] } }"; var expected = @"using System; class Program { void Test15() { int i; Console.WriteLine(i); i = NewMethod(); } private static int NewMethod() { return 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesNoNoYesYesYes() { var code = @"using System; class Program { void Test16() { int i; [| i = 10; |] i = 10; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test16() { int i; i = NewMethod(); i = 10; Console.WriteLine(i); } private static int NewMethod() { return 10; } }"; await TestExtractMethodAsync(code, expected); } // dataflow in and out can be false for symbols in unreachable code // boolean indicates // dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: false, readOutside: false, writtenOutside: true [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesNoYesNoNoYes() { var code = @"using System.Collections.Generic; using System.Linq; namespace ConsoleApp1 { class Test { IEnumerable<object> Crash0(IEnumerable<object> enumerable) { [|while (true) ; enumerable.Select(e => """"); return enumerable;|] } } }"; var expected = @"using System.Collections.Generic; using System.Linq; namespace ConsoleApp1 { class Test { IEnumerable<object> Crash0(IEnumerable<object> enumerable) { return NewMethod(enumerable); } private static IEnumerable<object> NewMethod(IEnumerable<object> enumerable) { while (true) ; enumerable.Select(e => """"); return enumerable; } } }"; await TestExtractMethodAsync(code, expected); } // dataflow in and out can be false for symbols in unreachable code // boolean indicates // dataFlowIn: false, dataFlowOut: false, alwaysAssigned: true, variableDeclared: false, readInside: true, writtenInside: false, readOutside: true, writtenOutside: true [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesNoYesNoYesYes() { var code = @"using System.Collections.Generic; using System.Linq; namespace ConsoleApp1 { class Test { IEnumerable<object> Crash0(IEnumerable<object> enumerable) { [|while (true) ; enumerable.Select(e => """");|] return enumerable; } } }"; var expected = @"using System.Collections.Generic; using System.Linq; namespace ConsoleApp1 { class Test { IEnumerable<object> Crash0(IEnumerable<object> enumerable) { enumerable = NewMethod(enumerable); return enumerable; } private static IEnumerable<object> NewMethod(IEnumerable<object> enumerable) { while (true) ; enumerable.Select(e => """"); return enumerable; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesNoYesYesNoNo() { var code = @"using System; class Program { void Test16_1() { int i; [| i = 10; Console.WriteLine(i); |] } }"; var expected = @"using System; class Program { void Test16_1() { int i; i = NewMethod(); } private static int NewMethod() { int i = 10; Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesNoYesYesNoYes() { var code = @"using System; class Program { void Test16_2() { int i = 10; [| i = 10; Console.WriteLine(i); |] } }"; var expected = @"using System; class Program { void Test16_2() { int i = 10; i = NewMethod(); } private static int NewMethod() { int i = 10; Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesNoYesYesYesNo() { var code = @"using System; class Program { void Test16_3() { int i; Console.WriteLine(i); [| i = 10; Console.WriteLine(i); |] } }"; var expected = @"using System; class Program { void Test16_3() { int i; Console.WriteLine(i); i = NewMethod(); } private static int NewMethod() { int i = 10; Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesNoYesYesYesYes() { var code = @"using System; class Program { void Test16_4() { int i = 10; Console.WriteLine(i); [| i = 10; Console.WriteLine(i); |] } }"; var expected = @"using System; class Program { void Test16_4() { int i = 10; Console.WriteLine(i); i = NewMethod(); } private static int NewMethod() { int i = 10; Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesYesNoYesNoNo() { var code = @"using System; class Program { void Test17() { [| int i = 10; |] } }"; var expected = @"using System; class Program { void Test17() { NewMethod(); } private static void NewMethod() { int i = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesYesNoYesNoYes() { var code = @"using System; class Program { void Test18() { [| int i = 10; |] i = 10; } }"; var expected = @"using System; class Program { void Test18() { int i = NewMethod(); i = 10; } private static int NewMethod() { return 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesYesYesYesNoNo() { var code = @"using System; class Program { void Test19() { [| int i = 10; Console.WriteLine(i); |] } }"; var expected = @"using System; class Program { void Test19() { NewMethod(); } private static void NewMethod() { int i = 10; Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesYesYesYesNoYes() { var code = @"using System; class Program { void Test20() { [| int i = 10; Console.WriteLine(i); |] i = 10; } }"; var expected = @"using System; class Program { void Test20() { int i; NewMethod(); i = 10; } private static void NewMethod() { int i = 10; Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoNoNoYesYesNo() { var code = @"using System; class Program { void Test21() { int i; [| if (int.Parse(""1"") > 10) { i = 1; } |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test21() { int i; i = NewMethod(i); Console.WriteLine(i); } private static int NewMethod(int i) { if (int.Parse(""1"") > 10) { i = 1; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoNoNoYesYesYes() { var code = @"using System; class Program { void Test22() { int i = 10; [| if (int.Parse(""1"") > 10) { i = 1; } |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test22() { int i = 10; i = NewMethod(i); Console.WriteLine(i); } private static int NewMethod(int i) { if (int.Parse(""1"") > 10) { i = 1; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoNoYesYesYesNo() { var code = @"using System; class Program { void Test22_1() { int i; [| if (int.Parse(""1"") > 10) { i = 1; Console.WriteLine(i); } |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test22_1() { int i; i = NewMethod(i); Console.WriteLine(i); } private static int NewMethod(int i) { if (int.Parse(""1"") > 10) { i = 1; Console.WriteLine(i); } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoNoYesYesYesYes() { var code = @"using System; class Program { void Test22_2() { int i = 10; [| if (int.Parse(""1"") > 10) { i = 1; Console.WriteLine(i); } |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test22_2() { int i = 10; i = NewMethod(i); Console.WriteLine(i); } private static int NewMethod(int i) { if (int.Parse(""1"") > 10) { i = 1; Console.WriteLine(i); } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoYesNoNoYesNo() { var code = @"using System; class Program { void Test23() { [| int i; |] Console.WriteLine(i); } }"; await ExpectExtractMethodToFailAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoYesNoNoYesYes() { var code = @"using System; class Program { void Test24() { [| int i; |] Console.WriteLine(i); i = 10; } }"; await ExpectExtractMethodToFailAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoYesNoYesYesNo() { var code = @"using System; class Program { void Test25() { [| int i; if (int.Parse(""1"") > 9) { i = 10; } |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test25() { int i = NewMethod(); Console.WriteLine(i); } private static int NewMethod() { int i; if (int.Parse(""1"") > 9) { i = 10; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoYesNoYesYesYes() { var code = @"using System; class Program { void Test26() { [| int i; if (int.Parse(""1"") > 9) { i = 10; } |] Console.WriteLine(i); i = 10; } }"; var expected = @"using System; class Program { void Test26() { int i = NewMethod(); Console.WriteLine(i); i = 10; } private static int NewMethod() { int i; if (int.Parse(""1"") > 9) { i = 10; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoYesYesNoYesNo() { var code = @"using System; class Program { void Test27() { [| int i; Console.WriteLine(i); |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test27() { int i = NewMethod(); Console.WriteLine(i); } private static int NewMethod() { int i; Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoYesYesNoYesYes() { var code = @"using System; class Program { void Test28() { [| int i; Console.WriteLine(i); |] Console.WriteLine(i); i = 10; } }"; var expected = @"using System; class Program { void Test28() { int i = NewMethod(); Console.WriteLine(i); i = 10; } private static int NewMethod() { int i; Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoYesYesYesYesNo() { var code = @"using System; class Program { void Test29() { [| int i; if (int.Parse(""1"") > 0) { i = 10; } Console.WriteLine(i); |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test29() { int i = NewMethod(); Console.WriteLine(i); } private static int NewMethod() { int i; if (int.Parse(""1"") > 0) { i = 10; } Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoYesYesYesYesYes() { var code = @"using System; class Program { void Test30() { [| int i; if (int.Parse(""1"") > 0) { i = 10; } Console.WriteLine(i); |] Console.WriteLine(i); i = 10; } }"; var expected = @"using System; class Program { void Test30() { int i = NewMethod(); Console.WriteLine(i); i = 10; } private static int NewMethod() { int i; if (int.Parse(""1"") > 0) { i = 10; } Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesYesNoNoYesYesNo() { var code = @"using System; class Program { void Test31() { int i; [| i = 10; |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test31() { int i; i = NewMethod(); Console.WriteLine(i); } private static int NewMethod() { return 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesYesNoNoYesYesYes() { var code = @"using System; class Program { void Test32() { int i; [| i = 10; |] Console.WriteLine(i); i = 10; } }"; var expected = @"using System; class Program { void Test32() { int i; i = NewMethod(); Console.WriteLine(i); i = 10; } private static int NewMethod() { return 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesYesNoYesYesYesNo() { var code = @"using System; class Program { void Test32_1() { int i; [| i = 10; Console.WriteLine(i); |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test32_1() { int i; i = NewMethod(); Console.WriteLine(i); } private static int NewMethod() { int i = 10; Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesYesNoYesYesYesYes() { var code = @"using System; class Program { void Test32_2() { int i = 10; [| i = 10; Console.WriteLine(i); |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test32_2() { int i = 10; i = NewMethod(); Console.WriteLine(i); } private static int NewMethod() { int i = 10; Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesYesYesNoYesYesNo() { var code = @"using System; class Program { void Test33() { [| int i = 10; |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test33() { int i = NewMethod(); Console.WriteLine(i); } private static int NewMethod() { return 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesYesYesNoYesYesYes() { var code = @"using System; class Program { void Test34() { [| int i = 10; |] Console.WriteLine(i); i = 10; } }"; var expected = @"using System; class Program { void Test34() { int i = NewMethod(); Console.WriteLine(i); i = 10; } private static int NewMethod() { return 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesYesYesYesYesYesNo() { var code = @"using System; class Program { void Test35() { [| int i = 10; Console.WriteLine(i); |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test35() { int i = NewMethod(); Console.WriteLine(i); } private static int NewMethod() { int i = 10; Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesYesYesYesYesYesYes() { var code = @"using System; class Program { void Test36() { [| int i = 10; Console.WriteLine(i); |] Console.WriteLine(i); i = 10; } }"; var expected = @"using System; class Program { void Test36() { int i = NewMethod(); Console.WriteLine(i); i = 10; } private static int NewMethod() { int i = 10; Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoNoNoYesNoNoNo() { var code = @"using System; class Program { void Test37() { int i; [| Console.WriteLine(i); |] } }"; var expected = @"using System; class Program { void Test37() { int i; NewMethod(i); } private static void NewMethod(int i) { Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoNoNoYesNoNoYes() { var code = @"using System; class Program { void Test38() { int i = 10; [| Console.WriteLine(i); |] } }"; var expected = @"using System; class Program { void Test38() { int i = 10; NewMethod(i); } private static void NewMethod(int i) { Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoNoNoYesNoYesNo() { var code = @"using System; class Program { void Test39() { int i; [| Console.WriteLine(i); |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test39() { int i; NewMethod(i); Console.WriteLine(i); } private static void NewMethod(int i) { Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoNoNoYesNoYesYes() { var code = @"using System; class Program { void Test40() { int i = 10; [| Console.WriteLine(i); |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test40() { int i = 10; NewMethod(i); Console.WriteLine(i); } private static void NewMethod(int i) { Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoNoNoYesYesNoNo() { var code = @"using System; class Program { void Test41() { int i; [| Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } |] } }"; var expected = @"using System; class Program { void Test41() { int i; i = NewMethod(i); } private static int NewMethod(int i) { Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoNoNoYesYesNoYes() { var code = @"using System; class Program { void Test42() { int i = 10; [| Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } |] } }"; var expected = @"using System; class Program { void Test42() { int i = 10; i = NewMethod(i); } private static int NewMethod(int i) { Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoNoNoYesYesYesNo() { var code = @"using System; class Program { void Test43() { int i; Console.WriteLine(i); [| Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } |] } }"; var expected = @"using System; class Program { void Test43() { int i; Console.WriteLine(i); i = NewMethod(i); } private static int NewMethod(int i) { Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoNoNoYesYesYesYes() { var code = @"using System; class Program { void Test44() { int i = 10; Console.WriteLine(i); [| Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } |] } }"; var expected = @"using System; class Program { void Test44() { int i = 10; Console.WriteLine(i); i = NewMethod(i); } private static int NewMethod(int i) { Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoYesNoYesYesNoNo() { var code = @"using System; class Program { void Test45() { int i; [| Console.WriteLine(i); i = 10; |] } }"; var expected = @"using System; class Program { void Test45() { int i; i = NewMethod(i); } private static int NewMethod(int i) { Console.WriteLine(i); i = 10; return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoYesNoYesYesNoYes() { var code = @"using System; class Program { void Test46() { int i = 10; [| Console.WriteLine(i); i = 10; |] } }"; var expected = @"using System; class Program { void Test46() { int i = 10; i = NewMethod(i); } private static int NewMethod(int i) { Console.WriteLine(i); i = 10; return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoYesNoYesYesYesNo() { var code = @"using System; class Program { void Test47() { int i; Console.WriteLine(i); [| Console.WriteLine(i); i = 10; |] } }"; var expected = @"using System; class Program { void Test47() { int i; Console.WriteLine(i); i = NewMethod(i); } private static int NewMethod(int i) { Console.WriteLine(i); i = 10; return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoYesNoYesYesYesYes() { var code = @"using System; class Program { void Test48() { int i = 10; Console.WriteLine(i); [| Console.WriteLine(i); i = 10; |] } }"; var expected = @"using System; class Program { void Test48() { int i = 10; Console.WriteLine(i); i = NewMethod(i); } private static int NewMethod(int i) { Console.WriteLine(i); i = 10; return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesYesNoNoYesYesYesNo() { var code = @"using System; class Program { void Test49() { int i; [| Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test49() { int i; i = NewMethod(i); Console.WriteLine(i); } private static int NewMethod(int i) { Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesYesNoNoYesYesYesYes() { var code = @"using System; class Program { void Test50() { int i = 10; [| Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test50() { int i = 10; i = NewMethod(i); Console.WriteLine(i); } private static int NewMethod(int i) { Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesYesYesNoYesYesYesNo() { var code = @"using System; class Program { void Test51() { int i; [| Console.WriteLine(i); i = 10; |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test51() { int i; i = NewMethod(i); Console.WriteLine(i); } private static int NewMethod(int i) { Console.WriteLine(i); i = 10; return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesYesYesNoYesYesYesYes() { var code = @"using System; class Program { void Test52() { int i = 10; [| Console.WriteLine(i); i = 10; |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test52() { int i = 10; i = NewMethod(i); Console.WriteLine(i); } private static int NewMethod(int i) { Console.WriteLine(i); i = 10; return i; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539049, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539049")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodInProperty1() { var code = @"class C2 { static public int Area { get { return 1; } } } class C3 { public static int Area { get { return [|C2.Area|]; } } } "; var expected = @"class C2 { static public int Area { get { return 1; } } } class C3 { public static int Area { get { return GetArea(); } } private static int GetArea() { return C2.Area; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(539049, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539049")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodInProperty2() { var code = @"class C3 { public static int Area { get { [|int i = 10; return i;|] } } } "; var expected = @"class C3 { public static int Area { get { return NewMethod(); } } private static int NewMethod() { return 10; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(539049, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539049")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodInProperty3() { var code = @"class C3 { public static int Area { set { [|int i = value;|] } } } "; var expected = @"class C3 { public static int Area { set { NewMethod(value); } } private static void NewMethod(int value) { int i = value; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(539029, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539029")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodProperty() { var code = @"class Program { private double area = 1.0; public double Area { get { return area; } } public override string ToString() { return string.Format(""{0:F2}"", [|Area|]); } } "; var expected = @"class Program { private double area = 1.0; public double Area { get { return area; } } public override string ToString() { return string.Format(""{0:F2}"", GetArea()); } private double GetArea() { return Area; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(539196, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539196")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodWithDeclareOneMoreVariablesInSameLineBeUsedAfter() { var code = @"class C { void M() { [|int x, y = 1;|] x = 4; Console.Write(x + y); } }"; var expected = @"class C { void M() { int x; int y = NewMethod(); x = 4; Console.Write(x + y); } private static int NewMethod() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539196, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539196")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodWithDeclareOneMoreVariablesInSameLineNotBeUsedAfter() { var code = @"class C { void M() { [|int x, y = 1;|] } }"; var expected = @"class C { void M() { NewMethod(); } private static void NewMethod() { int x, y = 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539214, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539214")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodForSplitOutStatementWithComments() { var code = @"class C { void M() { //start [|int x, y; x = 5; y = 10;|] //end Console.Write(x + y); } }"; var expected = @"class C { void M() { //start int x, y; NewMethod(out x, out y); //end Console.Write(x + y); } private static void NewMethod(out int x, out int y) { x = 5; y = 10; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539225")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug5098() { var code = @"class Program { static void Main(string[] args) { [|return;|] Console.Write(4); } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(539229, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539229")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug5107() { var code = @"class Program { static void Main(string[] args) { int i = 10; [|int j = j + i;|] Console.Write(i); Console.Write(j); } }"; var expected = @"class Program { static void Main(string[] args) { int i = 10; int j = NewMethod(i); Console.Write(i); Console.Write(j); } private static int NewMethod(int i) { return j + i; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539500")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task LambdaLiftedVariable1() { var code = @"class Program { delegate void Func(ref int i, int r); static void Main(string[] args) { int temp = 2; Func fnc = (ref int arg, int arg2) => { [|temp = arg = arg2;|] }; temp = 4; fnc(ref temp, 2); System.Console.WriteLine(temp); } }"; var expected = @"class Program { delegate void Func(ref int i, int r); static void Main(string[] args) { int temp = 2; Func fnc = (ref int arg, int arg2) => { NewMethod(out arg, arg2, out temp); }; temp = 4; fnc(ref temp, 2); System.Console.WriteLine(temp); } private static void NewMethod(out int arg, int arg2, out int temp) { temp = arg = arg2; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539488, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539488")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task LambdaLiftedVariable2() { var code = @"class Program { delegate void Action(); static void Main(string[] args) { int i = 0; Action query = null; if (i == 0) { query = () => { System.Console.WriteLine(i); }; } [|i = 3;|] query(); } }"; var expected = @"class Program { delegate void Action(); static void Main(string[] args) { int i = 0; Action query = null; if (i == 0) { query = () => { System.Console.WriteLine(i); }; } i = NewMethod(); query(); } private static int NewMethod() { return 3; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539531")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug5533() { var code = @"using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { [|TestDelegate testDel = (ref int x) => { x = 10; };|] int p = 2; testDel(ref p); Console.WriteLine(p); } }"; var expected = @"using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { TestDelegate testDel = NewMethod(); int p = 2; testDel(ref p); Console.WriteLine(p); } private static TestDelegate NewMethod() { return (ref int x) => { x = 10; }; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539531")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug5533_1() { var code = @"using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { [|TestDelegate testDel = (ref int x) => { int y = x; x = 10; };|] int p = 2; testDel(ref p); Console.WriteLine(p); } }"; var expected = @"using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { TestDelegate testDel = NewMethod(); int p = 2; testDel(ref p); Console.WriteLine(p); } private static TestDelegate NewMethod() { return (ref int x) => { int y = x; x = 10; }; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539531")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug5533_2() { var code = @"using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { TestDelegate testDel = (ref int x) => { [|int y = x; x = 10;|] }; int p = 2; testDel(ref p); Console.WriteLine(p); } }"; var expected = @"using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { TestDelegate testDel = (ref int x) => { x = NewMethod(x); }; int p = 2; testDel(ref p); Console.WriteLine(p); } private static int NewMethod(int x) { int y = x; x = 10; return x; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539531")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug5533_3() { var code = @"using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { [|TestDelegate testDel = delegate (ref int x) { x = 10; };|] int p = 2; testDel(ref p); Console.WriteLine(p); } }"; var expected = @"using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { TestDelegate testDel = NewMethod(); int p = 2; testDel(ref p); Console.WriteLine(p); } private static TestDelegate NewMethod() { return delegate (ref int x) { x = 10; }; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539859, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539859")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task LambdaLiftedVariable3() { var code = @"using System; class Program { static void Main(string[] args) { Action<int> F = x => { Action<int> F2 = x2 => { [|Console.WriteLine(args.Length + x2 + x);|] }; F2(x); }; F(args.Length); } }"; var expected = @"using System; class Program { static void Main(string[] args) { Action<int> F = x => { Action<int> F2 = x2 => { NewMethod(args, x, x2); }; F2(x); }; F(args.Length); } private static void NewMethod(string[] args, int x, int x2) { Console.WriteLine(args.Length + x2 + x); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539882, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539882")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug5982() { var code = @"using System; using System.Collections.Generic; class Program { static void Main(string[] args) { List<int> list = new List<int>(); Console.WriteLine([|list.Capacity|]); } }"; var expected = @"using System; using System.Collections.Generic; class Program { static void Main(string[] args) { List<int> list = new List<int>(); Console.WriteLine(GetCapacity(list)); } private static int GetCapacity(List<int> list) { return list.Capacity; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539932, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539932")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6041() { var code = @"using System; class Program { delegate R Del<in T, out R>(T arg); public void Goo() { Del<Exception, ArgumentException> d = (arg) => { return new ArgumentException(); }; [|d(new ArgumentException());|] } }"; var expected = @"using System; class Program { delegate R Del<in T, out R>(T arg); public void Goo() { Del<Exception, ArgumentException> d = (arg) => { return new ArgumentException(); }; NewMethod(d); } private static void NewMethod(Del<Exception, ArgumentException> d) { d(new ArgumentException()); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540183, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540183")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod50() { var code = @"class C { void Method() { while (true) { [|int i = 1; while (false) { int j = 1;|] } } } }"; var expected = @"class C { void Method() { while (true) { NewMethod(); } } private static void NewMethod() { int i = 1; while (false) { int j = 1; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod51() { var code = @"class C { void Method() { while (true) { switch(1) { case 1: [|int i = 10; break; case 2: int i2 = 20;|] break; } } } }"; var expected = @"class C { void Method() { while (true) { NewMethod(); } } private static void NewMethod() { switch (1) { case 1: int i = 10; break; case 2: int i2 = 20; break; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod52() { var code = @"class C { void Method() { [|int i = 1; while (false) { int j = 1;|] } } }"; var expected = @"class C { void Method() { NewMethod(); } private static void NewMethod() { int i = 1; while (false) { int j = 1; } } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539963, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539963")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod53() { var code = @"class Class { void Main() { Enum e = Enum.[|Field|]; } } enum Enum { }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(539964, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539964")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod54() { var code = @"class Class { void Main([|string|][] args) { } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(540072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540072")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6220() { var code = @"class C { void Main() { [| float f = 1.2f; |] System.Console.WriteLine(); } }"; var expected = @"class C { void Main() { NewMethod(); System.Console.WriteLine(); } private static void NewMethod() { float f = 1.2f; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540072")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6220_1() { var code = @"class C { void Main() { [| float f = 1.2f; // test |] System.Console.WriteLine(); } }"; var expected = @"class C { void Main() { NewMethod(); System.Console.WriteLine(); } private static void NewMethod() { float f = 1.2f; // test } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540071, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540071")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6219() { var code = @"class C { void Main() { float @float = 1.2f; [|@float = 1.44F;|] } }"; var expected = @"class C { void Main() { float @float = 1.2f; @float = NewMethod(); } private static float NewMethod() { return 1.44F; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540080, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540080")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6230() { var code = @"class C { void M() { int v =[| /**/1 + 2|]; System.Console.WriteLine(); } }"; var expected = @"class C { void M() { int v = GetV(); System.Console.WriteLine(); } private static int GetV() { return /**/1 + 2; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540080, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540080")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6230_1() { var code = @"class C { void M() { int v [|= /**/1 + 2|]; System.Console.WriteLine(); } }"; var expected = @"class C { void M() { NewMethod(); System.Console.WriteLine(); } private static void NewMethod() { int v = /**/1 + 2; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540052, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540052")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6197() { var code = @"using System; class Program { static void Main(string[] args) { Func<int, int> d = [|NewMethod|]; d.Invoke(2); } private static int NewMethod(int x) { return x * 2; } }"; var expected = @"using System; class Program { static void Main(string[] args) { Func<int, int> d = GetD(); d.Invoke(2); } private static Func<int, int> GetD() { return NewMethod; } private static int NewMethod(int x) { return x * 2; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(6277, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6277() { var code = @"using System; class Program { static void Main(string[] args) { [|int x; x = 1;|] return; int y = x; } }"; var expected = @"using System; class Program { static void Main(string[] args) { int x = NewMethod(); return; int y = x; } private static int NewMethod() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540151, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540151")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ArgumentlessReturnWithConstIfExpression() { var code = @"using System; class Program { void Test() { [|if (true) return;|] Console.WriteLine(); } }"; var expected = @"using System; class Program { void Test() { NewMethod(); return; Console.WriteLine(); } private static void NewMethod() { if (true) return; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540151, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540151")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ArgumentlessReturnWithConstIfExpression_1() { var code = @"using System; class Program { void Test() { if (true) [|if (true) return;|] Console.WriteLine(); } }"; var expected = @"using System; class Program { void Test() { if (true) { NewMethod(); return; } Console.WriteLine(); } private static void NewMethod() { if (true) return; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540151, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540151")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ArgumentlessReturnWithConstIfExpression_2() { var code = @"using System; class Program { void Test() { [|if (true) return;|] } }"; var expected = @"using System; class Program { void Test() { NewMethod(); } private static void NewMethod() { if (true) return; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540151, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540151")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ArgumentlessReturnWithConstIfExpression_3() { var code = @"using System; class Program { void Test() { if (true) [|if (true) return;|] } }"; var expected = @"using System; class Program { void Test() { if (true) { NewMethod(); return; } } private static void NewMethod() { if (true) return; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6313() { var code = @"using System; class Program { void Test(bool b) { [|if (b) { return; } Console.WriteLine();|] } }"; var expected = @"using System; class Program { void Test(bool b) { NewMethod(b); } private static void NewMethod(bool b) { if (b) { return; } Console.WriteLine(); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6313_1() { var code = @"using System; class Program { void Test(bool b) { [|if (b) { return; }|] Console.WriteLine(); } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6313_2() { var code = @"using System; class Program { int Test(bool b) { [|if (b) { return 1; } Console.WriteLine();|] } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6313_3() { var code = @"using System; class Program { void Test() { [|bool b = true; if (b) { return; } Action d = () => { if (b) { return; } Console.WriteLine(1); };|] } }"; var expected = @"using System; class Program { void Test() { NewMethod(); } private static void NewMethod() { bool b = true; if (b) { return; } Action d = () => { if (b) { return; } Console.WriteLine(1); }; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6313_4() { var code = @"using System; class Program { void Test() { [|Action d = () => { int i = 1; if (i > 10) { return; } Console.WriteLine(1); }; Action d2 = () => { int i = 1; if (i > 10) { return; } Console.WriteLine(1); };|] Console.WriteLine(1); } }"; var expected = @"using System; class Program { void Test() { NewMethod(); Console.WriteLine(1); } private static void NewMethod() { Action d = () => { int i = 1; if (i > 10) { return; } Console.WriteLine(1); }; Action d2 = () => { int i = 1; if (i > 10) { return; } Console.WriteLine(1); }; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6313_5() { var code = @"using System; class Program { void Test() { Action d = () => { [|int i = 1; if (i > 10) { return; } Console.WriteLine(1);|] }; } }"; var expected = @"using System; class Program { void Test() { Action d = () => { NewMethod(); }; } private static void NewMethod() { int i = 1; if (i > 10) { return; } Console.WriteLine(1); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6313_6() { var code = @"using System; class Program { void Test() { Action d = () => { [|int i = 1; if (i > 10) { return; }|] Console.WriteLine(1); }; } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(540170, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540170")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6333() { var code = @"using System; class Program { void Test() { Program p; [|p = new Program()|]; } }"; var expected = @"using System; class Program { void Test() { Program p; p = NewMethod(); } private static Program NewMethod() { return new Program(); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540216")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6393() { var code = @"using System; class Program { object Test<T>() { T abcd; [|abcd = new T()|]; return abcd; } }"; var expected = @"using System; class Program { object Test<T>() { T abcd; abcd = NewMethod<T>(); return abcd; } private static T NewMethod<T>() { return new T(); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540184, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540184")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6351() { var code = @"class Test { void method() { if (true) { for (int i = 0; i < 5; i++) { /*Begin*/ [|System.Console.WriteLine(); } System.Console.WriteLine();|] /*End*/ } } }"; var expected = @"class Test { void method() { if (true) { NewMethod(); /*End*/ } } private static void NewMethod() { for (int i = 0; i < 5; i++) { /*Begin*/ System.Console.WriteLine(); } System.Console.WriteLine(); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540184, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540184")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6351_1() { var code = @"class Test { void method() { if (true) { for (int i = 0; i < 5; i++) { /*Begin*/ [|System.Console.WriteLine(); } System.Console.WriteLine(); /*End*/|] } } }"; var expected = @"class Test { void method() { if (true) { NewMethod(); } } private static void NewMethod() { for (int i = 0; i < 5; i++) { /*Begin*/ System.Console.WriteLine(); } System.Console.WriteLine(); /*End*/ } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540184, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540184")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6351_2() { var code = @"class Test { void method() { if (true) [|{ for (int i = 0; i < 5; i++) { /*Begin*/ System.Console.WriteLine(); } System.Console.WriteLine(); /*End*/ }|] } }"; var expected = @"class Test { void method() { if (true) NewMethod(); } private static void NewMethod() { for (int i = 0; i < 5; i++) { /*Begin*/ System.Console.WriteLine(); } System.Console.WriteLine(); /*End*/ } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540333, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540333")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6560() { var code = @"using System; class Program { static void Main(string[] args) { string S = [|null|]; int Y = S.Length; } }"; var expected = @"using System; class Program { static void Main(string[] args) { string S = GetS(); int Y = S.Length; } private static string GetS() { return null; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540335")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6562() { var code = @"using System; class Program { int y = [|10|]; }"; var expected = @"using System; class Program { int y = GetY(); private static int GetY() { return 10; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540335")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6562_1() { var code = @"using System; class Program { const int i = [|10|]; }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(540335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540335")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6562_2() { var code = @"using System; class Program { Func<string> f = [|() => ""test""|]; }"; var expected = @"using System; class Program { Func<string> f = GetF(); private static Func<string> GetF() { return () => ""test""; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540335")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6562_3() { var code = @"using System; class Program { Func<string> f = () => [|""test""|]; }"; var expected = @"using System; class Program { Func<string> f = () => NewMethod(); private static string NewMethod() { return ""test""; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540361")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6598() { var code = @"using System; using System.Collections.Generic; using System.Linq; class { static void Main(string[] args) { [|Program|] } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(540372, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540372")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6613() { var code = @"#define A using System; class Program { static void Main(string[] args) { #if A [|Console.Write(5);|] #endif } }"; var expected = @"#define A using System; class Program { static void Main(string[] args) { #if A NewMethod(); #endif } private static void NewMethod() { Console.Write(5); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540396")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task InvalidSelection_MethodBody() { var code = @"using System; class Program { static void Main(string[] args) { void Method5(bool b1, bool b2) [|{ if (b1) { if (b2) return; Console.WriteLine(); } Console.WriteLine(); }|] } } "; await ExpectExtractMethodToFailAsync(code); } [WorkItem(541586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541586")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task StructThis() { var code = @"struct S { void Goo() { [|this = new S();|] } }"; var expected = @"struct S { void Goo() { NewMethod(); } private void NewMethod() { this = new S(); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(541627, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541627")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task DontUseConvertedTypeForImplicitNumericConversion() { var code = @"class T { void Goo() { int x1 = 5; long x2 = [|x1|]; } }"; var expected = @"class T { void Goo() { int x1 = 5; long x2 = GetX2(x1); } private static int GetX2(int x1) { return x1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(541668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541668")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BreakInSelection() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { string x1 = ""Hello""; switch (x1) { case null: int i1 = 10; break; default: switch (x1) { default: switch (x1) { [|default: int j1 = 99; i1 = 45; x1 = ""t""; string j2 = i1.ToString() + j1.ToString() + x1; break; } break; } break;|] } } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(541671, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541671")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task UnreachableCodeWithReturnStatement() { var code = @"class Program { static void Main(string[] args) { return; [|int i1 = 45; i1 = i1 + 10;|] return; } }"; var expected = @"class Program { static void Main(string[] args) { return; NewMethod(); return; } private static void NewMethod() { int i1 = 45; i1 = i1 + 10; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539862, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539862")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task DontBlindlyPutCapturedVariable1() { var code = @"using System; class Program { private static readonly int v = 5; delegate int Del(int i); static void Main(string[] args) { Ros.A a = new Ros.A(); Del d = (int x) => { [|a.F(x)|]; return x * v; }; d(3); } } namespace Ros { partial class A { public void F(int s) { } } }"; var expected = @"using System; class Program { private static readonly int v = 5; delegate int Del(int i); static void Main(string[] args) { Ros.A a = new Ros.A(); Del d = (int x) => { NewMethod(x, a); return x * v; }; d(3); } private static void NewMethod(int x, Ros.A a) { a.F(x); } } namespace Ros { partial class A { public void F(int s) { } } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539862, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539862")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task DontBlindlyPutCapturedVariable2() { var code = @"using System; class Program { private static readonly int v = 5; delegate int Del(int i); static void Main(string[] args) { Program p; Del d = (int x) => { [|p = null;|]; return x * v; }; d(3); } }"; var expected = @"using System; class Program { private static readonly int v = 5; delegate int Del(int i); static void Main(string[] args) { Program p; Del d = (int x) => { p = NewMethod(); ; return x * v; }; d(3); } private static Program NewMethod() { return null; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(541889, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541889")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task DontCrashOnRangeVariableSymbol() { var code = @"class Test { public void Linq1() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var lowNums = [|from|] n in numbers where n < 5 select n; } }"; await ExpectExtractMethodToFailAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractRangeVariable() { var code = @"using System.Linq; class Test { public void Linq1() { string[] array = null; var q = from string s in array select [|s|]; } }"; var expected = @"using System.Linq; class Test { public void Linq1() { string[] array = null; var q = from string s in array select GetS(s); } private static string GetS(string s) { return s; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542155, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542155")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task GenericWithErrorType() { var code = @"using Goo.Utilities; class Goo<T> { } class Bar { void gibberish() { Goo<[|Integer|]> x = null; x.IsEmpty(); } } namespace Goo.Utilities { internal static class GooExtensions { public static bool IsEmpty<T>(this Goo<T> source) { return false; } } }"; var expected = @"using Goo.Utilities; class Goo<T> { } class Bar { void gibberish() { Goo<Integer> x = NewMethod(); x.IsEmpty(); } private static Goo<Integer> NewMethod() { return null; } } namespace Goo.Utilities { internal static class GooExtensions { public static bool IsEmpty<T>(this Goo<T> source) { return false; } } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542105, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542105")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task NamedArgument() { var code = @"using System; class C { int this[int x = 5, int y = 7] { get { return 0; } set { } } void Goo() { var y = this[[|y|]: 1]; } }"; var expected = @"using System; class C { int this[int x = 5, int y = 7] { get { return 0; } set { } } void Goo() { var y = GetY(); } private int GetY() { return this[y: 1]; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542213, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542213")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task QueryExpressionVariable() { var code = @"using System; using System.Linq; using System.Collections.Generic; class Program { static void Main(string[] args) { var q2 = from a in Enumerable.Range(1, 2) from b in Enumerable.Range(1, 2) where ([|a == b|]) select a; } }"; var expected = @"using System; using System.Linq; using System.Collections.Generic; class Program { static void Main(string[] args) { var q2 = from a in Enumerable.Range(1, 2) from b in Enumerable.Range(1, 2) where (NewMethod(a, b)) select a; } private static bool NewMethod(int a, int b) { return a == b; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542465, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542465")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task IsExpression() { var code = @"using System; class Class1 { } class IsTest { static void Test(Class1 o) { var b = new Class1() is [|Class1|]; } static void Main() { } }"; var expected = @"using System; class Class1 { } class IsTest { static void Test(Class1 o) { var b = GetB(); } private static bool GetB() { return new Class1() is Class1; } static void Main() { } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542526, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542526")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TypeParametersInConstraint() { var code = @"using System; using System.Collections.Generic; class A { static void Goo<T, S>(T x) where T : IList<S> { var y = [|x.Count|]; } }"; var expected = @"using System; using System.Collections.Generic; class A { static void Goo<T, S>(T x) where T : IList<S> { var y = GetY<T, S>(x); } private static int GetY<T, S>(T x) where T : IList<S> { return x.Count; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542619")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task GlobalNamespaceInReturnType() { var code = @"class Program { class System { class Action { } } static global::System.Action a = () => { global::System.Console.WriteLine(); [|}|]; }"; var expected = @"class Program { class System { class Action { } } static global::System.Action a = GetA(); private static global::System.Action GetA() { return () => { global::System.Console.WriteLine(); }; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542582, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542582")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodExpandSelectionOnFor() { var code = @"using System; class Program { static void Main(string[] args) { for (int i = 0; i < 10; i++) [|{ Console.WriteLine(i);|] } } }"; var expected = @"using System; class Program { static void Main(string[] args) { for (int i = 0; i < 10; i++) NewMethod(i); } private static void NewMethod(int i) { Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodNotContainerOnFor() { var code = @"using System; class Program { static void Main(string[] args) { for (int i = 0; i < [|10|]; i++) ; } }"; var expected = @"using System; class Program { static void Main(string[] args) { for (int i = 0; i < NewMethod(); i++) ; } private static int NewMethod() { return 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodExpandSelectionOnForeach() { var code = @"using System; class Program { static void Main(string[] args) { foreach (var c in ""123"") [|{ Console.Write(c);|] } } }"; var expected = @"using System; class Program { static void Main(string[] args) { foreach (var c in ""123"") NewMethod(c); } private static void NewMethod(char c) { Console.Write(c); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodNotContainerOnForeach() { var code = @"using System; class Program { static void Main(string[] args) { foreach (var c in [|""123""|]) { Console.Write(c); } } }"; var expected = @"using System; class Program { static void Main(string[] args) { foreach (var c in NewMethod()) { Console.Write(c); } } private static string NewMethod() { return ""123""; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodNotContainerOnElseClause() { var code = @"using System; class Program { static void Main(string[] args) { if ([|true|]) { } else { } } }"; var expected = @"using System; class Program { static void Main(string[] args) { if (NewMethod()) { } else { } } private static bool NewMethod() { return true; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodExpandSelectionOnLabel() { var code = @"using System; class Program { static void Main(string[] args) { repeat: Console.WriteLine(""Roslyn"")[|;|] if (true) goto repeat; } }"; var expected = @"using System; class Program { static void Main(string[] args) { repeat: NewMethod(); if (true) goto repeat; } private static void NewMethod() { Console.WriteLine(""Roslyn""); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodNotContainerOnLabel() { var code = @"using System; class Program { static void Main(string[] args) { repeat: Console.WriteLine(""Roslyn""); if ([|true|]) goto repeat; } }"; var expected = @"using System; class Program { static void Main(string[] args) { repeat: Console.WriteLine(""Roslyn""); if (NewMethod()) goto repeat; } private static bool NewMethod() { return true; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodExpandSelectionOnSwitch() { var code = @"using System; class Program { static void Main(string[] args) { switch (args[0]) { case ""1"": Console.WriteLine(""one"")[|;|] break; default: Console.WriteLine(""other""); break; } } }"; var expected = @"using System; class Program { static void Main(string[] args) { switch (args[0]) { case ""1"": NewMethod(); break; default: Console.WriteLine(""other""); break; } } private static void NewMethod() { Console.WriteLine(""one""); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodNotContainerOnSwitch() { var code = @"using System; class Program { static void Main(string[] args) { switch ([|args[0]|]) { case ""1"": Console.WriteLine(""one""); break; default: Console.WriteLine(""other""); break; } } }"; var expected = @"using System; class Program { static void Main(string[] args) { switch (NewMethod(args)) { case ""1"": Console.WriteLine(""one""); break; default: Console.WriteLine(""other""); break; } } private static string NewMethod(string[] args) { return args[0]; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodExpandSelectionOnDo() { var code = @"using System; class Program { static void Main(string[] args) { do [|{ Console.WriteLine(""I don't like"");|] } while (DateTime.Now.DayOfWeek == DayOfWeek.Monday); } }"; var expected = @"using System; class Program { static void Main(string[] args) { do NewMethod(); while (DateTime.Now.DayOfWeek == DayOfWeek.Monday); } private static void NewMethod() { Console.WriteLine(""I don't like""); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodNotContainerOnDo() { var code = @"using System; class Program { static void Main(string[] args) { do { Console.WriteLine(""I don't like""); } while ([|DateTime.Now.DayOfWeek == DayOfWeek.Monday|]); } }"; var expected = @"using System; class Program { static void Main(string[] args) { do { Console.WriteLine(""I don't like""); } while (NewMethod()); } private static bool NewMethod() { return DateTime.Now.DayOfWeek == DayOfWeek.Monday; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodExpandSelectionOnWhile() { var code = @"using System; class Program { static void Main(string[] args) { while (true) [|{ ;|] } } }"; var expected = @"using System; class Program { static void Main(string[] args) { while (true) NewMethod(); } private static void NewMethod() { ; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodExpandSelectionOnStruct() { var code = @"using System; struct Goo { static Action a = () => { Console.WriteLine(); [|}|]; }"; var expected = @"using System; struct Goo { static Action a = GetA(); private static Action GetA() { return () => { Console.WriteLine(); }; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542619")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodIncludeGlobal() { var code = @"class Program { class System { class Action { } } static global::System.Action a = () => { global::System.Console.WriteLine(); [|}|]; static void Main(string[] args) { } }"; var expected = @"class Program { class System { class Action { } } static global::System.Action a = GetA(); private static global::System.Action GetA() { return () => { global::System.Console.WriteLine(); }; } static void Main(string[] args) { } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542582, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542582")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodExpandSelection() { var code = @"class Program { static void Main(string[] args) { for (int i = 0; i < 10; i++) [|{ System.Console.WriteLine(i);|] } } }"; var expected = @"class Program { static void Main(string[] args) { for (int i = 0; i < 10; i++) NewMethod(i); } private static void NewMethod(int i) { System.Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542594, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542594")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodRename1() { var code = @"class Program { static void Main() { [|var i = 42;|] var j = 42; } private static void NewMethod() { } private static void NewMethod2() { } }"; var expected = @"class Program { static void Main() { NewMethod1(); var j = 42; } private static void NewMethod1() { var i = 42; } private static void NewMethod() { } private static void NewMethod2() { } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542594, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542594")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodRename2() { var code = @"class Program { static void Main() { NewMethod1(); [|var j = 42;|] } private static void NewMethod1() { var i = 42; } private static void NewMethod() { } private static void NewMethod2() { } }"; var expected = @"class Program { static void Main() { NewMethod1(); NewMethod3(); } private static void NewMethod3() { var j = 42; } private static void NewMethod1() { var i = 42; } private static void NewMethod() { } private static void NewMethod2() { } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542632")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodInInteractive1() { var code = @"int i; [|i = 2|]; i = 3;"; var expected = @"int i; i = NewMethod(); int NewMethod() { return 2; } i = 3;"; await TestExtractMethodAsync(code, expected, parseOptions: Options.Script); } [WorkItem(542670, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542670")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TypeParametersInConstraint1() { var code = @"using System; using System.Collections.Generic; class A { static void Goo<T, S, U>(T x) where T : IList<S> where S : IList<U> { var y = [|x.Count|]; } }"; var expected = @"using System; using System.Collections.Generic; class A { static void Goo<T, S, U>(T x) where T : IList<S> where S : IList<U> { var y = GetY<T, S>(x); } private static int GetY<T, S>(T x) where T : IList<S> { return x.Count; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(706894, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/706894")] [WorkItem(543012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543012")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TypeParametersInConstraint2() { var code = @" using System; interface I<T> where T : IComparable<T> { int Count { get; } } class A { static void Goo<T, S>(S x) where S : I<T> where T : IComparable<T> { var y = [|x.Count|]; } } "; var expected = @" using System; interface I<T> where T : IComparable<T> { int Count { get; } } class A { static void Goo<T, S>(S x) where S : I<T> where T : IComparable<T> { var y = GetY<T, S>(x); } private static int GetY<T, S>(S x) where T : IComparable<T> where S : I<T> { return x.Count; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(706894, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/706894")] [WorkItem(543012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543012")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TypeParametersInConstraint3() { var code = @" using System; interface I<T> where T : class { int Count { get; } } class A { static void Goo<T, S>(S x) where S : I<T> where T : class { var y = [|x.Count|]; } } "; var expected = @" using System; interface I<T> where T : class { int Count { get; } } class A { static void Goo<T, S>(S x) where S : I<T> where T : class { var y = GetY<T, S>(x); } private static int GetY<T, S>(S x) where T : class where S : I<T> { return x.Count; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(543012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543012")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TypeParametersInConstraint4() { var code = @" using System; using System.Collections.Generic; interface I<T> where T : class { } interface I2<T1, T2> : I<T1> where T1 : class, IEnumerable<T2> where T2 : struct { int Count { get; } } class A { public virtual void Goo<T, S>(S x) where S : IList<I2<IEnumerable<T>, T>> where T : struct { } } class B : A { public override void Goo<T, S>(S x) { var y = [|x.Count|]; } } "; var expected = @" using System; using System.Collections.Generic; interface I<T> where T : class { } interface I2<T1, T2> : I<T1> where T1 : class, IEnumerable<T2> where T2 : struct { int Count { get; } } class A { public virtual void Goo<T, S>(S x) where S : IList<I2<IEnumerable<T>, T>> where T : struct { } } class B : A { public override void Goo<T, S>(S x) { var y = GetY<T, S>(x); } private static int GetY<T, S>(S x) where T : struct where S : IList<I2<IEnumerable<T>, T>> { return x.Count; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(543012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543012")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TypeParametersInConstraintBestEffort() { var code = @" using System; using System.Collections.Generic; using System.Linq; class A<T> { public virtual void Test<S>(S s) where S : T { } } class B : A<string> { public override void Test<S>(S s) { var t = [|s.ToString()|]; } } "; var expected = @" using System; using System.Collections.Generic; using System.Linq; class A<T> { public virtual void Test<S>(S s) where S : T { } } class B : A<string> { public override void Test<S>(S s) { var t = GetT(s); } private static string GetT<S>(S s) where S : string { return s.ToString(); } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(542672, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542672")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ConstructedTypes() { var code = @"using System; using System.Collections.Generic; class Program { static void Goo<T>() { List<T> x = new List<T>(); Action a = () => Console.WriteLine([|x.Count|]); } }"; var expected = @"using System; using System.Collections.Generic; class Program { static void Goo<T>() { List<T> x = new List<T>(); Action a = () => Console.WriteLine(GetCount(x)); } private static int GetCount<T>(List<T> x) { return x.Count; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542792, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542792")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TypeInDefault() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { Node<int, Exception> node = new Node<int, Exception>(); } } class Node<K, T> where T : new() { public K Key; public T Item; public Node<K, T> NextNode; public Node() { Key = default([|K|]); Item = new T(); NextNode = null; Console.WriteLine(Key); } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { Node<int, Exception> node = new Node<int, Exception>(); } } class Node<K, T> where T : new() { public K Key; public T Item; public Node<K, T> NextNode; public Node() { Key = NewMethod(); Item = new T(); NextNode = null; Console.WriteLine(Key); } private static K NewMethod() { return default(K); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542708, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542708")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Script_ArgumentException() { var code = @"using System; public static void GetNonVirtualMethod<TDelegate>( Type type, string name) { Type delegateType = typeof(TDelegate); var invoke = [|delegateType|].GetMethod(""Invoke""); }"; var expected = @"using System; public static void GetNonVirtualMethod<TDelegate>( Type type, string name) { Type delegateType = typeof(TDelegate); var invoke = GetDelegateType(delegateType).GetMethod(""Invoke""); } Type GetDelegateType(Type delegateType) { return delegateType; }"; await TestExtractMethodAsync(code, expected, parseOptions: Options.Script); } [WorkItem(529008, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529008")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ReadOutSideIsUnReachable() { var code = @"class Test { public static void Main() { string str = string.Empty; object obj; [|lock (new string[][] { new string[] { str }, new string[] { str } }) { obj = new object(); return; }|] System.Console.Write(obj); } }"; var expected = @"class Test { public static void Main() { string str = string.Empty; object obj; NewMethod(str, out obj); return; System.Console.Write(obj); } private static void NewMethod(string str, out object obj) { lock (new string[][] { new string[] { str }, new string[] { str } }) { obj = new object(); return; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(543186, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543186")] public async Task AnonymousTypePropertyName() { var code = @"class C { void M() { var x = new { [|String|] = true }; } }"; var expected = @"class C { void M() { NewMethod(); } private static void NewMethod() { var x = new { String = true }; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(543662, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543662")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ArgumentOfBaseConstrInit() { var code = @"class O { public O(int t) : base([|t|]) { } }"; var expected = @"class O { public O(int t) : base(GetT(t)) { } private static int GetT(int t) { return t; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task UnsafeType() { var code = @" unsafe class O { unsafe public O(int t) { [|t = 1;|] } }"; var expected = @" unsafe class O { unsafe public O(int t) { t = NewMethod(); } private static int NewMethod() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(544144, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544144")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task CastExpressionWithImplicitUserDefinedConversion() { var code = @" class C { static public implicit operator long(C i) { return 5; } static void Main() { C c = new C(); int y1 = [|(int)c|]; } }"; var expected = @" class C { static public implicit operator long(C i) { return 5; } static void Main() { C c = new C(); int y1 = GetY1(c); } private static int GetY1(C c) { return (int)c; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(544387, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544387")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task FixedPointerVariable() { var code = @" class Test { static int x = 0; unsafe static void Main() { fixed (int* p1 = &x) { int a1 = [|*p1|]; } } }"; var expected = @" class Test { static int x = 0; unsafe static void Main() { fixed (int* p1 = &x) { int a1 = GetA1(p1); } } private static unsafe int GetA1(int* p1) { return *p1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(544444, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544444")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task PointerDeclarationStatement() { var code = @" class Program { unsafe static void Main() { int* p1 = null; [|int* p2 = p1;|] } }"; var expected = @" class Program { unsafe static void Main() { int* p1 = null; NewMethod(p1); } private static unsafe void NewMethod(int* p1) { int* p2 = p1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(544446, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544446")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task PrecededByCastExpr() { var code = @" class Program { static void Main() { int i1 = (int)[|5L|]; } }"; var expected = @" class Program { static void Main() { int i1 = (int)NewMethod(); } private static long NewMethod() { return 5L; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542944")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExpressionWithLocalConst() { var code = @"class Program { static void Main(string[] args) { const string a = null; [|a = null;|] } }"; var expected = @"class Program { static void Main(string[] args) { const string a = null; a = NewMethod(a); } private static string NewMethod(string a) { a = null; return a; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542944")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExpressionWithLocalConst2() { var code = @"class Program { static void Main(string[] args) { const string a = null; [|a = null;|] } }"; var expected = @"class Program { static void Main(string[] args) { const string a = null; a = NewMethod(a); } private static string NewMethod(string a) { a = null; return a; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(544675, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544675")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task HiddenPosition() { var code = @"class Program { static void Main(string[] args) { const string a = null; [|a = null;|] } #line default #line hidden }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(530609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530609")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task NoCrashInteractive() { var code = @"[|if (true) { }|]"; var expected = @"NewMethod(); void NewMethod() { if (true) { } }"; await TestExtractMethodAsync(code, expected, parseOptions: new CSharpParseOptions(kind: SourceCodeKind.Script)); } [WorkItem(530322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530322")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodShouldNotBreakFormatting() { var code = @"class C { void M(int i, int j, int k) { M(0, [|1|], 2); } }"; var expected = @"class C { void M(int i, int j, int k) { M(0, NewMethod(), 2); } private static int NewMethod() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(604389, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/604389")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestExtractLiteralExpression() { var code = @"class Program { static void Main() { var c = new C { X = { Y = { [|1|] } } }; } } class C { public dynamic X; }"; var expected = @"class Program { static void Main() { var c = new C { X = { Y = { NewMethod() } } }; } private static int NewMethod() { return 1; } } class C { public dynamic X; }"; await TestExtractMethodAsync(code, expected); } [WorkItem(604389, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/604389")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestExtractCollectionInitializer() { var code = @"class Program { static void Main() { var c = new C { X = { Y = [|{ 1 }|] } }; } } class C { public dynamic X; }"; var expected = @"class Program { static void Main() { var c = GetC(); } private static C GetC() { return new C { X = { Y = { 1 } } }; } } class C { public dynamic X; }"; await TestExtractMethodAsync(code, expected); } [WorkItem(854662, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/854662")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestExtractCollectionInitializer2() { var code = @"using System; using System.Collections.Generic; class Program { public Dictionary<int, int> A { get; private set; } static int Main(string[] args) { int a = 0; return new Program { A = { { [|a + 2|], 0 } } }.A.Count; } }"; var expected = @"using System; using System.Collections.Generic; class Program { public Dictionary<int, int> A { get; private set; } static int Main(string[] args) { int a = 0; return new Program { A = { { NewMethod(a), 0 } } }.A.Count; } private static int NewMethod(int a) { return a + 2; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(530267, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530267")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestCoClassImplicitConversion() { var code = @"using System; using System.Runtime.InteropServices; [CoClass(typeof(C))] [ComImport] [Guid(""8D3A7A55-A8F5-4669-A5AD-996A3EB8F2ED"")] interface I { } class C : I { static void Main() { [|new I()|]; // Extract Method } }"; var expected = @"using System; using System.Runtime.InteropServices; [CoClass(typeof(C))] [ComImport] [Guid(""8D3A7A55-A8F5-4669-A5AD-996A3EB8F2ED"")] interface I { } class C : I { static void Main() { NewMethod(); // Extract Method } private static I NewMethod() { return new I(); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(530710, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530710")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestOverloadResolution() { var code = @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(object y, Action<string> x) { Console.WriteLine(1); } static void Outer(string y, Action<int> x) { Console.WriteLine(2); } static void Main() { Outer(null, y => Inner(x => { [|x|].Ex(); }, y)); // Prints 1 } } static class E { public static void Ex(this int x) { } }"; var expected = @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(object y, Action<string> x) { Console.WriteLine(1); } static void Outer(string y, Action<int> x) { Console.WriteLine(2); } static void Main() { Outer(null, (Action<string>)(y => Inner(x => { GetX(x).Ex(); }, y))); // Prints 1 } private static string GetX(string x) { return x; } } static class E { public static void Ex(this int x) { } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(530710, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530710")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestOverloadResolution1() { var code = @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(object y, Action<string> x) { Console.WriteLine(1); } static void Outer(string y, Action<int> x) { Console.WriteLine(2); } static void Main() { Outer(null, y => Inner(x => { [|x.Ex()|]; }, y)); // Prints 1 } } static class E { public static void Ex(this int x) { } }"; var expected = @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(object y, Action<string> x) { Console.WriteLine(1); } static void Outer(string y, Action<int> x) { Console.WriteLine(2); } static void Main() { Outer(null, (Action<string>)(y => Inner(x => { NewMethod(x); }, y))); // Prints 1 } private static void NewMethod(string x) { x.Ex(); } } static class E { public static void Ex(this int x) { } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(530710, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530710")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestOverloadResolution2() { var code = @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(object y, Action<string> x) { Console.WriteLine(1); } static void Outer(string y, Action<int> x) { Console.WriteLine(2); } static void Main() { Outer(null, y => Inner(x => { [|x.Ex();|] }, y)); // Prints 1 } } static class E { public static void Ex(this int x) { } }"; var expected = @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(object y, Action<string> x) { Console.WriteLine(1); } static void Outer(string y, Action<int> x) { Console.WriteLine(2); } static void Main() { Outer(null, (Action<string>)(y => Inner(x => { NewMethod(x); }, y))); // Prints 1 } private static void NewMethod(string x) { x.Ex(); } } static class E { public static void Ex(this int x) { } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(731924, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/731924")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestTreatEnumSpecial() { var code = @"using System; class Program { public enum A { A1, A2 } static void Main(string[] args) { A a = A.A1; [|Console.WriteLine(a);|] } }"; var expected = @"using System; class Program { public enum A { A1, A2 } static void Main(string[] args) { A a = A.A1; NewMethod(a); } private static void NewMethod(A a) { Console.WriteLine(a); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(756222, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756222")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestReturnStatementInAsyncMethod() { var code = @"using System.Threading.Tasks; class C { async Task<int> M() { await Task.Yield(); [|return 3;|] } }"; var expected = @"using System.Threading.Tasks; class C { async Task<int> M() { await Task.Yield(); return NewMethod(); } private static int NewMethod() { return 3; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(574576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/574576")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestAsyncMethodWithRefOrOutParameters() { var code = @"using System.Threading.Tasks; class C { public async void Goo() { [|var q = 1; var p = 2; await Task.Yield();|] var r = q; var s = p; } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(1025272, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1025272")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestAsyncMethodWithWellKnownValueType() { var code = @"using System; using System.Threading; using System.Threading.Tasks; class Program { public async Task Hello() { var cancellationToken = CancellationToken.None; [|var i = await Task.Run(() => { Console.WriteLine(); cancellationToken.ThrowIfCancellationRequested(); return 1; }, cancellationToken);|] cancellationToken.ThrowIfCancellationRequested(); Console.WriteLine(i); } }"; var expected = @"using System; using System.Threading; using System.Threading.Tasks; class Program { public async Task Hello() { var cancellationToken = CancellationToken.None; int i = await NewMethod(ref cancellationToken); cancellationToken.ThrowIfCancellationRequested(); Console.WriteLine(i); } private static async Task<int> NewMethod(ref CancellationToken cancellationToken) { return await Task.Run(() => { Console.WriteLine(); cancellationToken.ThrowIfCancellationRequested(); return 1; }, cancellationToken); } }"; await ExpectExtractMethodToFailAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestAsyncMethodWithWellKnownValueType1() { var code = @"using System; using System.Threading; using System.Threading.Tasks; class Program { public async Task Hello() { var cancellationToken = CancellationToken.None; [|var i = await Task.Run(() => { Console.WriteLine(); cancellationToken = CancellationToken.None; return 1; }, cancellationToken);|] cancellationToken.ThrowIfCancellationRequested(); Console.WriteLine(i); } }"; await ExpectExtractMethodToFailAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestDontPutOutOrRefForStructOff() { var code = @"using System.Threading.Tasks; namespace ClassLibrary9 { public struct S { public int I; } public class Class1 { private async Task<int> Test() { S s = new S(); s.I = 10; [|int i = await Task.Run(() => { var i2 = s.I; return Test(); });|] return i; } } }"; await ExpectExtractMethodToFailAsync(code, dontPutOutOrRefOnStruct: false); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestDontPutOutOrRefForStructOn() { var code = @"using System.Threading.Tasks; namespace ClassLibrary9 { public struct S { public int I; } public class Class1 { private async Task<int> Test() { S s = new S(); s.I = 10; [|int i = await Task.Run(() => { var i2 = s.I; return Test(); });|] return i; } } }"; var expected = @"using System.Threading.Tasks; namespace ClassLibrary9 { public struct S { public int I; } public class Class1 { private async Task<int> Test() { S s = new S(); s.I = 10; int i = await NewMethod(s); return i; } private async Task<int> NewMethod(S s) { return await Task.Run(() => { var i2 = s.I; return Test(); }); } } }"; await TestExtractMethodAsync(code, expected, dontPutOutOrRefOnStruct: true); } [Theory] [InlineData("add", "remove")] [InlineData("remove", "add")] [WorkItem(17474, "https://github.com/dotnet/roslyn/issues/17474")] [Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestExtractMethodEventAccessorUnresolvedName(string testedAccessor, string untestedAccessor) { // This code intentionally omits a 'using System;' var code = $@"namespace ClassLibrary9 {{ public class Class {{ public event EventHandler Event {{ {testedAccessor} {{ [|throw new NotImplementedException();|] }} {untestedAccessor} {{ throw new NotImplementedException(); }} }} }} }}"; var expected = $@"namespace ClassLibrary9 {{ public class Class {{ public event EventHandler Event {{ {testedAccessor} {{ NewMethod(); }} {untestedAccessor} {{ throw new NotImplementedException(); }} }} private static void NewMethod() {{ throw new NotImplementedException(); }} }} }}"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(19958, "https://github.com/dotnet/roslyn/issues/19958")] public async Task TestExtractMethodRefPassThrough() { var code = @"using System; namespace ClassLibrary9 { internal class ClassExtensions { public static int OtherMethod(ref int x) => x; public static void Method(ref int x) => Console.WriteLine(OtherMethod(ref [|x|])); } }"; var expected = @"using System; namespace ClassLibrary9 { internal class ClassExtensions { public static int OtherMethod(ref int x) => x; public static void Method(ref int x) => Console.WriteLine(OtherMethod(ref $x$)); public static ref int NewMethod(ref int x) { return ref x; } } }"; await TestExtractMethodAsync(code, expected, temporaryFailing: true); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(19958, "https://github.com/dotnet/roslyn/issues/19958")] public async Task TestExtractMethodRefPassThroughDuplicateVariable() { var code = @"using System; namespace ClassLibrary9 { internal interface IClass { bool InterfaceMethod(ref Guid x, out IOtherClass y); } internal interface IOtherClass { bool OtherInterfaceMethod(); } internal static class ClassExtensions { public static void Method(this IClass instance, Guid guid) { var r = instance.InterfaceMethod(ref [|guid|], out IOtherClass guid); if (!r) return; r = guid.OtherInterfaceMethod(); if (r) throw null; } } }"; var expected = @"using System; namespace ClassLibrary9 { internal interface IClass { bool InterfaceMethod(ref Guid x, out IOtherClass y); } internal interface IOtherClass { bool OtherInterfaceMethod(); } internal static class ClassExtensions { public static void Method(this IClass instance, Guid guid) { var r = instance.InterfaceMethod(ref NewMethod(ref guid), out IOtherClass guid); if (!r) return; r = guid.OtherInterfaceMethod(); if (r) throw null; } public static ref Guid NewMethod(ref Guid guid) { return ref guid; } } }"; await TestExtractMethodAsync(code, expected, temporaryFailing: true); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod_Argument1() { var service = new CSharpExtractMethodService(); Assert.NotNull(await Record.ExceptionAsync(async () => { var tree = await service.ExtractMethodAsync(document: null, textSpan: default, localFunction: false, options: null, CancellationToken.None); })); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod_Argument2() { var solution = new AdhocWorkspace().CurrentSolution; var projectId = ProjectId.CreateNewId(); var project = solution.AddProject(projectId, "Project", "Project.dll", LanguageNames.CSharp).GetProject(projectId); var document = project.AddMetadataReference(TestMetadata.Net451.mscorlib) .AddDocument("Document", SourceText.From("")); var service = new CSharpExtractMethodService() as IExtractMethodService; await service.ExtractMethodAsync(document, textSpan: default, localFunction: false); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ExtractMethod)] [Trait(Traits.Feature, Traits.Features.Interactive)] public void ExtractMethodCommandDisabledInSubmission() { using var workspace = TestWorkspace.Create(XElement.Parse(@" <Workspace> <Submission Language=""C#"" CommonReferences=""true""> typeof(string).$$Name </Submission> </Workspace> "), workspaceKind: WorkspaceKind.Interactive, composition: EditorTestCompositions.EditorFeaturesWpf); // Force initialization. workspace.GetOpenDocumentIds().Select(id => workspace.GetTestDocument(id).GetTextView()).ToList(); var textView = workspace.Documents.Single().GetTextView(); var handler = workspace.ExportProvider.GetCommandHandler<ExtractMethodCommandHandler>(PredefinedCommandHandlerNames.ExtractMethod, ContentTypeNames.CSharpContentType); var state = handler.GetCommandState(new ExtractMethodCommandArgs(textView, textView.TextBuffer)); Assert.True(state.IsUnspecified); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(18347, "https://github.com/dotnet/roslyn/issues/18347")] public async Task ExtractMethodUnreferencedLocalFunction1() { var code = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { [|int localValue = arg;|] int LocalCapture() => arg; } } }"; var expected = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { NewMethod(arg); int LocalCapture() => arg; } private static void NewMethod(int arg) { int localValue = arg; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(18347, "https://github.com/dotnet/roslyn/issues/18347")] public async Task ExtractMethodUnreferencedLocalFunction2() { var code = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { int LocalCapture() => arg; [|int localValue = arg;|] } } }"; var expected = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { int LocalCapture() => arg; NewMethod(arg); } private static void NewMethod(int arg) { int localValue = arg; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(18347, "https://github.com/dotnet/roslyn/issues/18347")] public async Task ExtractMethodUnreferencedLocalFunction3() { var code = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { [|arg = arg + 3;|] int LocalCapture() => arg; } } }"; var expected = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { arg = NewMethod(arg); int LocalCapture() => arg; } private static int NewMethod(int arg) { arg = arg + 3; return arg; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(18347, "https://github.com/dotnet/roslyn/issues/18347")] public async Task ExtractMethodUnreferencedLocalFunction4() { var code = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { int LocalCapture() => arg; [|arg = arg + 3;|] } } }"; var expected = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { int LocalCapture() => arg; arg = NewMethod(arg); } private static int NewMethod(int arg) { arg = arg + 3; return arg; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(18347, "https://github.com/dotnet/roslyn/issues/18347")] public async Task ExtractMethodUnreferencedLocalFunction5() { var code = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { [|arg = arg + 3;|] arg = 1; int LocalCapture() => arg; } } }"; var expected = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { arg = NewMethod(arg); arg = 1; int LocalCapture() => arg; } private static int NewMethod(int arg) { arg = arg + 3; return arg; } } }"; await TestExtractMethodAsync(code, expected); } [Theory] [InlineData("LocalCapture();")] [InlineData("System.Func<int> function = LocalCapture;")] [InlineData("System.Func<int> function = () => LocalCapture();")] [Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(18347, "https://github.com/dotnet/roslyn/issues/18347")] public async Task ExtractMethodFlowsToLocalFunction1(string usageSyntax) { var code = $@"namespace ExtractMethodCrashRepro {{ public static class SomeClass {{ private static void Repro( int arg ) {{ [|arg = arg + 3;|] {usageSyntax} int LocalCapture() => arg; }} }} }}"; var expected = $@"namespace ExtractMethodCrashRepro {{ public static class SomeClass {{ private static void Repro( int arg ) {{ arg = NewMethod(arg); {usageSyntax} int LocalCapture() => arg; }} private static int NewMethod(int arg) {{ arg = arg + 3; return arg; }} }} }}"; await TestExtractMethodAsync(code, expected); } [Theory] [InlineData("LocalCapture();")] [InlineData("System.Func<int> function = LocalCapture;")] [InlineData("System.Func<int> function = () => LocalCapture();")] [Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(18347, "https://github.com/dotnet/roslyn/issues/18347")] public async Task ExtractMethodFlowsToLocalFunction2(string usageSyntax) { var code = $@"namespace ExtractMethodCrashRepro {{ public static class SomeClass {{ private static void Repro( int arg ) {{ int LocalCapture() => arg; [|arg = arg + 3;|] {usageSyntax} }} }} }}"; var expected = $@"namespace ExtractMethodCrashRepro {{ public static class SomeClass {{ private static void Repro( int arg ) {{ int LocalCapture() => arg; arg = NewMethod(arg); {usageSyntax} }} private static int NewMethod(int arg) {{ arg = arg + 3; return arg; }} }} }}"; await TestExtractMethodAsync(code, expected); } /// <summary> /// This test verifies that Extract Method works properly when the region to extract references a local /// function, the local function uses an unassigned but wholly local variable. /// </summary> [Theory] [InlineData("LocalCapture();")] [InlineData("System.Func<int> function = LocalCapture;")] [InlineData("System.Func<int> function = () => LocalCapture();")] [Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(18347, "https://github.com/dotnet/roslyn/issues/18347")] public async Task ExtractMethodFlowsToLocalFunctionWithUnassignedLocal(string usageSyntax) { var code = $@"namespace ExtractMethodCrashRepro {{ public static class SomeClass {{ private static void Repro( int arg ) {{ int local; int LocalCapture() => arg + local; [|arg = arg + 3;|] {usageSyntax} }} }} }}"; var expected = $@"namespace ExtractMethodCrashRepro {{ public static class SomeClass {{ private static void Repro( int arg ) {{ int local; int LocalCapture() => arg + local; arg = NewMethod(arg); {usageSyntax} }} private static int NewMethod(int arg) {{ arg = arg + 3; return arg; }} }} }}"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(18347, "https://github.com/dotnet/roslyn/issues/18347")] public async Task ExtractMethodDoesNotFlowToLocalFunction1() { var code = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { [|arg = arg + 3;|] arg = 1; int LocalCapture() => arg; } } }"; var expected = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { arg = NewMethod(arg); arg = 1; int LocalCapture() => arg; } private static int NewMethod(int arg) { arg = arg + 3; return arg; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestUnreachableCodeModifiedInside() { var code = @"using System.Collections.Generic; using System.Linq; namespace ConsoleApp1 { class Test { IEnumerable<object> Crash0(IEnumerable<object> enumerable) { [|while (true) ; enumerable = null; var i = enumerable.Any(); return enumerable;|] } } }"; var expected = @"using System.Collections.Generic; using System.Linq; namespace ConsoleApp1 { class Test { IEnumerable<object> Crash0(IEnumerable<object> enumerable) { return NewMethod(ref enumerable); } private static IEnumerable<object> NewMethod(ref IEnumerable<object> enumerable) { while (true) ; enumerable = null; var i = enumerable.Any(); return enumerable; } } }"; // allowMovingDeclaration: false is default behavior on VS. // it doesn't affect result mostly but it does affect for symbols in unreachable code since // data flow in and out for the symbol is always set to false await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestUnreachableCodeModifiedOutside() { var code = @"using System.Collections.Generic; using System.Linq; namespace ConsoleApp1 { class Test { IEnumerable<object> Crash0(IEnumerable<object> enumerable) { [|while (true) ; var i = enumerable.Any();|] enumerable = null; return enumerable; } } }"; var expected = @"using System.Collections.Generic; using System.Linq; namespace ConsoleApp1 { class Test { IEnumerable<object> Crash0(IEnumerable<object> enumerable) { NewMethod(enumerable); enumerable = null; return enumerable; } private static void NewMethod(IEnumerable<object> enumerable) { while (true) ; var i = enumerable.Any(); } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestUnreachableCodeModifiedBoth() { var code = @"using System.Collections.Generic; using System.Linq; namespace ConsoleApp1 { class Test { IEnumerable<object> Crash0(IEnumerable<object> enumerable) { [|while (true) ; enumerable = null; var i = enumerable.Any();|] enumerable = null; return enumerable; } } }"; var expected = @"using System.Collections.Generic; using System.Linq; namespace ConsoleApp1 { class Test { IEnumerable<object> Crash0(IEnumerable<object> enumerable) { enumerable = NewMethod(enumerable); enumerable = null; return enumerable; } private static IEnumerable<object> NewMethod(IEnumerable<object> enumerable) { while (true) ; enumerable = null; var i = enumerable.Any(); return enumerable; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestLocalFunctionParameters() { var code = @"using System.Collections.Generic; using System.Linq; namespace ConsoleApp1 { class Test { public void Bar(int value) { void Local(int value2) { [|Bar(value, value2);|] } } } }"; var expected = @"using System.Collections.Generic; using System.Linq; namespace ConsoleApp1 { class Test { public void Bar(int value) { void Local(int value2) { NewMethod(value, value2); } } private void NewMethod(int value, int value2) { Bar(value, value2); } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestDataFlowInButNoReadInside() { var code = @"using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp39 { class Program { void Method(out object test) { test = null; var a = test != null; [|if (a) { return; } if (A == a) { test = new object(); }|] } } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp39 { class Program { void Method(out object test) { test = null; var a = test != null; NewMethod(ref test, a); } private static void NewMethod(ref object test, bool a) { if (a) { return; } if (A == a) { test = new object(); } } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task AllowBestEffortForUnknownVariableDataFlow() { var code = @" class Program { void Method(out object test) { test = null; var a = test != null; [|if (a) { return; } if (A == a) { test = new object(); }|] } }"; var expected = @" class Program { void Method(out object test) { test = null; var a = test != null; NewMethod(ref test, a); } private static void NewMethod(ref object test, bool a) { if (a) { return; } if (A == a) { test = new object(); } } }"; await TestExtractMethodAsync(code, expected, allowBestEffort: true); } [WorkItem(30750, "https://github.com/dotnet/roslyn/issues/30750")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodInInterface() { var code = @" interface Program { void Goo(); void Test() { [|Goo();|] } }"; var expected = @" interface Program { void Goo(); void Test() { NewMethod(); } void NewMethod() { Goo(); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(33242, "https://github.com/dotnet/roslyn/issues/33242")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodInExpressionBodiedConstructors() { var code = @" class Goo { private readonly string _bar; private Goo(string bar) => _bar = [|bar|]; }"; var expected = @" class Goo { private readonly string _bar; private Goo(string bar) => _bar = GetBar(bar); private static string GetBar(string bar) { return bar; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(33242, "https://github.com/dotnet/roslyn/issues/33242")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodInExpressionBodiedFinalizers() { var code = @" class Goo { bool finalized; ~Goo() => finalized = [|true|]; }"; var expected = @" class Goo { bool finalized; ~Goo() => finalized = NewMethod(); private static bool NewMethod() { return true; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodInvolvingFunctionPointer() { var code = @" class C { void M(delegate*<delegate*<ref string, ref readonly int>> ptr1) { string s = null; _ = [|ptr1()|](ref s); } }"; var expected = @" class C { void M(delegate*<delegate*<ref string, ref readonly int>> ptr1) { string s = null; _ = NewMethod(ptr1)(ref s); } private static delegate*<ref string, ref readonly int> NewMethod(delegate*<delegate*<ref string, ref readonly int>> ptr1) { return ptr1(); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodInvolvingFunctionPointerWithTypeParameter() { var code = @" class C { void M<T1, T2>(delegate*<T1, T2> ptr1) { _ = [|ptr1|](); } }"; var expected = @" class C { void M<T1, T2>(delegate*<T1, T2> ptr1) { _ = GetPtr1(ptr1)(); } private static delegate*<T1, T2> GetPtr1<T1, T2>(delegate*<T1, T2> ptr1) { return ptr1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(44260, "https://github.com/dotnet/roslyn/issues/44260")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TopLevelStatement_ValueInAssignment() { var code = @" bool local; local = [|true|]; "; var expected = @" bool local; bool NewMethod() { return true; } local = NewMethod(); "; await TestExtractMethodAsync(code, expected); } [WorkItem(44260, "https://github.com/dotnet/roslyn/issues/44260")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TopLevelStatement_ArgumentInInvocation() { // Note: the cast should be simplified // https://github.com/dotnet/roslyn/issues/44260 var code = @" System.Console.WriteLine([|""string""|]); "; var expected = @" System.Console.WriteLine((string)NewMethod()); string NewMethod() { return ""string""; }"; await TestExtractMethodAsync(code, expected); } [Theory] [InlineData("unsafe")] [InlineData("checked")] [InlineData("unchecked")] [Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(4950, "https://github.com/dotnet/roslyn/issues/4950")] public async Task ExtractMethodInvolvingUnsafeBlock(string keyword) { var code = $@" using System; class Program {{ static void Main(string[] args) {{ object value = args; [| IntPtr p; {keyword} {{ object t = value; p = IntPtr.Zero; }} |] Console.WriteLine(p); }} }} "; var expected = $@" using System; class Program {{ static void Main(string[] args) {{ object value = args; IntPtr p = NewMethod(value); Console.WriteLine(p); }} private static IntPtr NewMethod(object value) {{ IntPtr p; {keyword} {{ object t = value; p = IntPtr.Zero; }} return p; }} }} "; await TestExtractMethodAsync(code, expected); } } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/Engine/DkmClrCustomTypeInfo.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 #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll #endregion using System; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; namespace Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation { [DebuggerDisplay("{DebuggerDisplay, nq}")] public class DkmClrCustomTypeInfo { public readonly Guid PayloadTypeId; public readonly ReadOnlyCollection<byte> Payload; private DkmClrCustomTypeInfo(Guid payloadTypeId, ReadOnlyCollection<byte> payload) { PayloadTypeId = payloadTypeId; Payload = payload; } public static DkmClrCustomTypeInfo Create(Guid payloadTypeId, ReadOnlyCollection<byte> payload) { return new DkmClrCustomTypeInfo(payloadTypeId, payload); } private string DebuggerDisplay => $"[{string.Join(", ", Payload.Select(b => $"0x{b:x2}"))}] from {PayloadTypeId}"; } }
// Licensed to the .NET Foundation under one or more 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 #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll #endregion using System; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; namespace Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation { [DebuggerDisplay("{DebuggerDisplay, nq}")] public class DkmClrCustomTypeInfo { public readonly Guid PayloadTypeId; public readonly ReadOnlyCollection<byte> Payload; private DkmClrCustomTypeInfo(Guid payloadTypeId, ReadOnlyCollection<byte> payload) { PayloadTypeId = payloadTypeId; Payload = payload; } public static DkmClrCustomTypeInfo Create(Guid payloadTypeId, ReadOnlyCollection<byte> payload) { return new DkmClrCustomTypeInfo(payloadTypeId, payload); } private string DebuggerDisplay => $"[{string.Join(", ", Payload.Select(b => $"0x{b:x2}"))}] from {PayloadTypeId}"; } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/Experimentation/ExperimentationOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.VisualStudio.LanguageServices.Experimentation { internal static class ExperimentationOptions { internal const string LocalRegistryPath = @"Roslyn\Internal\Experiment\"; } [ExportOptionProvider, Shared] internal class ExperimentationOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ExperimentationOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray<IOption>.Empty; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.VisualStudio.LanguageServices.Experimentation { internal static class ExperimentationOptions { internal const string LocalRegistryPath = @"Roslyn\Internal\Experiment\"; } [ExportOptionProvider, Shared] internal class ExperimentationOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ExperimentationOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray<IOption>.Empty; } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/Implementation/KeywordHighlighting/HighlighterViewTaggerProvider.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.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Highlighting { [Export(typeof(IViewTaggerProvider))] [TagType(typeof(KeywordHighlightTag))] [ContentType(ContentTypeNames.CSharpContentType)] [ContentType(ContentTypeNames.VisualBasicContentType)] [TextViewRole(PredefinedTextViewRoles.Interactive)] internal class HighlighterViewTaggerProvider : AsynchronousViewTaggerProvider<KeywordHighlightTag> { private readonly IHighlightingService _highlightingService; private static readonly PooledObjects.ObjectPool<List<TextSpan>> s_listPool = new(() => new List<TextSpan>()); // Whenever an edit happens, clear all highlights. When moving the caret, preserve // highlights if the caret stays within an existing tag. protected override TaggerCaretChangeBehavior CaretChangeBehavior => TaggerCaretChangeBehavior.RemoveAllTagsOnCaretMoveOutsideOfTag; protected override TaggerTextChangeBehavior TextChangeBehavior => TaggerTextChangeBehavior.RemoveAllTags; protected override IEnumerable<PerLanguageOption2<bool>> PerLanguageOptions => SpecializedCollections.SingletonEnumerable(FeatureOnOffOptions.KeywordHighlighting); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public HighlighterViewTaggerProvider( IThreadingContext threadingContext, IHighlightingService highlightingService, IAsynchronousOperationListenerProvider listenerProvider) : base(threadingContext, listenerProvider.GetListener(FeatureAttribute.KeywordHighlighting)) { _highlightingService = highlightingService; } protected override TaggerDelay EventChangeDelay => TaggerDelay.NearImmediate; protected override ITaggerEventSource CreateEventSource(ITextView textView, ITextBuffer subjectBuffer) { return TaggerEventSources.Compose( TaggerEventSources.OnTextChanged(subjectBuffer), TaggerEventSources.OnCaretPositionChanged(textView, subjectBuffer), TaggerEventSources.OnParseOptionChanged(subjectBuffer)); } protected override async Task ProduceTagsAsync(TaggerContext<KeywordHighlightTag> context, DocumentSnapshotSpan documentSnapshotSpan, int? caretPosition) { var cancellationToken = context.CancellationToken; var document = documentSnapshotSpan.Document; // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/763988 // It turns out a document might be associated with a project of wrong language, e.g. C# document in a Xaml project. // Even though we couldn't repro the crash above, a fix is made in one of possibly multiple code paths that could cause // us to end up in this situation. // Regardless of the effective of the fix, we want to enhance the guard against such scenario here until an audit in // workspace is completed to eliminate the root cause. if (document?.SupportsSyntaxTree != true) { return; } var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); if (!documentOptions.GetOption(FeatureOnOffOptions.KeywordHighlighting)) { return; } if (!caretPosition.HasValue) { return; } var snapshotSpan = documentSnapshotSpan.SnapshotSpan; var position = caretPosition.Value; var snapshot = snapshotSpan.Snapshot; // See if the user is just moving their caret around in an existing tag. If so, we don't // want to actually go recompute things. Note: this only works for containment. If the // user moves their caret to the end of a highlighted reference, we do want to recompute // as they may now be at the start of some other reference that should be highlighted instead. var existingTags = context.GetExistingContainingTags(new SnapshotPoint(snapshot, position)); if (!existingTags.IsEmpty()) { context.SetSpansTagged(SpecializedCollections.EmptyEnumerable<DocumentSnapshotSpan>()); return; } using (Logger.LogBlock(FunctionId.Tagger_Highlighter_TagProducer_ProduceTags, cancellationToken)) using (s_listPool.GetPooledObject(out var highlights)) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); _highlightingService.AddHighlights(root, position, highlights, cancellationToken); foreach (var span in highlights) { context.AddTag(new TagSpan<KeywordHighlightTag>(span.ToSnapshotSpan(snapshot), KeywordHighlightTag.Instance)); } } } } }
// Licensed to the .NET Foundation under one or more 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.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Highlighting { [Export(typeof(IViewTaggerProvider))] [TagType(typeof(KeywordHighlightTag))] [ContentType(ContentTypeNames.CSharpContentType)] [ContentType(ContentTypeNames.VisualBasicContentType)] [TextViewRole(PredefinedTextViewRoles.Interactive)] internal class HighlighterViewTaggerProvider : AsynchronousViewTaggerProvider<KeywordHighlightTag> { private readonly IHighlightingService _highlightingService; private static readonly PooledObjects.ObjectPool<List<TextSpan>> s_listPool = new(() => new List<TextSpan>()); // Whenever an edit happens, clear all highlights. When moving the caret, preserve // highlights if the caret stays within an existing tag. protected override TaggerCaretChangeBehavior CaretChangeBehavior => TaggerCaretChangeBehavior.RemoveAllTagsOnCaretMoveOutsideOfTag; protected override TaggerTextChangeBehavior TextChangeBehavior => TaggerTextChangeBehavior.RemoveAllTags; protected override IEnumerable<PerLanguageOption2<bool>> PerLanguageOptions => SpecializedCollections.SingletonEnumerable(FeatureOnOffOptions.KeywordHighlighting); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public HighlighterViewTaggerProvider( IThreadingContext threadingContext, IHighlightingService highlightingService, IAsynchronousOperationListenerProvider listenerProvider) : base(threadingContext, listenerProvider.GetListener(FeatureAttribute.KeywordHighlighting)) { _highlightingService = highlightingService; } protected override TaggerDelay EventChangeDelay => TaggerDelay.NearImmediate; protected override ITaggerEventSource CreateEventSource(ITextView textView, ITextBuffer subjectBuffer) { return TaggerEventSources.Compose( TaggerEventSources.OnTextChanged(subjectBuffer), TaggerEventSources.OnCaretPositionChanged(textView, subjectBuffer), TaggerEventSources.OnParseOptionChanged(subjectBuffer)); } protected override async Task ProduceTagsAsync(TaggerContext<KeywordHighlightTag> context, DocumentSnapshotSpan documentSnapshotSpan, int? caretPosition) { var cancellationToken = context.CancellationToken; var document = documentSnapshotSpan.Document; // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/763988 // It turns out a document might be associated with a project of wrong language, e.g. C# document in a Xaml project. // Even though we couldn't repro the crash above, a fix is made in one of possibly multiple code paths that could cause // us to end up in this situation. // Regardless of the effective of the fix, we want to enhance the guard against such scenario here until an audit in // workspace is completed to eliminate the root cause. if (document?.SupportsSyntaxTree != true) { return; } var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); if (!documentOptions.GetOption(FeatureOnOffOptions.KeywordHighlighting)) { return; } if (!caretPosition.HasValue) { return; } var snapshotSpan = documentSnapshotSpan.SnapshotSpan; var position = caretPosition.Value; var snapshot = snapshotSpan.Snapshot; // See if the user is just moving their caret around in an existing tag. If so, we don't // want to actually go recompute things. Note: this only works for containment. If the // user moves their caret to the end of a highlighted reference, we do want to recompute // as they may now be at the start of some other reference that should be highlighted instead. var existingTags = context.GetExistingContainingTags(new SnapshotPoint(snapshot, position)); if (!existingTags.IsEmpty()) { context.SetSpansTagged(SpecializedCollections.EmptyEnumerable<DocumentSnapshotSpan>()); return; } using (Logger.LogBlock(FunctionId.Tagger_Highlighter_TagProducer_ProduceTags, cancellationToken)) using (s_listPool.GetPooledObject(out var highlights)) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); _highlightingService.AddHighlights(root, position, highlights, cancellationToken); foreach (var span in highlights) { context.AddTag(new TagSpan<KeywordHighlightTag>(span.ToSnapshotSpan(snapshot), KeywordHighlightTag.Instance)); } } } } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/CodeFixes/UseImplicitOrExplicitType/UseExplicitTypeCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; 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.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.TypeStyle { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseExplicitType), Shared] internal class UseExplicitTypeCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public UseExplicitTypeCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.UseExplicitTypeDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(new MyCodeAction( c => FixAsync(context.Document, context.Diagnostics.First(), c)), context.Diagnostics); return Task.CompletedTask; } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var root = editor.OriginalRoot; foreach (var diagnostic in diagnostics) { var node = root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true); await HandleDeclarationAsync(document, editor, node, cancellationToken).ConfigureAwait(false); } } internal static async Task HandleDeclarationAsync( Document document, SyntaxEditor editor, SyntaxNode node, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var declarationContext = node.Parent; TypeSyntax typeSyntax = null; ParenthesizedVariableDesignationSyntax parensDesignation = null; if (declarationContext is RefTypeSyntax refType) { declarationContext = declarationContext.Parent; } if (declarationContext is VariableDeclarationSyntax varDecl) { typeSyntax = varDecl.Type; } else if (declarationContext is ForEachStatementSyntax forEach) { typeSyntax = forEach.Type; } else if (declarationContext is DeclarationExpressionSyntax declarationExpression) { typeSyntax = declarationExpression.Type; if (declarationExpression.Designation.IsKind(SyntaxKind.ParenthesizedVariableDesignation, out ParenthesizedVariableDesignationSyntax variableDesignation)) { parensDesignation = variableDesignation; } } else { throw ExceptionUtilities.UnexpectedValue(declarationContext.Kind()); } if (parensDesignation is null) { typeSyntax = typeSyntax.StripRefIfNeeded(); // We're going to be passed through the simplifier. Tell it to not just convert this back to var (as // that would defeat the purpose of this refactoring entirely). var newTypeSyntax = semanticModel.GetTypeInfo(typeSyntax, cancellationToken).ConvertedType .GenerateTypeSyntax(allowVar: false) .WithTriviaFrom(typeSyntax); Debug.Assert(!newTypeSyntax.ContainsDiagnostics, "Explicit type replacement likely introduced an error in code"); editor.ReplaceNode(typeSyntax, newTypeSyntax); } else { var tupleTypeSymbol = semanticModel.GetTypeInfo(typeSyntax.Parent, cancellationToken).ConvertedType; var leadingTrivia = node.GetLeadingTrivia() .Concat(parensDesignation.GetAllPrecedingTriviaToPreviousToken().Where(t => !t.IsWhitespace()).Select(t => t.WithoutAnnotations(SyntaxAnnotation.ElasticAnnotation))); var tupleDeclaration = GenerateTupleDeclaration(tupleTypeSymbol, parensDesignation).WithLeadingTrivia(leadingTrivia); editor.ReplaceNode(declarationContext, tupleDeclaration); } } private static ExpressionSyntax GenerateTupleDeclaration(ITypeSymbol typeSymbol, ParenthesizedVariableDesignationSyntax parensDesignation) { Debug.Assert(typeSymbol.IsTupleType); var elements = ((INamedTypeSymbol)typeSymbol).TupleElements; Debug.Assert(elements.Length == parensDesignation.Variables.Count); using var builderDisposer = ArrayBuilder<SyntaxNode>.GetInstance(elements.Length, out var builder); for (var i = 0; i < elements.Length; i++) { var designation = parensDesignation.Variables[i]; var type = elements[i].Type; ExpressionSyntax newDeclaration; switch (designation.Kind()) { case SyntaxKind.SingleVariableDesignation: case SyntaxKind.DiscardDesignation: var typeName = type.GenerateTypeSyntax(allowVar: false); newDeclaration = SyntaxFactory.DeclarationExpression(typeName, designation); break; case SyntaxKind.ParenthesizedVariableDesignation: newDeclaration = GenerateTupleDeclaration(type, (ParenthesizedVariableDesignationSyntax)designation); break; default: throw ExceptionUtilities.UnexpectedValue(designation.Kind()); } newDeclaration = newDeclaration .WithLeadingTrivia(designation.GetAllPrecedingTriviaToPreviousToken()) .WithTrailingTrivia(designation.GetTrailingTrivia()); builder.Add(SyntaxFactory.Argument(newDeclaration)); } var separatorBuilder = ArrayBuilder<SyntaxToken>.GetInstance(builder.Count - 1, SyntaxFactory.Token(leading: default, SyntaxKind.CommaToken, trailing: default)); return SyntaxFactory.TupleExpression( SyntaxFactory.Token(SyntaxKind.OpenParenToken).WithTrailingTrivia(), SyntaxFactory.SeparatedList(builder.ToImmutable(), separatorBuilder.ToImmutableAndFree()), SyntaxFactory.Token(SyntaxKind.CloseParenToken)) .WithTrailingTrivia(parensDesignation.GetTrailingTrivia()); } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpAnalyzersResources.Use_explicit_type_instead_of_var, createChangedDocument, CSharpAnalyzersResources.Use_explicit_type_instead_of_var) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; 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.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.TypeStyle { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseExplicitType), Shared] internal class UseExplicitTypeCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public UseExplicitTypeCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.UseExplicitTypeDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(new MyCodeAction( c => FixAsync(context.Document, context.Diagnostics.First(), c)), context.Diagnostics); return Task.CompletedTask; } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var root = editor.OriginalRoot; foreach (var diagnostic in diagnostics) { var node = root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true); await HandleDeclarationAsync(document, editor, node, cancellationToken).ConfigureAwait(false); } } internal static async Task HandleDeclarationAsync( Document document, SyntaxEditor editor, SyntaxNode node, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var declarationContext = node.Parent; TypeSyntax typeSyntax = null; ParenthesizedVariableDesignationSyntax parensDesignation = null; if (declarationContext is RefTypeSyntax refType) { declarationContext = declarationContext.Parent; } if (declarationContext is VariableDeclarationSyntax varDecl) { typeSyntax = varDecl.Type; } else if (declarationContext is ForEachStatementSyntax forEach) { typeSyntax = forEach.Type; } else if (declarationContext is DeclarationExpressionSyntax declarationExpression) { typeSyntax = declarationExpression.Type; if (declarationExpression.Designation.IsKind(SyntaxKind.ParenthesizedVariableDesignation, out ParenthesizedVariableDesignationSyntax variableDesignation)) { parensDesignation = variableDesignation; } } else { throw ExceptionUtilities.UnexpectedValue(declarationContext.Kind()); } if (parensDesignation is null) { typeSyntax = typeSyntax.StripRefIfNeeded(); // We're going to be passed through the simplifier. Tell it to not just convert this back to var (as // that would defeat the purpose of this refactoring entirely). var newTypeSyntax = semanticModel.GetTypeInfo(typeSyntax, cancellationToken).ConvertedType .GenerateTypeSyntax(allowVar: false) .WithTriviaFrom(typeSyntax); Debug.Assert(!newTypeSyntax.ContainsDiagnostics, "Explicit type replacement likely introduced an error in code"); editor.ReplaceNode(typeSyntax, newTypeSyntax); } else { var tupleTypeSymbol = semanticModel.GetTypeInfo(typeSyntax.Parent, cancellationToken).ConvertedType; var leadingTrivia = node.GetLeadingTrivia() .Concat(parensDesignation.GetAllPrecedingTriviaToPreviousToken().Where(t => !t.IsWhitespace()).Select(t => t.WithoutAnnotations(SyntaxAnnotation.ElasticAnnotation))); var tupleDeclaration = GenerateTupleDeclaration(tupleTypeSymbol, parensDesignation).WithLeadingTrivia(leadingTrivia); editor.ReplaceNode(declarationContext, tupleDeclaration); } } private static ExpressionSyntax GenerateTupleDeclaration(ITypeSymbol typeSymbol, ParenthesizedVariableDesignationSyntax parensDesignation) { Debug.Assert(typeSymbol.IsTupleType); var elements = ((INamedTypeSymbol)typeSymbol).TupleElements; Debug.Assert(elements.Length == parensDesignation.Variables.Count); using var builderDisposer = ArrayBuilder<SyntaxNode>.GetInstance(elements.Length, out var builder); for (var i = 0; i < elements.Length; i++) { var designation = parensDesignation.Variables[i]; var type = elements[i].Type; ExpressionSyntax newDeclaration; switch (designation.Kind()) { case SyntaxKind.SingleVariableDesignation: case SyntaxKind.DiscardDesignation: var typeName = type.GenerateTypeSyntax(allowVar: false); newDeclaration = SyntaxFactory.DeclarationExpression(typeName, designation); break; case SyntaxKind.ParenthesizedVariableDesignation: newDeclaration = GenerateTupleDeclaration(type, (ParenthesizedVariableDesignationSyntax)designation); break; default: throw ExceptionUtilities.UnexpectedValue(designation.Kind()); } newDeclaration = newDeclaration .WithLeadingTrivia(designation.GetAllPrecedingTriviaToPreviousToken()) .WithTrailingTrivia(designation.GetTrailingTrivia()); builder.Add(SyntaxFactory.Argument(newDeclaration)); } var separatorBuilder = ArrayBuilder<SyntaxToken>.GetInstance(builder.Count - 1, SyntaxFactory.Token(leading: default, SyntaxKind.CommaToken, trailing: default)); return SyntaxFactory.TupleExpression( SyntaxFactory.Token(SyntaxKind.OpenParenToken).WithTrailingTrivia(), SyntaxFactory.SeparatedList(builder.ToImmutable(), separatorBuilder.ToImmutableAndFree()), SyntaxFactory.Token(SyntaxKind.CloseParenToken)) .WithTrailingTrivia(parensDesignation.GetTrailingTrivia()); } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpAnalyzersResources.Use_explicit_type_instead_of_var, createChangedDocument, CSharpAnalyzersResources.Use_explicit_type_instead_of_var) { } } } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/EditorConfigSettings/Analyzers/ViewModel/AnalyzerSettingsViewModel.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 Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider; using Microsoft.Internal.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Shell.TableManager; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Analyzers.ViewModel { internal partial class AnalyzerSettingsViewModel : SettingsViewModelBase< AnalyzerSetting, AnalyzerSettingsViewModel.SettingsSnapshotFactory, AnalyzerSettingsViewModel.SettingsEntriesSnapshot> { public AnalyzerSettingsViewModel(ISettingsProvider<AnalyzerSetting> data, IWpfTableControlProvider controlProvider, ITableManagerProvider tableMangerProvider) : base(data, controlProvider, tableMangerProvider) { } public override string Identifier => "AnalyzerSettings"; protected override SettingsSnapshotFactory CreateSnapshotFactory(ISettingsProvider<AnalyzerSetting> data) => new(data); protected override IEnumerable<ColumnState2> GetInitialColumnStates() => new[] { new ColumnState2(ColumnDefinitions.Analyzer.Id, isVisible: true, width: 0), new ColumnState2(ColumnDefinitions.Analyzer.Title, isVisible: true, width: 0), new ColumnState2(ColumnDefinitions.Analyzer.Description, isVisible: false, width: 0), new ColumnState2(ColumnDefinitions.Analyzer.Category, isVisible: true, width: 0, groupingPriority: 1), new ColumnState2(ColumnDefinitions.Analyzer.Severity, isVisible: true, width: 0), new ColumnState2(ColumnDefinitions.Analyzer.Location, isVisible: true, width: 0) }; protected override string[] GetFixedColumns() => new[] { ColumnDefinitions.Analyzer.Category, ColumnDefinitions.Analyzer.Id, ColumnDefinitions.Analyzer.Title, ColumnDefinitions.Analyzer.Description, ColumnDefinitions.Analyzer.Severity, ColumnDefinitions.Analyzer.Location, }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider; using Microsoft.Internal.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Shell.TableManager; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Analyzers.ViewModel { internal partial class AnalyzerSettingsViewModel : SettingsViewModelBase< AnalyzerSetting, AnalyzerSettingsViewModel.SettingsSnapshotFactory, AnalyzerSettingsViewModel.SettingsEntriesSnapshot> { public AnalyzerSettingsViewModel(ISettingsProvider<AnalyzerSetting> data, IWpfTableControlProvider controlProvider, ITableManagerProvider tableMangerProvider) : base(data, controlProvider, tableMangerProvider) { } public override string Identifier => "AnalyzerSettings"; protected override SettingsSnapshotFactory CreateSnapshotFactory(ISettingsProvider<AnalyzerSetting> data) => new(data); protected override IEnumerable<ColumnState2> GetInitialColumnStates() => new[] { new ColumnState2(ColumnDefinitions.Analyzer.Id, isVisible: true, width: 0), new ColumnState2(ColumnDefinitions.Analyzer.Title, isVisible: true, width: 0), new ColumnState2(ColumnDefinitions.Analyzer.Description, isVisible: false, width: 0), new ColumnState2(ColumnDefinitions.Analyzer.Category, isVisible: true, width: 0, groupingPriority: 1), new ColumnState2(ColumnDefinitions.Analyzer.Severity, isVisible: true, width: 0), new ColumnState2(ColumnDefinitions.Analyzer.Location, isVisible: true, width: 0) }; protected override string[] GetFixedColumns() => new[] { ColumnDefinitions.Analyzer.Category, ColumnDefinitions.Analyzer.Id, ColumnDefinitions.Analyzer.Title, ColumnDefinitions.Analyzer.Description, ColumnDefinitions.Analyzer.Severity, ColumnDefinitions.Analyzer.Location, }; } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/CodeFixes/RemoveUnnecessaryParentheses/AbstractRemoveUnnecessaryParenthesesCodeFixProvider.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; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.RemoveUnnecessaryParentheses { internal abstract class AbstractRemoveUnnecessaryParenthesesCodeFixProvider<TParenthesizedExpressionSyntax> : SyntaxEditorBasedCodeFixProvider where TParenthesizedExpressionSyntax : SyntaxNode { public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.RemoveUnnecessaryParenthesesDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; protected abstract bool CanRemoveParentheses( TParenthesizedExpressionSyntax current, SemanticModel semanticModel, CancellationToken cancellationToken); public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix( new MyCodeAction( c => FixAsync(context.Document, context.Diagnostics[0], c)), context.Diagnostics); return Task.CompletedTask; } protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); var originalNodes = diagnostics.SelectAsArray( d => (TParenthesizedExpressionSyntax)d.AdditionalLocations[0].FindNode( findInsideTrivia: true, getInnermostNodeForTie: true, cancellationToken)); return editor.ApplyExpressionLevelSemanticEditsAsync( document, originalNodes, (semanticModel, current) => current != null && CanRemoveParentheses(current, semanticModel, cancellationToken), (_, currentRoot, current) => currentRoot.ReplaceNode(current, syntaxFacts.Unparenthesize(current)), cancellationToken); } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(AnalyzersResources.Remove_unnecessary_parentheses, createChangedDocument, AnalyzersResources.Remove_unnecessary_parentheses) { } } } }
// Licensed to the .NET Foundation under one or more 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; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.RemoveUnnecessaryParentheses { internal abstract class AbstractRemoveUnnecessaryParenthesesCodeFixProvider<TParenthesizedExpressionSyntax> : SyntaxEditorBasedCodeFixProvider where TParenthesizedExpressionSyntax : SyntaxNode { public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.RemoveUnnecessaryParenthesesDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; protected abstract bool CanRemoveParentheses( TParenthesizedExpressionSyntax current, SemanticModel semanticModel, CancellationToken cancellationToken); public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix( new MyCodeAction( c => FixAsync(context.Document, context.Diagnostics[0], c)), context.Diagnostics); return Task.CompletedTask; } protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); var originalNodes = diagnostics.SelectAsArray( d => (TParenthesizedExpressionSyntax)d.AdditionalLocations[0].FindNode( findInsideTrivia: true, getInnermostNodeForTie: true, cancellationToken)); return editor.ApplyExpressionLevelSemanticEditsAsync( document, originalNodes, (semanticModel, current) => current != null && CanRemoveParentheses(current, semanticModel, cancellationToken), (_, currentRoot, current) => currentRoot.ReplaceNode(current, syntaxFacts.Unparenthesize(current)), cancellationToken); } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(AnalyzersResources.Remove_unnecessary_parentheses, createChangedDocument, AnalyzersResources.Remove_unnecessary_parentheses) { } } } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/Editing/DeclarationModifiers.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.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; #if CODE_STYLE namespace Microsoft.CodeAnalysis.Internal.Editing #else namespace Microsoft.CodeAnalysis.Editing #endif { public struct DeclarationModifiers : IEquatable<DeclarationModifiers> { private readonly Modifiers _modifiers; private DeclarationModifiers(Modifiers modifiers) => _modifiers = modifiers; internal DeclarationModifiers( bool isStatic = false, bool isAbstract = false, bool isNew = false, bool isUnsafe = false, bool isReadOnly = false, bool isVirtual = false, bool isOverride = false, bool isSealed = false, bool isConst = false, bool isWithEvents = false, bool isPartial = false, bool isAsync = false, bool isWriteOnly = false, bool isRef = false, bool isVolatile = false, bool isExtern = false) : this( (isStatic ? Modifiers.Static : Modifiers.None) | (isAbstract ? Modifiers.Abstract : Modifiers.None) | (isNew ? Modifiers.New : Modifiers.None) | (isUnsafe ? Modifiers.Unsafe : Modifiers.None) | (isReadOnly ? Modifiers.ReadOnly : Modifiers.None) | (isVirtual ? Modifiers.Virtual : Modifiers.None) | (isOverride ? Modifiers.Override : Modifiers.None) | (isSealed ? Modifiers.Sealed : Modifiers.None) | (isConst ? Modifiers.Const : Modifiers.None) | (isWithEvents ? Modifiers.WithEvents : Modifiers.None) | (isPartial ? Modifiers.Partial : Modifiers.None) | (isAsync ? Modifiers.Async : Modifiers.None) | (isWriteOnly ? Modifiers.WriteOnly : Modifiers.None) | (isRef ? Modifiers.Ref : Modifiers.None) | (isVolatile ? Modifiers.Volatile : Modifiers.None) | (isExtern ? Modifiers.Extern : Modifiers.None)) { } public static DeclarationModifiers From(ISymbol symbol) { if (symbol is INamedTypeSymbol || symbol is IFieldSymbol || symbol is IPropertySymbol || symbol is IMethodSymbol || symbol is IEventSymbol) { var field = symbol as IFieldSymbol; var property = symbol as IPropertySymbol; var method = symbol as IMethodSymbol; return new DeclarationModifiers( isStatic: symbol.IsStatic, isAbstract: symbol.IsAbstract, isReadOnly: field?.IsReadOnly == true || property?.IsReadOnly == true, isVirtual: symbol.IsVirtual, isOverride: symbol.IsOverride, isSealed: symbol.IsSealed, isConst: field?.IsConst == true, isUnsafe: symbol.RequiresUnsafeModifier(), isVolatile: field?.IsVolatile == true, isExtern: symbol.IsExtern, isAsync: method?.IsAsync == true); } // Only named types, members of named types, and local functions have modifiers. // Everything else has none. return DeclarationModifiers.None; } public bool IsStatic => (_modifiers & Modifiers.Static) != 0; public bool IsAbstract => (_modifiers & Modifiers.Abstract) != 0; public bool IsNew => (_modifiers & Modifiers.New) != 0; public bool IsUnsafe => (_modifiers & Modifiers.Unsafe) != 0; public bool IsReadOnly => (_modifiers & Modifiers.ReadOnly) != 0; public bool IsVirtual => (_modifiers & Modifiers.Virtual) != 0; public bool IsOverride => (_modifiers & Modifiers.Override) != 0; public bool IsSealed => (_modifiers & Modifiers.Sealed) != 0; public bool IsConst => (_modifiers & Modifiers.Const) != 0; public bool IsWithEvents => (_modifiers & Modifiers.WithEvents) != 0; public bool IsPartial => (_modifiers & Modifiers.Partial) != 0; public bool IsAsync => (_modifiers & Modifiers.Async) != 0; public bool IsWriteOnly => (_modifiers & Modifiers.WriteOnly) != 0; public bool IsRef => (_modifiers & Modifiers.Ref) != 0; public bool IsVolatile => (_modifiers & Modifiers.Volatile) != 0; public bool IsExtern => (_modifiers & Modifiers.Extern) != 0; public DeclarationModifiers WithIsStatic(bool isStatic) => new(SetFlag(_modifiers, Modifiers.Static, isStatic)); public DeclarationModifiers WithIsAbstract(bool isAbstract) => new(SetFlag(_modifiers, Modifiers.Abstract, isAbstract)); public DeclarationModifiers WithIsNew(bool isNew) => new(SetFlag(_modifiers, Modifiers.New, isNew)); public DeclarationModifiers WithIsUnsafe(bool isUnsafe) => new(SetFlag(_modifiers, Modifiers.Unsafe, isUnsafe)); public DeclarationModifiers WithIsReadOnly(bool isReadOnly) => new(SetFlag(_modifiers, Modifiers.ReadOnly, isReadOnly)); public DeclarationModifiers WithIsVirtual(bool isVirtual) => new(SetFlag(_modifiers, Modifiers.Virtual, isVirtual)); public DeclarationModifiers WithIsOverride(bool isOverride) => new(SetFlag(_modifiers, Modifiers.Override, isOverride)); public DeclarationModifiers WithIsSealed(bool isSealed) => new(SetFlag(_modifiers, Modifiers.Sealed, isSealed)); public DeclarationModifiers WithIsConst(bool isConst) => new(SetFlag(_modifiers, Modifiers.Const, isConst)); public DeclarationModifiers WithWithEvents(bool withEvents) => new(SetFlag(_modifiers, Modifiers.WithEvents, withEvents)); public DeclarationModifiers WithPartial(bool isPartial) => new(SetFlag(_modifiers, Modifiers.Partial, isPartial)); [SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "Public API.")] public DeclarationModifiers WithAsync(bool isAsync) => new(SetFlag(_modifiers, Modifiers.Async, isAsync)); public DeclarationModifiers WithIsWriteOnly(bool isWriteOnly) => new(SetFlag(_modifiers, Modifiers.WriteOnly, isWriteOnly)); public DeclarationModifiers WithIsRef(bool isRef) => new(SetFlag(_modifiers, Modifiers.Ref, isRef)); public DeclarationModifiers WithIsVolatile(bool isVolatile) => new(SetFlag(_modifiers, Modifiers.Volatile, isVolatile)); public DeclarationModifiers WithIsExtern(bool isExtern) => new(SetFlag(_modifiers, Modifiers.Extern, isExtern)); private static Modifiers SetFlag(Modifiers existing, Modifiers modifier, bool isSet) => isSet ? (existing | modifier) : (existing & ~modifier); [Flags] private enum Modifiers { #pragma warning disable format None = 0, Static = 1 << 0, Abstract = 1 << 1, New = 1 << 2, Unsafe = 1 << 3, ReadOnly = 1 << 4, Virtual = 1 << 5, Override = 1 << 6, Sealed = 1 << 7, Const = 1 << 8, WithEvents = 1 << 9, Partial = 1 << 10, Async = 1 << 11, WriteOnly = 1 << 12, Ref = 1 << 13, Volatile = 1 << 14, Extern = 1 << 15, #pragma warning restore format } public static DeclarationModifiers None => default; public static DeclarationModifiers Static => new(Modifiers.Static); public static DeclarationModifiers Abstract => new(Modifiers.Abstract); public static DeclarationModifiers New => new(Modifiers.New); public static DeclarationModifiers Unsafe => new(Modifiers.Unsafe); public static DeclarationModifiers ReadOnly => new(Modifiers.ReadOnly); public static DeclarationModifiers Virtual => new(Modifiers.Virtual); public static DeclarationModifiers Override => new(Modifiers.Override); public static DeclarationModifiers Sealed => new(Modifiers.Sealed); public static DeclarationModifiers Const => new(Modifiers.Const); public static DeclarationModifiers WithEvents => new(Modifiers.WithEvents); public static DeclarationModifiers Partial => new(Modifiers.Partial); public static DeclarationModifiers Async => new(Modifiers.Async); public static DeclarationModifiers WriteOnly => new(Modifiers.WriteOnly); public static DeclarationModifiers Ref => new(Modifiers.Ref); public static DeclarationModifiers Volatile => new(Modifiers.Volatile); public static DeclarationModifiers Extern => new(Modifiers.Extern); public static DeclarationModifiers operator |(DeclarationModifiers left, DeclarationModifiers right) => new(left._modifiers | right._modifiers); public static DeclarationModifiers operator &(DeclarationModifiers left, DeclarationModifiers right) => new(left._modifiers & right._modifiers); public static DeclarationModifiers operator +(DeclarationModifiers left, DeclarationModifiers right) => new(left._modifiers | right._modifiers); public static DeclarationModifiers operator -(DeclarationModifiers left, DeclarationModifiers right) => new(left._modifiers & ~right._modifiers); public bool Equals(DeclarationModifiers modifiers) => _modifiers == modifiers._modifiers; public override bool Equals(object obj) => obj is DeclarationModifiers mods && Equals(mods); public override int GetHashCode() => (int)_modifiers; public static bool operator ==(DeclarationModifiers left, DeclarationModifiers right) => left._modifiers == right._modifiers; public static bool operator !=(DeclarationModifiers left, DeclarationModifiers right) => left._modifiers != right._modifiers; public override string ToString() => _modifiers.ToString(); public static bool TryParse(string value, out DeclarationModifiers modifiers) { if (Enum.TryParse(value, out Modifiers mods)) { modifiers = new DeclarationModifiers(mods); return true; } else { modifiers = 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. #nullable disable using System; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; #if CODE_STYLE namespace Microsoft.CodeAnalysis.Internal.Editing #else namespace Microsoft.CodeAnalysis.Editing #endif { public struct DeclarationModifiers : IEquatable<DeclarationModifiers> { private readonly Modifiers _modifiers; private DeclarationModifiers(Modifiers modifiers) => _modifiers = modifiers; internal DeclarationModifiers( bool isStatic = false, bool isAbstract = false, bool isNew = false, bool isUnsafe = false, bool isReadOnly = false, bool isVirtual = false, bool isOverride = false, bool isSealed = false, bool isConst = false, bool isWithEvents = false, bool isPartial = false, bool isAsync = false, bool isWriteOnly = false, bool isRef = false, bool isVolatile = false, bool isExtern = false) : this( (isStatic ? Modifiers.Static : Modifiers.None) | (isAbstract ? Modifiers.Abstract : Modifiers.None) | (isNew ? Modifiers.New : Modifiers.None) | (isUnsafe ? Modifiers.Unsafe : Modifiers.None) | (isReadOnly ? Modifiers.ReadOnly : Modifiers.None) | (isVirtual ? Modifiers.Virtual : Modifiers.None) | (isOverride ? Modifiers.Override : Modifiers.None) | (isSealed ? Modifiers.Sealed : Modifiers.None) | (isConst ? Modifiers.Const : Modifiers.None) | (isWithEvents ? Modifiers.WithEvents : Modifiers.None) | (isPartial ? Modifiers.Partial : Modifiers.None) | (isAsync ? Modifiers.Async : Modifiers.None) | (isWriteOnly ? Modifiers.WriteOnly : Modifiers.None) | (isRef ? Modifiers.Ref : Modifiers.None) | (isVolatile ? Modifiers.Volatile : Modifiers.None) | (isExtern ? Modifiers.Extern : Modifiers.None)) { } public static DeclarationModifiers From(ISymbol symbol) { if (symbol is INamedTypeSymbol || symbol is IFieldSymbol || symbol is IPropertySymbol || symbol is IMethodSymbol || symbol is IEventSymbol) { var field = symbol as IFieldSymbol; var property = symbol as IPropertySymbol; var method = symbol as IMethodSymbol; return new DeclarationModifiers( isStatic: symbol.IsStatic, isAbstract: symbol.IsAbstract, isReadOnly: field?.IsReadOnly == true || property?.IsReadOnly == true, isVirtual: symbol.IsVirtual, isOverride: symbol.IsOverride, isSealed: symbol.IsSealed, isConst: field?.IsConst == true, isUnsafe: symbol.RequiresUnsafeModifier(), isVolatile: field?.IsVolatile == true, isExtern: symbol.IsExtern, isAsync: method?.IsAsync == true); } // Only named types, members of named types, and local functions have modifiers. // Everything else has none. return DeclarationModifiers.None; } public bool IsStatic => (_modifiers & Modifiers.Static) != 0; public bool IsAbstract => (_modifiers & Modifiers.Abstract) != 0; public bool IsNew => (_modifiers & Modifiers.New) != 0; public bool IsUnsafe => (_modifiers & Modifiers.Unsafe) != 0; public bool IsReadOnly => (_modifiers & Modifiers.ReadOnly) != 0; public bool IsVirtual => (_modifiers & Modifiers.Virtual) != 0; public bool IsOverride => (_modifiers & Modifiers.Override) != 0; public bool IsSealed => (_modifiers & Modifiers.Sealed) != 0; public bool IsConst => (_modifiers & Modifiers.Const) != 0; public bool IsWithEvents => (_modifiers & Modifiers.WithEvents) != 0; public bool IsPartial => (_modifiers & Modifiers.Partial) != 0; public bool IsAsync => (_modifiers & Modifiers.Async) != 0; public bool IsWriteOnly => (_modifiers & Modifiers.WriteOnly) != 0; public bool IsRef => (_modifiers & Modifiers.Ref) != 0; public bool IsVolatile => (_modifiers & Modifiers.Volatile) != 0; public bool IsExtern => (_modifiers & Modifiers.Extern) != 0; public DeclarationModifiers WithIsStatic(bool isStatic) => new(SetFlag(_modifiers, Modifiers.Static, isStatic)); public DeclarationModifiers WithIsAbstract(bool isAbstract) => new(SetFlag(_modifiers, Modifiers.Abstract, isAbstract)); public DeclarationModifiers WithIsNew(bool isNew) => new(SetFlag(_modifiers, Modifiers.New, isNew)); public DeclarationModifiers WithIsUnsafe(bool isUnsafe) => new(SetFlag(_modifiers, Modifiers.Unsafe, isUnsafe)); public DeclarationModifiers WithIsReadOnly(bool isReadOnly) => new(SetFlag(_modifiers, Modifiers.ReadOnly, isReadOnly)); public DeclarationModifiers WithIsVirtual(bool isVirtual) => new(SetFlag(_modifiers, Modifiers.Virtual, isVirtual)); public DeclarationModifiers WithIsOverride(bool isOverride) => new(SetFlag(_modifiers, Modifiers.Override, isOverride)); public DeclarationModifiers WithIsSealed(bool isSealed) => new(SetFlag(_modifiers, Modifiers.Sealed, isSealed)); public DeclarationModifiers WithIsConst(bool isConst) => new(SetFlag(_modifiers, Modifiers.Const, isConst)); public DeclarationModifiers WithWithEvents(bool withEvents) => new(SetFlag(_modifiers, Modifiers.WithEvents, withEvents)); public DeclarationModifiers WithPartial(bool isPartial) => new(SetFlag(_modifiers, Modifiers.Partial, isPartial)); [SuppressMessage("Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "Public API.")] public DeclarationModifiers WithAsync(bool isAsync) => new(SetFlag(_modifiers, Modifiers.Async, isAsync)); public DeclarationModifiers WithIsWriteOnly(bool isWriteOnly) => new(SetFlag(_modifiers, Modifiers.WriteOnly, isWriteOnly)); public DeclarationModifiers WithIsRef(bool isRef) => new(SetFlag(_modifiers, Modifiers.Ref, isRef)); public DeclarationModifiers WithIsVolatile(bool isVolatile) => new(SetFlag(_modifiers, Modifiers.Volatile, isVolatile)); public DeclarationModifiers WithIsExtern(bool isExtern) => new(SetFlag(_modifiers, Modifiers.Extern, isExtern)); private static Modifiers SetFlag(Modifiers existing, Modifiers modifier, bool isSet) => isSet ? (existing | modifier) : (existing & ~modifier); [Flags] private enum Modifiers { #pragma warning disable format None = 0, Static = 1 << 0, Abstract = 1 << 1, New = 1 << 2, Unsafe = 1 << 3, ReadOnly = 1 << 4, Virtual = 1 << 5, Override = 1 << 6, Sealed = 1 << 7, Const = 1 << 8, WithEvents = 1 << 9, Partial = 1 << 10, Async = 1 << 11, WriteOnly = 1 << 12, Ref = 1 << 13, Volatile = 1 << 14, Extern = 1 << 15, #pragma warning restore format } public static DeclarationModifiers None => default; public static DeclarationModifiers Static => new(Modifiers.Static); public static DeclarationModifiers Abstract => new(Modifiers.Abstract); public static DeclarationModifiers New => new(Modifiers.New); public static DeclarationModifiers Unsafe => new(Modifiers.Unsafe); public static DeclarationModifiers ReadOnly => new(Modifiers.ReadOnly); public static DeclarationModifiers Virtual => new(Modifiers.Virtual); public static DeclarationModifiers Override => new(Modifiers.Override); public static DeclarationModifiers Sealed => new(Modifiers.Sealed); public static DeclarationModifiers Const => new(Modifiers.Const); public static DeclarationModifiers WithEvents => new(Modifiers.WithEvents); public static DeclarationModifiers Partial => new(Modifiers.Partial); public static DeclarationModifiers Async => new(Modifiers.Async); public static DeclarationModifiers WriteOnly => new(Modifiers.WriteOnly); public static DeclarationModifiers Ref => new(Modifiers.Ref); public static DeclarationModifiers Volatile => new(Modifiers.Volatile); public static DeclarationModifiers Extern => new(Modifiers.Extern); public static DeclarationModifiers operator |(DeclarationModifiers left, DeclarationModifiers right) => new(left._modifiers | right._modifiers); public static DeclarationModifiers operator &(DeclarationModifiers left, DeclarationModifiers right) => new(left._modifiers & right._modifiers); public static DeclarationModifiers operator +(DeclarationModifiers left, DeclarationModifiers right) => new(left._modifiers | right._modifiers); public static DeclarationModifiers operator -(DeclarationModifiers left, DeclarationModifiers right) => new(left._modifiers & ~right._modifiers); public bool Equals(DeclarationModifiers modifiers) => _modifiers == modifiers._modifiers; public override bool Equals(object obj) => obj is DeclarationModifiers mods && Equals(mods); public override int GetHashCode() => (int)_modifiers; public static bool operator ==(DeclarationModifiers left, DeclarationModifiers right) => left._modifiers == right._modifiers; public static bool operator !=(DeclarationModifiers left, DeclarationModifiers right) => left._modifiers != right._modifiers; public override string ToString() => _modifiers.ToString(); public static bool TryParse(string value, out DeclarationModifiers modifiers) { if (Enum.TryParse(value, out Modifiers mods)) { modifiers = new DeclarationModifiers(mods); return true; } else { modifiers = default; return false; } } } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/Parser/BlockContexts/PropertyBlockContext.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 '----------------------------------------------------------------------------- ' Contains the definition of the BlockContext '----------------------------------------------------------------------------- Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Friend NotInheritable Class PropertyBlockContext Inherits DeclarationContext Private ReadOnly _isPropertyBlock As Boolean Friend Sub New(statement As StatementSyntax, prevContext As BlockContext, isPropertyBlock As Boolean) MyBase.New(SyntaxKind.PropertyBlock, statement, prevContext) _isPropertyBlock = isPropertyBlock End Sub Private ReadOnly Property IsPropertyBlock As Boolean Get Return _isPropertyBlock OrElse Statements.Count > 0 End Get End Property Friend Overrides Function CreateBlockSyntax(endStmt As StatementSyntax) As VisualBasicSyntaxNode Dim beginBlockStmt As PropertyStatementSyntax = Nothing Dim endBlockStmt As EndBlockStatementSyntax = DirectCast(endStmt, EndBlockStatementSyntax) GetBeginEndStatements(beginBlockStmt, endBlockStmt) Dim accessors = _statements.ToList(Of AccessorBlockSyntax)() FreeStatements() ' We can only get here if this is a block property but still check accessor count. If accessors.Any Then ' Only auto properties can be initialized. If there is a Get or Set accessor then it is an error. beginBlockStmt = ReportErrorIfHasInitializer(beginBlockStmt) End If Return SyntaxFactory.PropertyBlock(beginBlockStmt, accessors, endBlockStmt) End Function Friend Overrides Function ProcessSyntax(node As VisualBasicSyntaxNode) As BlockContext Select Case node.Kind Case SyntaxKind.GetAccessorStatement Return New MethodBlockContext(SyntaxKind.GetAccessorBlock, DirectCast(node, StatementSyntax), Me) Case SyntaxKind.SetAccessorStatement ' Checks for duplicate GET/SET are deferred to declared per Dev10 code Return New MethodBlockContext(SyntaxKind.SetAccessorBlock, DirectCast(node, StatementSyntax), Me) Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock ' Handle any block created by this context Add(node) Case Else ' TODO - In Dev10, the code tries to report ERRID_PropertyMemberSyntax. This would occur prior to auto properties ' when the statement was a malformed declaration. However, due to autoproperties this no longer seems possible. ' test should confirm that this error can no longer be produced in Dev10. Is it worth trying to preserve this behavior? Dim context As BlockContext = EndBlock(Nothing) Debug.Assert(context Is PrevBlock) If IsPropertyBlock Then ' Property blocks can only contain Get and Set. node = Parser.ReportSyntaxError(node, ERRID.ERR_InvInsideEndsProperty) End If ' Let the outer context process this statement Return context.ProcessSyntax(node) End Select Return Me End Function Friend Overrides Function TryLinkSyntax(node As VisualBasicSyntaxNode, ByRef newContext As BlockContext) As LinkResult newContext = Nothing If KindEndsBlock(node.Kind) Then Return UseSyntax(node, newContext) End If Select Case node.Kind Case _ SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement Return UseSyntax(node, newContext) Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock Return UseSyntax(node, newContext, DirectCast(node, AccessorBlockSyntax).End.IsMissing) Case Else newContext = Me Return LinkResult.Crumble End Select End Function Friend Overrides Function EndBlock(endStmt As StatementSyntax) As BlockContext If IsPropertyBlock OrElse endStmt IsNot Nothing Then Return MyBase.EndBlock(endStmt) End If ' This is an auto property. Do not create a block. Just add the property statement to the outer block ' TODO - Consider changing the kind to AutoProperty. For now auto properties are just PropertyStatement ' whose parent is not a PropertyBlock. Don't create a missing end for an auto property Debug.Assert(PrevBlock IsNot Nothing) Debug.Assert(Statements.Count = 0) Dim beginBlockStmt As PropertyStatementSyntax = DirectCast(BeginStatement, PropertyStatementSyntax) ' Check if auto property has params If beginBlockStmt.ParameterList IsNot Nothing AndAlso beginBlockStmt.ParameterList.Parameters.Count > 0 Then beginBlockStmt = New PropertyStatementSyntax(beginBlockStmt.Kind, beginBlockStmt.AttributeLists.Node, beginBlockStmt.Modifiers.Node, beginBlockStmt.PropertyKeyword, beginBlockStmt.Identifier, Parser.ReportSyntaxError(beginBlockStmt.ParameterList, ERRID.ERR_AutoPropertyCantHaveParams), beginBlockStmt.AsClause, beginBlockStmt.Initializer, beginBlockStmt.ImplementsClause) End If 'Add auto property to Prev context. DO NOT call ProcessSyntax because that will create a PropertyContext. ' Just add the statement to the context. Dim context = PrevBlock context.Add(beginBlockStmt) Return context End Function Friend Shared Function ReportErrorIfHasInitializer(propertyStatement As PropertyStatementSyntax) As PropertyStatementSyntax If propertyStatement.Initializer IsNot Nothing OrElse ( propertyStatement.AsClause IsNot Nothing AndAlso TryCast(propertyStatement.AsClause, AsNewClauseSyntax) IsNot Nothing ) Then propertyStatement = Parser.ReportSyntaxError(propertyStatement, ERRID.ERR_InitializedExpandedProperty) 'TODO - In Dev10 resources there is an unused resource ERRID.ERR_NewExpandedProperty for the new case. ' Is it worthwhile adding to Dev12? End If Return propertyStatement 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.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax '----------------------------------------------------------------------------- ' Contains the definition of the BlockContext '----------------------------------------------------------------------------- Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Friend NotInheritable Class PropertyBlockContext Inherits DeclarationContext Private ReadOnly _isPropertyBlock As Boolean Friend Sub New(statement As StatementSyntax, prevContext As BlockContext, isPropertyBlock As Boolean) MyBase.New(SyntaxKind.PropertyBlock, statement, prevContext) _isPropertyBlock = isPropertyBlock End Sub Private ReadOnly Property IsPropertyBlock As Boolean Get Return _isPropertyBlock OrElse Statements.Count > 0 End Get End Property Friend Overrides Function CreateBlockSyntax(endStmt As StatementSyntax) As VisualBasicSyntaxNode Dim beginBlockStmt As PropertyStatementSyntax = Nothing Dim endBlockStmt As EndBlockStatementSyntax = DirectCast(endStmt, EndBlockStatementSyntax) GetBeginEndStatements(beginBlockStmt, endBlockStmt) Dim accessors = _statements.ToList(Of AccessorBlockSyntax)() FreeStatements() ' We can only get here if this is a block property but still check accessor count. If accessors.Any Then ' Only auto properties can be initialized. If there is a Get or Set accessor then it is an error. beginBlockStmt = ReportErrorIfHasInitializer(beginBlockStmt) End If Return SyntaxFactory.PropertyBlock(beginBlockStmt, accessors, endBlockStmt) End Function Friend Overrides Function ProcessSyntax(node As VisualBasicSyntaxNode) As BlockContext Select Case node.Kind Case SyntaxKind.GetAccessorStatement Return New MethodBlockContext(SyntaxKind.GetAccessorBlock, DirectCast(node, StatementSyntax), Me) Case SyntaxKind.SetAccessorStatement ' Checks for duplicate GET/SET are deferred to declared per Dev10 code Return New MethodBlockContext(SyntaxKind.SetAccessorBlock, DirectCast(node, StatementSyntax), Me) Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock ' Handle any block created by this context Add(node) Case Else ' TODO - In Dev10, the code tries to report ERRID_PropertyMemberSyntax. This would occur prior to auto properties ' when the statement was a malformed declaration. However, due to autoproperties this no longer seems possible. ' test should confirm that this error can no longer be produced in Dev10. Is it worth trying to preserve this behavior? Dim context As BlockContext = EndBlock(Nothing) Debug.Assert(context Is PrevBlock) If IsPropertyBlock Then ' Property blocks can only contain Get and Set. node = Parser.ReportSyntaxError(node, ERRID.ERR_InvInsideEndsProperty) End If ' Let the outer context process this statement Return context.ProcessSyntax(node) End Select Return Me End Function Friend Overrides Function TryLinkSyntax(node As VisualBasicSyntaxNode, ByRef newContext As BlockContext) As LinkResult newContext = Nothing If KindEndsBlock(node.Kind) Then Return UseSyntax(node, newContext) End If Select Case node.Kind Case _ SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement Return UseSyntax(node, newContext) Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock Return UseSyntax(node, newContext, DirectCast(node, AccessorBlockSyntax).End.IsMissing) Case Else newContext = Me Return LinkResult.Crumble End Select End Function Friend Overrides Function EndBlock(endStmt As StatementSyntax) As BlockContext If IsPropertyBlock OrElse endStmt IsNot Nothing Then Return MyBase.EndBlock(endStmt) End If ' This is an auto property. Do not create a block. Just add the property statement to the outer block ' TODO - Consider changing the kind to AutoProperty. For now auto properties are just PropertyStatement ' whose parent is not a PropertyBlock. Don't create a missing end for an auto property Debug.Assert(PrevBlock IsNot Nothing) Debug.Assert(Statements.Count = 0) Dim beginBlockStmt As PropertyStatementSyntax = DirectCast(BeginStatement, PropertyStatementSyntax) ' Check if auto property has params If beginBlockStmt.ParameterList IsNot Nothing AndAlso beginBlockStmt.ParameterList.Parameters.Count > 0 Then beginBlockStmt = New PropertyStatementSyntax(beginBlockStmt.Kind, beginBlockStmt.AttributeLists.Node, beginBlockStmt.Modifiers.Node, beginBlockStmt.PropertyKeyword, beginBlockStmt.Identifier, Parser.ReportSyntaxError(beginBlockStmt.ParameterList, ERRID.ERR_AutoPropertyCantHaveParams), beginBlockStmt.AsClause, beginBlockStmt.Initializer, beginBlockStmt.ImplementsClause) End If 'Add auto property to Prev context. DO NOT call ProcessSyntax because that will create a PropertyContext. ' Just add the statement to the context. Dim context = PrevBlock context.Add(beginBlockStmt) Return context End Function Friend Shared Function ReportErrorIfHasInitializer(propertyStatement As PropertyStatementSyntax) As PropertyStatementSyntax If propertyStatement.Initializer IsNot Nothing OrElse ( propertyStatement.AsClause IsNot Nothing AndAlso TryCast(propertyStatement.AsClause, AsNewClauseSyntax) IsNot Nothing ) Then propertyStatement = Parser.ReportSyntaxError(propertyStatement, ERRID.ERR_InitializedExpandedProperty) 'TODO - In Dev10 resources there is an unused resource ERRID.ERR_NewExpandedProperty for the new case. ' Is it worthwhile adding to Dev12? End If Return propertyStatement End Function End Class End Namespace
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/VisualBasic/Portable/Simplification/Reducers/VisualBasicCallReducer.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification Partial Friend Class VisualBasicCallReducer Inherits AbstractVisualBasicReducer Private Shared ReadOnly s_pool As ObjectPool(Of IReductionRewriter) = New ObjectPool(Of IReductionRewriter)(Function() New Rewriter(s_pool)) Public Sub New() MyBase.New(s_pool) End Sub Private Shared ReadOnly s_simplifyCallStatement As Func(Of CallStatementSyntax, SemanticModel, OptionSet, CancellationToken, SyntaxNode) = AddressOf SimplifyCallStatement Private Shared Function SimplifyCallStatement( callStatement As CallStatementSyntax, semanticModel As SemanticModel, optionSet As OptionSet, cancellationToken As CancellationToken ) As ExecutableStatementSyntax If callStatement.CanRemoveCallKeyword() Then Dim leading = callStatement.GetLeadingTrivia() Dim resultNode = SyntaxFactory.ExpressionStatement(callStatement.Invocation) _ .WithLeadingTrivia(leading) resultNode = SimplificationHelpers.CopyAnnotations(callStatement, resultNode) Return resultNode End If ' We don't know how to simplify this. Return callStatement End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification Partial Friend Class VisualBasicCallReducer Inherits AbstractVisualBasicReducer Private Shared ReadOnly s_pool As ObjectPool(Of IReductionRewriter) = New ObjectPool(Of IReductionRewriter)(Function() New Rewriter(s_pool)) Public Sub New() MyBase.New(s_pool) End Sub Private Shared ReadOnly s_simplifyCallStatement As Func(Of CallStatementSyntax, SemanticModel, OptionSet, CancellationToken, SyntaxNode) = AddressOf SimplifyCallStatement Private Shared Function SimplifyCallStatement( callStatement As CallStatementSyntax, semanticModel As SemanticModel, optionSet As OptionSet, cancellationToken As CancellationToken ) As ExecutableStatementSyntax If callStatement.CanRemoveCallKeyword() Then Dim leading = callStatement.GetLeadingTrivia() Dim resultNode = SyntaxFactory.ExpressionStatement(callStatement.Invocation) _ .WithLeadingTrivia(leading) resultNode = SimplificationHelpers.CopyAnnotations(callStatement, resultNode) Return resultNode End If ' We don't know how to simplify this. Return callStatement End Function End Class End Namespace
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/CSharp/Highlighting/KeywordHighlighters/UnsafeStatementHighlighter.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.ComponentModel.Composition; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.Implementation.Highlighting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters { [ExportHighlighter(LanguageNames.CSharp)] internal class UnsafeStatementHighlighter : AbstractKeywordHighlighter<UnsafeStatementSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public UnsafeStatementHighlighter() { } protected override void AddHighlights(UnsafeStatementSyntax unsafeStatement, List<TextSpan> highlights, CancellationToken cancellationToken) => highlights.Add(unsafeStatement.UnsafeKeyword.Span); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.Implementation.Highlighting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters { [ExportHighlighter(LanguageNames.CSharp)] internal class UnsafeStatementHighlighter : AbstractKeywordHighlighter<UnsafeStatementSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public UnsafeStatementHighlighter() { } protected override void AddHighlights(UnsafeStatementSyntax unsafeStatement, List<TextSpan> highlights, CancellationToken cancellationToken) => highlights.Add(unsafeStatement.UnsafeKeyword.Span); } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/Telemetry/VSTelemetryCache.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.Concurrent; using Microsoft.CodeAnalysis.Internal.Log; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Telemetry { internal static class VSTelemetryCache { private const string EventPrefix = "vs/ide/vbcs/"; private const string PropertyPrefix = "vs.ide.vbcs."; // these don't have concurrency limit on purpose to reduce chance of lock contention. // if that becomes a problem - by showing up in our perf investigation, then we will consider adding concurrency limit. private static readonly ConcurrentDictionary<Key, string> s_eventMap = new(); private static readonly ConcurrentDictionary<Key, string> s_propertyMap = new(); public static string GetEventName(this FunctionId functionId, string eventKey = null) => s_eventMap.GetOrAdd(new Key(functionId, eventKey), CreateEventName); public static string GetPropertyName(this FunctionId functionId, string propertyKey) => s_propertyMap.GetOrAdd(new Key(functionId, propertyKey), CreatePropertyName); private static string CreateEventName(Key key) => (EventPrefix + Enum.GetName(typeof(FunctionId), key.FunctionId).Replace('_', '/') + (key.ItemKey == null ? string.Empty : ("/" + key.ItemKey))).ToLowerInvariant(); private static string CreatePropertyName(Key key) => (PropertyPrefix + Enum.GetName(typeof(FunctionId), key.FunctionId).Replace('_', '.') + "." + key.ItemKey).ToLowerInvariant(); private struct Key : IEquatable<Key> { public readonly FunctionId FunctionId; public readonly string ItemKey; public Key(FunctionId functionId, string itemKey) { this.FunctionId = functionId; this.ItemKey = itemKey; } public override int GetHashCode() => Hash.Combine((int)FunctionId, ItemKey?.GetHashCode() ?? 0); public override bool Equals(object obj) => obj is Key && Equals((Key)obj); public bool Equals(Key key) => this.FunctionId == key.FunctionId && this.ItemKey == key.ItemKey; } } }
// Licensed to the .NET Foundation under one or more 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.Concurrent; using Microsoft.CodeAnalysis.Internal.Log; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Telemetry { internal static class VSTelemetryCache { private const string EventPrefix = "vs/ide/vbcs/"; private const string PropertyPrefix = "vs.ide.vbcs."; // these don't have concurrency limit on purpose to reduce chance of lock contention. // if that becomes a problem - by showing up in our perf investigation, then we will consider adding concurrency limit. private static readonly ConcurrentDictionary<Key, string> s_eventMap = new(); private static readonly ConcurrentDictionary<Key, string> s_propertyMap = new(); public static string GetEventName(this FunctionId functionId, string eventKey = null) => s_eventMap.GetOrAdd(new Key(functionId, eventKey), CreateEventName); public static string GetPropertyName(this FunctionId functionId, string propertyKey) => s_propertyMap.GetOrAdd(new Key(functionId, propertyKey), CreatePropertyName); private static string CreateEventName(Key key) => (EventPrefix + Enum.GetName(typeof(FunctionId), key.FunctionId).Replace('_', '/') + (key.ItemKey == null ? string.Empty : ("/" + key.ItemKey))).ToLowerInvariant(); private static string CreatePropertyName(Key key) => (PropertyPrefix + Enum.GetName(typeof(FunctionId), key.FunctionId).Replace('_', '.') + "." + key.ItemKey).ToLowerInvariant(); private struct Key : IEquatable<Key> { public readonly FunctionId FunctionId; public readonly string ItemKey; public Key(FunctionId functionId, string itemKey) { this.FunctionId = functionId; this.ItemKey = itemKey; } public override int GetHashCode() => Hash.Combine((int)FunctionId, ItemKey?.GetHashCode() ?? 0); public override bool Equals(object obj) => obj is Key && Equals((Key)obj); public bool Equals(Key key) => this.FunctionId == key.FunctionId && this.ItemKey == key.ItemKey; } } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/Trivia/TriviaDataFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Formatting { /// <summary> /// trivia factory. /// /// it will cache some commonly used trivia to reduce memory footprint and heap allocation /// </summary> internal partial class TriviaDataFactory : AbstractTriviaDataFactory { public TriviaDataFactory(TreeData treeInfo, AnalyzerConfigOptions options) : base(treeInfo, options) { } private static bool IsCSharpWhitespace(char c) => SyntaxFacts.IsWhitespace(c) || SyntaxFacts.IsNewLine(c); public override TriviaData CreateLeadingTrivia(SyntaxToken token) { // no trivia if (!token.HasLeadingTrivia) { Debug.Assert(this.TreeInfo.GetTextBetween(default, token).All(IsCSharpWhitespace)); return GetSpaceTriviaData(space: 0); } var result = Analyzer.Leading(token); var info = GetWhitespaceOnlyTriviaInfo(default, token, result); if (info != null) { Debug.Assert(this.TreeInfo.GetTextBetween(default, token).All(IsCSharpWhitespace)); return info; } return new ComplexTrivia(this.Options, this.TreeInfo, default, token); } public override TriviaData CreateTrailingTrivia(SyntaxToken token) { // no trivia if (!token.HasTrailingTrivia) { Debug.Assert(this.TreeInfo.GetTextBetween(token, default).All(IsCSharpWhitespace)); return GetSpaceTriviaData(space: 0); } var result = Analyzer.Trailing(token); var info = GetWhitespaceOnlyTriviaInfo(token, default, result); if (info != null) { Debug.Assert(this.TreeInfo.GetTextBetween(token, default).All(IsCSharpWhitespace)); return info; } return new ComplexTrivia(this.Options, this.TreeInfo, token, default); } public override TriviaData Create(SyntaxToken token1, SyntaxToken token2) { // no trivia in between if (!token1.HasTrailingTrivia && !token2.HasLeadingTrivia) { Debug.Assert(string.IsNullOrWhiteSpace(this.TreeInfo.GetTextBetween(token1, token2))); return GetSpaceTriviaData(space: 0); } var result = Analyzer.Between(token1, token2); var info = GetWhitespaceOnlyTriviaInfo(token1, token2, result); if (info != null) { Debug.Assert(string.IsNullOrWhiteSpace(this.TreeInfo.GetTextBetween(token1, token2))); return info; } return new ComplexTrivia(this.Options, this.TreeInfo, token1, token2); } private static bool ContainsOnlyWhitespace(Analyzer.AnalysisResult result) { return !result.HasComments && !result.HasPreprocessor && !result.HasSkippedTokens && !result.HasSkippedOrDisabledText && !result.HasConflictMarker; } private TriviaData? GetWhitespaceOnlyTriviaInfo(SyntaxToken token1, SyntaxToken token2, Analyzer.AnalysisResult result) { if (!ContainsOnlyWhitespace(result)) { return null; } // only whitespace in between var space = GetSpaceOnSingleLine(result); Contract.ThrowIfFalse(space >= -1); if (space >= 0) { // check whether we can use cache return GetSpaceTriviaData(space, result.TreatAsElastic); } // tab is used in a place where it is not an indentation if (result.LineBreaks == 0 && result.Tab > 0) { // calculate actual space size from tab var spaces = CalculateSpaces(token1, token2); return new ModifiedWhitespace(this.Options, result.LineBreaks, indentation: spaces, elastic: result.TreatAsElastic, language: LanguageNames.CSharp); } // check whether we can cache trivia info for current indentation var lineCountAndIndentation = GetLineBreaksAndIndentation(result); return GetWhitespaceTriviaData(lineCountAndIndentation.lineBreaks, lineCountAndIndentation.indentation, lineCountAndIndentation.canUseTriviaAsItIs, result.TreatAsElastic); } private int CalculateSpaces(SyntaxToken token1, SyntaxToken token2) { var initialColumn = (token1.RawKind == 0) ? 0 : this.TreeInfo.GetOriginalColumn(TabSize, token1) + token1.Span.Length; var textSnippet = this.TreeInfo.GetTextBetween(token1, token2); return textSnippet.ConvertTabToSpace(TabSize, initialColumn, textSnippet.Length); } private (bool canUseTriviaAsItIs, int lineBreaks, int indentation) GetLineBreaksAndIndentation(Analyzer.AnalysisResult result) { Debug.Assert(result.Tab >= 0); Debug.Assert(result.LineBreaks >= 0); var indentation = result.Tab * TabSize + result.Space; if (result.HasTrailingSpace || result.HasUnknownWhitespace) { if (result.HasUnknownWhitespace && result.LineBreaks == 0 && indentation == 0) { // make sure we don't remove all whitespace indentation = 1; } return (canUseTriviaAsItIs: false, result.LineBreaks, indentation); } if (!UseTabs) { if (result.Tab > 0) { return (canUseTriviaAsItIs: false, result.LineBreaks, indentation); } return (canUseTriviaAsItIs: true, result.LineBreaks, indentation); } Debug.Assert(UseTabs); // tab can only appear before space to be a valid tab for indentation if (result.HasTabAfterSpace) { return (canUseTriviaAsItIs: false, result.LineBreaks, indentation); } if (result.Space >= TabSize) { return (canUseTriviaAsItIs: false, result.LineBreaks, indentation); } Debug.Assert((indentation / TabSize) == result.Tab); Debug.Assert((indentation % TabSize) == result.Space); return (canUseTriviaAsItIs: true, result.LineBreaks, indentation); } private static int GetSpaceOnSingleLine(Analyzer.AnalysisResult result) { if (result.HasTrailingSpace || result.HasUnknownWhitespace || result.LineBreaks > 0 || result.Tab > 0) { return -1; } return result.Space; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Formatting { /// <summary> /// trivia factory. /// /// it will cache some commonly used trivia to reduce memory footprint and heap allocation /// </summary> internal partial class TriviaDataFactory : AbstractTriviaDataFactory { public TriviaDataFactory(TreeData treeInfo, AnalyzerConfigOptions options) : base(treeInfo, options) { } private static bool IsCSharpWhitespace(char c) => SyntaxFacts.IsWhitespace(c) || SyntaxFacts.IsNewLine(c); public override TriviaData CreateLeadingTrivia(SyntaxToken token) { // no trivia if (!token.HasLeadingTrivia) { Debug.Assert(this.TreeInfo.GetTextBetween(default, token).All(IsCSharpWhitespace)); return GetSpaceTriviaData(space: 0); } var result = Analyzer.Leading(token); var info = GetWhitespaceOnlyTriviaInfo(default, token, result); if (info != null) { Debug.Assert(this.TreeInfo.GetTextBetween(default, token).All(IsCSharpWhitespace)); return info; } return new ComplexTrivia(this.Options, this.TreeInfo, default, token); } public override TriviaData CreateTrailingTrivia(SyntaxToken token) { // no trivia if (!token.HasTrailingTrivia) { Debug.Assert(this.TreeInfo.GetTextBetween(token, default).All(IsCSharpWhitespace)); return GetSpaceTriviaData(space: 0); } var result = Analyzer.Trailing(token); var info = GetWhitespaceOnlyTriviaInfo(token, default, result); if (info != null) { Debug.Assert(this.TreeInfo.GetTextBetween(token, default).All(IsCSharpWhitespace)); return info; } return new ComplexTrivia(this.Options, this.TreeInfo, token, default); } public override TriviaData Create(SyntaxToken token1, SyntaxToken token2) { // no trivia in between if (!token1.HasTrailingTrivia && !token2.HasLeadingTrivia) { Debug.Assert(string.IsNullOrWhiteSpace(this.TreeInfo.GetTextBetween(token1, token2))); return GetSpaceTriviaData(space: 0); } var result = Analyzer.Between(token1, token2); var info = GetWhitespaceOnlyTriviaInfo(token1, token2, result); if (info != null) { Debug.Assert(string.IsNullOrWhiteSpace(this.TreeInfo.GetTextBetween(token1, token2))); return info; } return new ComplexTrivia(this.Options, this.TreeInfo, token1, token2); } private static bool ContainsOnlyWhitespace(Analyzer.AnalysisResult result) { return !result.HasComments && !result.HasPreprocessor && !result.HasSkippedTokens && !result.HasSkippedOrDisabledText && !result.HasConflictMarker; } private TriviaData? GetWhitespaceOnlyTriviaInfo(SyntaxToken token1, SyntaxToken token2, Analyzer.AnalysisResult result) { if (!ContainsOnlyWhitespace(result)) { return null; } // only whitespace in between var space = GetSpaceOnSingleLine(result); Contract.ThrowIfFalse(space >= -1); if (space >= 0) { // check whether we can use cache return GetSpaceTriviaData(space, result.TreatAsElastic); } // tab is used in a place where it is not an indentation if (result.LineBreaks == 0 && result.Tab > 0) { // calculate actual space size from tab var spaces = CalculateSpaces(token1, token2); return new ModifiedWhitespace(this.Options, result.LineBreaks, indentation: spaces, elastic: result.TreatAsElastic, language: LanguageNames.CSharp); } // check whether we can cache trivia info for current indentation var lineCountAndIndentation = GetLineBreaksAndIndentation(result); return GetWhitespaceTriviaData(lineCountAndIndentation.lineBreaks, lineCountAndIndentation.indentation, lineCountAndIndentation.canUseTriviaAsItIs, result.TreatAsElastic); } private int CalculateSpaces(SyntaxToken token1, SyntaxToken token2) { var initialColumn = (token1.RawKind == 0) ? 0 : this.TreeInfo.GetOriginalColumn(TabSize, token1) + token1.Span.Length; var textSnippet = this.TreeInfo.GetTextBetween(token1, token2); return textSnippet.ConvertTabToSpace(TabSize, initialColumn, textSnippet.Length); } private (bool canUseTriviaAsItIs, int lineBreaks, int indentation) GetLineBreaksAndIndentation(Analyzer.AnalysisResult result) { Debug.Assert(result.Tab >= 0); Debug.Assert(result.LineBreaks >= 0); var indentation = result.Tab * TabSize + result.Space; if (result.HasTrailingSpace || result.HasUnknownWhitespace) { if (result.HasUnknownWhitespace && result.LineBreaks == 0 && indentation == 0) { // make sure we don't remove all whitespace indentation = 1; } return (canUseTriviaAsItIs: false, result.LineBreaks, indentation); } if (!UseTabs) { if (result.Tab > 0) { return (canUseTriviaAsItIs: false, result.LineBreaks, indentation); } return (canUseTriviaAsItIs: true, result.LineBreaks, indentation); } Debug.Assert(UseTabs); // tab can only appear before space to be a valid tab for indentation if (result.HasTabAfterSpace) { return (canUseTriviaAsItIs: false, result.LineBreaks, indentation); } if (result.Space >= TabSize) { return (canUseTriviaAsItIs: false, result.LineBreaks, indentation); } Debug.Assert((indentation / TabSize) == result.Tab); Debug.Assert((indentation % TabSize) == result.Space); return (canUseTriviaAsItIs: true, result.LineBreaks, indentation); } private static int GetSpaceOnSingleLine(Analyzer.AnalysisResult result) { if (result.HasTrailingSpace || result.HasUnknownWhitespace || result.LineBreaks > 0 || result.Tab > 0) { return -1; } return result.Space; } } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/CodeFixes/RemoveUnreachableCode/CSharpRemoveUnreachableCodeCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.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.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.RemoveUnreachableCode { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.RemoveUnreachableCode), Shared] internal class CSharpRemoveUnreachableCodeCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpRemoveUnreachableCodeCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(IDEDiagnosticIds.RemoveUnreachableCodeDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeQuality; public override Task RegisterCodeFixesAsync(CodeFixContext context) { var diagnostic = context.Diagnostics[0]; #if CODE_STYLE // 'CodeActionPriority' is not a public API, hence not supported in CodeStyle layer. // https://github.com/dotnet/roslyn/issues/42431 tracks adding a public API. var codeAction = new MyCodeAction( CSharpCodeFixesResources.Remove_unreachable_code, c => FixAsync(context.Document, diagnostic, c)); #else // Only the first reported unreacha ble line will have a squiggle. On that line, make the // code action normal priority as the user is likely bringing up the lightbulb to fix the // squiggle. On all the other lines make the code action low priority as it's definitely // helpful, but shouldn't interfere with anything else the uesr is doing. var priority = IsSubsequentSection(diagnostic) ? CodeActionPriority.Low : CodeActionPriority.Medium; var codeAction = new MyCodeAction( CSharpCodeFixesResources.Remove_unreachable_code, c => FixAsync(context.Document, diagnostic, c), priority); #endif context.RegisterCodeFix(codeAction, diagnostic); return Task.CompletedTask; } protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) => !IsSubsequentSection(diagnostic); private static bool IsSubsequentSection(Diagnostic diagnostic) => diagnostic.Properties.ContainsKey(CSharpRemoveUnreachableCodeDiagnosticAnalyzer.IsSubsequentSection); protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { foreach (var diagnostic in diagnostics) { var firstUnreachableStatementLocation = diagnostic.AdditionalLocations.First(); var firstUnreachableStatement = (StatementSyntax)firstUnreachableStatementLocation.FindNode(cancellationToken); RemoveStatement(editor, firstUnreachableStatement); var sections = RemoveUnreachableCodeHelpers.GetSubsequentUnreachableSections(firstUnreachableStatement); foreach (var section in sections) { foreach (var statement in section) { RemoveStatement(editor, statement); } } } return Task.CompletedTask; // Local function static void RemoveStatement(SyntaxEditor editor, SyntaxNode statement) { if (!statement.IsParentKind(SyntaxKind.Block) && !statement.IsParentKind(SyntaxKind.SwitchSection)) { editor.ReplaceNode(statement, SyntaxFactory.Block()); } else { editor.RemoveNode(statement, SyntaxRemoveOptions.KeepUnbalancedDirectives); } } } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { #if CODE_STYLE // 'CodeActionPriority' is not a public API, hence not supported in CodeStyle layer. // https://github.com/dotnet/roslyn/issues/42431 tracks adding a public API. public MyCodeAction( string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } #else public MyCodeAction( string title, Func<CancellationToken, Task<Document>> createChangedDocument, CodeActionPriority priority) : base(title, createChangedDocument, title) { Priority = priority; } internal override CodeActionPriority Priority { get; } #endif } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.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.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.RemoveUnreachableCode { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.RemoveUnreachableCode), Shared] internal class CSharpRemoveUnreachableCodeCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpRemoveUnreachableCodeCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(IDEDiagnosticIds.RemoveUnreachableCodeDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeQuality; public override Task RegisterCodeFixesAsync(CodeFixContext context) { var diagnostic = context.Diagnostics[0]; #if CODE_STYLE // 'CodeActionPriority' is not a public API, hence not supported in CodeStyle layer. // https://github.com/dotnet/roslyn/issues/42431 tracks adding a public API. var codeAction = new MyCodeAction( CSharpCodeFixesResources.Remove_unreachable_code, c => FixAsync(context.Document, diagnostic, c)); #else // Only the first reported unreacha ble line will have a squiggle. On that line, make the // code action normal priority as the user is likely bringing up the lightbulb to fix the // squiggle. On all the other lines make the code action low priority as it's definitely // helpful, but shouldn't interfere with anything else the uesr is doing. var priority = IsSubsequentSection(diagnostic) ? CodeActionPriority.Low : CodeActionPriority.Medium; var codeAction = new MyCodeAction( CSharpCodeFixesResources.Remove_unreachable_code, c => FixAsync(context.Document, diagnostic, c), priority); #endif context.RegisterCodeFix(codeAction, diagnostic); return Task.CompletedTask; } protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) => !IsSubsequentSection(diagnostic); private static bool IsSubsequentSection(Diagnostic diagnostic) => diagnostic.Properties.ContainsKey(CSharpRemoveUnreachableCodeDiagnosticAnalyzer.IsSubsequentSection); protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { foreach (var diagnostic in diagnostics) { var firstUnreachableStatementLocation = diagnostic.AdditionalLocations.First(); var firstUnreachableStatement = (StatementSyntax)firstUnreachableStatementLocation.FindNode(cancellationToken); RemoveStatement(editor, firstUnreachableStatement); var sections = RemoveUnreachableCodeHelpers.GetSubsequentUnreachableSections(firstUnreachableStatement); foreach (var section in sections) { foreach (var statement in section) { RemoveStatement(editor, statement); } } } return Task.CompletedTask; // Local function static void RemoveStatement(SyntaxEditor editor, SyntaxNode statement) { if (!statement.IsParentKind(SyntaxKind.Block) && !statement.IsParentKind(SyntaxKind.SwitchSection)) { editor.ReplaceNode(statement, SyntaxFactory.Block()); } else { editor.RemoveNode(statement, SyntaxRemoveOptions.KeepUnbalancedDirectives); } } } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { #if CODE_STYLE // 'CodeActionPriority' is not a public API, hence not supported in CodeStyle layer. // https://github.com/dotnet/roslyn/issues/42431 tracks adding a public API. public MyCodeAction( string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } #else public MyCodeAction( string title, Func<CancellationToken, Task<Document>> createChangedDocument, CodeActionPriority priority) : base(title, createChangedDocument, title) { Priority = priority; } internal override CodeActionPriority Priority { get; } #endif } } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/TableDataSource/AbstractTableControlEventProcessorProvider.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.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Shell.TableManager; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource { internal abstract class AbstractTableControlEventProcessorProvider<TItem> : ITableControlEventProcessorProvider where TItem : TableItem { public ITableControlEventProcessor GetAssociatedEventProcessor(IWpfTableControl tableControl) => CreateEventProcessor(); protected virtual EventProcessor CreateEventProcessor() => new(); protected class EventProcessor : TableControlEventProcessorBase { protected static AbstractTableEntriesSnapshot<TItem> GetEntriesSnapshot(ITableEntryHandle entryHandle) => GetEntriesSnapshot(entryHandle, out _); protected static AbstractTableEntriesSnapshot<TItem> GetEntriesSnapshot(ITableEntryHandle entryHandle, out int index) { if (!entryHandle.TryGetSnapshot(out var snapshot, out index)) { return null; } return snapshot as AbstractTableEntriesSnapshot<TItem>; } public override void PreprocessNavigate(ITableEntryHandle entryHandle, TableEntryNavigateEventArgs e) { var roslynSnapshot = GetEntriesSnapshot(entryHandle, out var index); if (roslynSnapshot == null) { return; } // don't be too strict on navigation on our item. if we can't handle the item, // let default handler to handle it at least. // we might fail to navigate if we don't see the document in our solution anymore. // that can happen if error is staled build error or user used #line pragma in C# // to point to some random file in error or more. // TODO: Use a threaded-wait-dialog here so we can cancel navigation. e.Handled = roslynSnapshot.TryNavigateTo(index, e.IsPreview, e.ShouldActivate, CancellationToken.None); } } } }
// Licensed to the .NET Foundation under one or more 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.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Shell.TableManager; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource { internal abstract class AbstractTableControlEventProcessorProvider<TItem> : ITableControlEventProcessorProvider where TItem : TableItem { public ITableControlEventProcessor GetAssociatedEventProcessor(IWpfTableControl tableControl) => CreateEventProcessor(); protected virtual EventProcessor CreateEventProcessor() => new(); protected class EventProcessor : TableControlEventProcessorBase { protected static AbstractTableEntriesSnapshot<TItem> GetEntriesSnapshot(ITableEntryHandle entryHandle) => GetEntriesSnapshot(entryHandle, out _); protected static AbstractTableEntriesSnapshot<TItem> GetEntriesSnapshot(ITableEntryHandle entryHandle, out int index) { if (!entryHandle.TryGetSnapshot(out var snapshot, out index)) { return null; } return snapshot as AbstractTableEntriesSnapshot<TItem>; } public override void PreprocessNavigate(ITableEntryHandle entryHandle, TableEntryNavigateEventArgs e) { var roslynSnapshot = GetEntriesSnapshot(entryHandle, out var index); if (roslynSnapshot == null) { return; } // don't be too strict on navigation on our item. if we can't handle the item, // let default handler to handle it at least. // we might fail to navigate if we don't see the document in our solution anymore. // that can happen if error is staled build error or user used #line pragma in C# // to point to some random file in error or more. // TODO: Use a threaded-wait-dialog here so we can cancel navigation. e.Handled = roslynSnapshot.TryNavigateTo(index, e.IsPreview, e.ShouldActivate, CancellationToken.None); } } } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/VisualBasic/Impl/Options/AutomationObject/AutomationObject.DocumentationComment.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.DocumentationComments Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options Partial Public Class AutomationObject Public Property AutoComment As Boolean Get Return GetBooleanOption(DocumentationCommentOptions.AutoXmlDocCommentGeneration) End Get Set(value As Boolean) SetBooleanOption(DocumentationCommentOptions.AutoXmlDocCommentGeneration, value) End Set End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.DocumentationComments Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options Partial Public Class AutomationObject Public Property AutoComment As Boolean Get Return GetBooleanOption(DocumentationCommentOptions.AutoXmlDocCommentGeneration) End Get Set(value As Boolean) SetBooleanOption(DocumentationCommentOptions.AutoXmlDocCommentGeneration, value) End Set End Property End Class End Namespace
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/Test/Resources/Core/MetadataTests/NetModule01/ModuleCS00.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; public delegate byte ModDele(sbyte p1, ref string p2); public enum ModEnum : ulong { None = 0, Red = 255, White = 255255, Blue=1 } public interface ModIBase { object ReadOnlyProp { get; } object M(ref object p1, out object p2, params object[] ary); } namespace NS.Module { public interface ModIDerive : ModIBase { object this[object p] { get; set; } } public struct ModStruct { public ModStruct(ModClass p = default(ModClass)) : this() { SField = p; } private ModClass SField; internal ushort SProp { get; set; } public ulong SM() { return 0; } } public class ModClass { private short prop = 0; public short CProp { get { return prop; } set { prop = value; } } public ModIDerive CM(int p1 = 0, uint p2 = 1, long p3 = 2) { return null; } public string this[string s] { get { return s; } } } } public static class StaticModClass { }
// Licensed to the .NET Foundation under one or more 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; public delegate byte ModDele(sbyte p1, ref string p2); public enum ModEnum : ulong { None = 0, Red = 255, White = 255255, Blue=1 } public interface ModIBase { object ReadOnlyProp { get; } object M(ref object p1, out object p2, params object[] ary); } namespace NS.Module { public interface ModIDerive : ModIBase { object this[object p] { get; set; } } public struct ModStruct { public ModStruct(ModClass p = default(ModClass)) : this() { SField = p; } private ModClass SField; internal ushort SProp { get; set; } public ulong SM() { return 0; } } public class ModClass { private short prop = 0; public short CProp { get { return prop; } set { prop = value; } } public ModIDerive CM(int p1 = 0, uint p2 = 1, long p3 = 2) { return null; } public string this[string s] { get { return s; } } } } public static class StaticModClass { }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/CodeFixes/UseCompoundAssignment/CSharpUseCompoundCoalesceAssignmentCodeFixProvider.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.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.UseCompoundAssignment { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseCompoundCoalesceAssignment), Shared] internal class CSharpUseCompoundCoalesceAssignmentCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpUseCompoundCoalesceAssignmentCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(IDEDiagnosticIds.UseCoalesceCompoundAssignmentDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; public override Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var diagnostic = context.Diagnostics[0]; context.RegisterCodeFix(new MyCodeAction( c => FixAsync(document, diagnostic, c)), context.Diagnostics); return Task.CompletedTask; } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var syntaxKinds = syntaxFacts.SyntaxKinds; foreach (var diagnostic in diagnostics) { var coalesce = diagnostic.AdditionalLocations[0].FindNode(getInnermostNodeForTie: true, cancellationToken); // changing from `x ?? (x = y)` to `x ??= y` can change the type. Specifically, // with nullable value types (`int?`) it could change from `int?` to `int`. // // Add an explicit cast to the original type to ensure semantics are preserved. // Simplification engine can then remove it if it's not necessary. var type = semanticModel.GetTypeInfo(coalesce, cancellationToken).Type; editor.ReplaceNode(coalesce, (currentCoalesceNode, generator) => { var currentCoalesce = (BinaryExpressionSyntax)currentCoalesceNode; var coalesceRight = (ParenthesizedExpressionSyntax)currentCoalesce.Right; var assignment = (AssignmentExpressionSyntax)coalesceRight.Expression; var compoundOperator = SyntaxFactory.Token(SyntaxKind.QuestionQuestionEqualsToken); var finalAssignment = SyntaxFactory.AssignmentExpression( SyntaxKind.CoalesceAssignmentExpression, assignment.Left, compoundOperator.WithTriviaFrom(assignment.OperatorToken), assignment.Right); return type == null || type.IsErrorType() ? finalAssignment : generator.CastExpression(type, finalAssignment); }); } } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(AnalyzersResources.Use_compound_assignment, createChangedDocument, AnalyzersResources.Use_compound_assignment) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.UseCompoundAssignment { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseCompoundCoalesceAssignment), Shared] internal class CSharpUseCompoundCoalesceAssignmentCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpUseCompoundCoalesceAssignmentCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(IDEDiagnosticIds.UseCoalesceCompoundAssignmentDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; public override Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var diagnostic = context.Diagnostics[0]; context.RegisterCodeFix(new MyCodeAction( c => FixAsync(document, diagnostic, c)), context.Diagnostics); return Task.CompletedTask; } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var syntaxKinds = syntaxFacts.SyntaxKinds; foreach (var diagnostic in diagnostics) { var coalesce = diagnostic.AdditionalLocations[0].FindNode(getInnermostNodeForTie: true, cancellationToken); // changing from `x ?? (x = y)` to `x ??= y` can change the type. Specifically, // with nullable value types (`int?`) it could change from `int?` to `int`. // // Add an explicit cast to the original type to ensure semantics are preserved. // Simplification engine can then remove it if it's not necessary. var type = semanticModel.GetTypeInfo(coalesce, cancellationToken).Type; editor.ReplaceNode(coalesce, (currentCoalesceNode, generator) => { var currentCoalesce = (BinaryExpressionSyntax)currentCoalesceNode; var coalesceRight = (ParenthesizedExpressionSyntax)currentCoalesce.Right; var assignment = (AssignmentExpressionSyntax)coalesceRight.Expression; var compoundOperator = SyntaxFactory.Token(SyntaxKind.QuestionQuestionEqualsToken); var finalAssignment = SyntaxFactory.AssignmentExpression( SyntaxKind.CoalesceAssignmentExpression, assignment.Left, compoundOperator.WithTriviaFrom(assignment.OperatorToken), assignment.Right); return type == null || type.IsErrorType() ? finalAssignment : generator.CastExpression(type, finalAssignment); }); } } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(AnalyzersResources.Use_compound_assignment, createChangedDocument, AnalyzersResources.Use_compound_assignment) { } } } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/Directory.Build.props
<Project> <Import Project="$([MSBuild]::GetPathOfFileAbove('Directory.Build.props', '$(MSBuildThisFileDirectory)../'))" /> <PropertyGroup> <ExcludeFromSourceBuild>true</ExcludeFromSourceBuild> </PropertyGroup> </Project>
<Project> <Import Project="$([MSBuild]::GetPathOfFileAbove('Directory.Build.props', '$(MSBuildThisFileDirectory)../'))" /> <PropertyGroup> <ExcludeFromSourceBuild>true</ExcludeFromSourceBuild> </PropertyGroup> </Project>
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/SharedUtilitiesAndExtensions/Workspace/CSharp/Lightup/NullableSyntaxAnnotationEx.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Reflection; #if !CODE_STYLE using Microsoft.CodeAnalysis.CodeGeneration; using Roslyn.Utilities; #endif namespace Microsoft.CodeAnalysis.CSharp.Shared.Lightup { internal static class NullableSyntaxAnnotationEx { public static SyntaxAnnotation? Oblivious { get; } public static SyntaxAnnotation? AnnotatedOrNotAnnotated { get; } static NullableSyntaxAnnotationEx() { var nullableSyntaxAnnotation = typeof(Workspace).Assembly.GetType("Microsoft.CodeAnalysis.CodeGeneration.NullableSyntaxAnnotation", throwOnError: false); if (nullableSyntaxAnnotation is object) { Oblivious = (SyntaxAnnotation?)nullableSyntaxAnnotation.GetField(nameof(Oblivious), BindingFlags.Static | BindingFlags.Public)?.GetValue(null); AnnotatedOrNotAnnotated = (SyntaxAnnotation?)nullableSyntaxAnnotation.GetField(nameof(AnnotatedOrNotAnnotated), BindingFlags.Static | BindingFlags.Public)?.GetValue(null); } #if !CODE_STYLE Contract.ThrowIfFalse(ReferenceEquals(Oblivious, NullableSyntaxAnnotation.Oblivious)); Contract.ThrowIfFalse(ReferenceEquals(AnnotatedOrNotAnnotated, NullableSyntaxAnnotation.AnnotatedOrNotAnnotated)); #endif } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Reflection; #if !CODE_STYLE using Microsoft.CodeAnalysis.CodeGeneration; using Roslyn.Utilities; #endif namespace Microsoft.CodeAnalysis.CSharp.Shared.Lightup { internal static class NullableSyntaxAnnotationEx { public static SyntaxAnnotation? Oblivious { get; } public static SyntaxAnnotation? AnnotatedOrNotAnnotated { get; } static NullableSyntaxAnnotationEx() { var nullableSyntaxAnnotation = typeof(Workspace).Assembly.GetType("Microsoft.CodeAnalysis.CodeGeneration.NullableSyntaxAnnotation", throwOnError: false); if (nullableSyntaxAnnotation is object) { Oblivious = (SyntaxAnnotation?)nullableSyntaxAnnotation.GetField(nameof(Oblivious), BindingFlags.Static | BindingFlags.Public)?.GetValue(null); AnnotatedOrNotAnnotated = (SyntaxAnnotation?)nullableSyntaxAnnotation.GetField(nameof(AnnotatedOrNotAnnotated), BindingFlags.Static | BindingFlags.Public)?.GetValue(null); } #if !CODE_STYLE Contract.ThrowIfFalse(ReferenceEquals(Oblivious, NullableSyntaxAnnotation.Oblivious)); Contract.ThrowIfFalse(ReferenceEquals(AnnotatedOrNotAnnotated, NullableSyntaxAnnotation.AnnotatedOrNotAnnotated)); #endif } } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/TodoComment/TodoCommentTests.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.Editor.Implementation.TodoComments Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Test.Utilities.TodoComments Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.TodoComment <[UseExportProvider]> Public Class TodoCommentTests Inherits AbstractTodoCommentTests Protected Overrides Function CreateWorkspace(codeWithMarker As String) As TestWorkspace Dim workspace = TestWorkspace.CreateVisualBasic(codeWithMarker) workspace.SetOptions(workspace.Options.WithChangedOption(TodoCommentOptions.TokenList, DefaultTokenList)) Return workspace End Function <Fact> Public Async Function TestSingleLineTodoComment_Colon() As Task Dim code = <code>' [|TODO:test|]</code> Await TestAsync(code) End Function <Fact> Public Async Function TestSingleLineTodoComment_Space() As Task Dim code = <code>' [|TODO test|]</code> Await TestAsync(code) End Function <Fact> Public Async Function TestSingleLineTodoComment_Underscore() As Task Dim code = <code>' TODO_test</code> Await TestAsync(code) End Function <Fact> Public Async Function TestSingleLineTodoComment_Number() As Task Dim code = <code>' TODO1 test</code> Await TestAsync(code) End Function <Fact> Public Async Function TestSingleLineTodoComment_Quote() As Task Dim code = <code>' "TODO test"</code> Await TestAsync(code) End Function <Fact> Public Async Function TestSingleLineTodoComment_Middle() As Task Dim code = <code>' Hello TODO test</code> Await TestAsync(code) End Function <Fact> Public Async Function TestSingleLineTodoComment_Document() As Task Dim code = <code>''' [|TODO test|]</code> Await TestAsync(code) End Function <Fact> Public Async Function TestSingleLineTodoComment_Preprocessor1() As Task Dim code = <code>#If DEBUG Then ' [|TODO test|]</code> Await TestAsync(code) End Function <Fact> Public Async Function TestSingleLineTodoComment_Preprocessor2() As Task Dim code = <code>#If DEBUG Then ''' [|TODO test|]</code> Await TestAsync(code) End Function <Fact> Public Async Function TestSingleLineTodoComment_Region() As Task Dim code = <code>#Region ' [|TODO test |]</code> Await TestAsync(code) End Function <Fact> Public Async Function TestSingleLineTodoComment_EndRegion() As Task Dim code = <code>#End Region ' [|TODO test |]</code> Await TestAsync(code) End Function <Fact> Public Async Function TestSingleLineTodoComment_TrailingSpan() As Task Dim code = <code>' [|TODO test |]</code> Await TestAsync(code) End Function <Fact> Public Async Function TestSingleLineTodoComment_REM() As Task Dim code = <code>REM [|TODO test |]</code> Await TestAsync(code) End Function <Fact> Public Async Function TestSingleLineTodoComment_Preprocessor_REM() As Task Dim code = <code>#If Debug Then REM [|TODO test |]</code> Await TestAsync(code) End Function <Fact> Public Async Function TestSinglelineDocumentComment_Multiline() As Task Dim code = <code> ''' <summary> ''' [|TODO : test |] ''' </summary> ''' [|UNDONE: test2 |]</code> Await TestAsync(code) End Function <Fact> <WorkItem(606010, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/606010")> Public Async Function TestLeftRightSingleQuote() As Task Dim code = <code> ‘[|todo fullwidth 1|] ’[|todo fullwidth 2|] </code> Await TestAsync(code) End Function <Fact> <WorkItem(606019, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/606019")> Public Async Function TestHalfFullTodo() As Task Dim code = <code> '[|todo whatever|] </code> Await TestAsync(code) End Function <Fact> <WorkItem(627723, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627723")> Public Async Function TestSingleQuote_Invalid1() As Task Dim code = <code> '' todo whatever </code> Await TestAsync(code) End Function <Fact> <WorkItem(627723, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627723")> Public Async Function TestSingleQuote_Invalid2() As Task Dim code = <code> '''' todo whatever </code> Await TestAsync(code) End Function <Fact> <WorkItem(627723, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627723")> Public Async Function TestSingleQuote_Invalid3() As Task Dim code = <code> ' '' todo whatever </code> Await TestAsync(code) End Function Private Overloads Function TestAsync(codeWithMarker As XElement) As Task Return TestAsync(codeWithMarker.NormalizedValue()) 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.Editor.Implementation.TodoComments Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Test.Utilities.TodoComments Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.TodoComment <[UseExportProvider]> Public Class TodoCommentTests Inherits AbstractTodoCommentTests Protected Overrides Function CreateWorkspace(codeWithMarker As String) As TestWorkspace Dim workspace = TestWorkspace.CreateVisualBasic(codeWithMarker) workspace.SetOptions(workspace.Options.WithChangedOption(TodoCommentOptions.TokenList, DefaultTokenList)) Return workspace End Function <Fact> Public Async Function TestSingleLineTodoComment_Colon() As Task Dim code = <code>' [|TODO:test|]</code> Await TestAsync(code) End Function <Fact> Public Async Function TestSingleLineTodoComment_Space() As Task Dim code = <code>' [|TODO test|]</code> Await TestAsync(code) End Function <Fact> Public Async Function TestSingleLineTodoComment_Underscore() As Task Dim code = <code>' TODO_test</code> Await TestAsync(code) End Function <Fact> Public Async Function TestSingleLineTodoComment_Number() As Task Dim code = <code>' TODO1 test</code> Await TestAsync(code) End Function <Fact> Public Async Function TestSingleLineTodoComment_Quote() As Task Dim code = <code>' "TODO test"</code> Await TestAsync(code) End Function <Fact> Public Async Function TestSingleLineTodoComment_Middle() As Task Dim code = <code>' Hello TODO test</code> Await TestAsync(code) End Function <Fact> Public Async Function TestSingleLineTodoComment_Document() As Task Dim code = <code>''' [|TODO test|]</code> Await TestAsync(code) End Function <Fact> Public Async Function TestSingleLineTodoComment_Preprocessor1() As Task Dim code = <code>#If DEBUG Then ' [|TODO test|]</code> Await TestAsync(code) End Function <Fact> Public Async Function TestSingleLineTodoComment_Preprocessor2() As Task Dim code = <code>#If DEBUG Then ''' [|TODO test|]</code> Await TestAsync(code) End Function <Fact> Public Async Function TestSingleLineTodoComment_Region() As Task Dim code = <code>#Region ' [|TODO test |]</code> Await TestAsync(code) End Function <Fact> Public Async Function TestSingleLineTodoComment_EndRegion() As Task Dim code = <code>#End Region ' [|TODO test |]</code> Await TestAsync(code) End Function <Fact> Public Async Function TestSingleLineTodoComment_TrailingSpan() As Task Dim code = <code>' [|TODO test |]</code> Await TestAsync(code) End Function <Fact> Public Async Function TestSingleLineTodoComment_REM() As Task Dim code = <code>REM [|TODO test |]</code> Await TestAsync(code) End Function <Fact> Public Async Function TestSingleLineTodoComment_Preprocessor_REM() As Task Dim code = <code>#If Debug Then REM [|TODO test |]</code> Await TestAsync(code) End Function <Fact> Public Async Function TestSinglelineDocumentComment_Multiline() As Task Dim code = <code> ''' <summary> ''' [|TODO : test |] ''' </summary> ''' [|UNDONE: test2 |]</code> Await TestAsync(code) End Function <Fact> <WorkItem(606010, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/606010")> Public Async Function TestLeftRightSingleQuote() As Task Dim code = <code> ‘[|todo fullwidth 1|] ’[|todo fullwidth 2|] </code> Await TestAsync(code) End Function <Fact> <WorkItem(606019, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/606019")> Public Async Function TestHalfFullTodo() As Task Dim code = <code> '[|todo whatever|] </code> Await TestAsync(code) End Function <Fact> <WorkItem(627723, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627723")> Public Async Function TestSingleQuote_Invalid1() As Task Dim code = <code> '' todo whatever </code> Await TestAsync(code) End Function <Fact> <WorkItem(627723, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627723")> Public Async Function TestSingleQuote_Invalid2() As Task Dim code = <code> '''' todo whatever </code> Await TestAsync(code) End Function <Fact> <WorkItem(627723, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627723")> Public Async Function TestSingleQuote_Invalid3() As Task Dim code = <code> ' '' todo whatever </code> Await TestAsync(code) End Function Private Overloads Function TestAsync(codeWithMarker As XElement) As Task Return TestAsync(codeWithMarker.NormalizedValue()) End Function End Class End Namespace
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/Progression/IProgressionLanguageService.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.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { internal interface IProgressionLanguageService : ILanguageService { IEnumerable<SyntaxNode> GetTopLevelNodesFromDocument(SyntaxNode root, CancellationToken cancellationToken); string GetDescriptionForSymbol(ISymbol symbol, bool includeContainingSymbol); string GetLabelForSymbol(ISymbol symbol, bool includeContainingSymbol); } }
// Licensed to the .NET Foundation under one or more 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.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { internal interface IProgressionLanguageService : ILanguageService { IEnumerable<SyntaxNode> GetTopLevelNodesFromDocument(SyntaxNode root, CancellationToken cancellationToken); string GetDescriptionForSymbol(ISymbol symbol, bool includeContainingSymbol); string GetLabelForSymbol(ISymbol symbol, bool includeContainingSymbol); } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/Symbols/Wrapped/WrappedEventSymbol.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.Globalization; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents an event that is based on another event. /// When inheriting from this class, one shouldn't assume that /// the default behavior it has is appropriate for every case. /// That behavior should be carefully reviewed and derived type /// should override behavior as appropriate. /// </summary> internal abstract class WrappedEventSymbol : EventSymbol { /// <summary> /// The underlying EventSymbol. /// </summary> protected readonly EventSymbol _underlyingEvent; public WrappedEventSymbol(EventSymbol underlyingEvent) { RoslynDebug.Assert((object)underlyingEvent != null); _underlyingEvent = underlyingEvent; } public EventSymbol UnderlyingEvent { get { return _underlyingEvent; } } public override bool IsImplicitlyDeclared { get { return _underlyingEvent.IsImplicitlyDeclared; } } internal override bool HasSpecialName { get { return _underlyingEvent.HasSpecialName; } } public override string Name { get { return _underlyingEvent.Name; } } public override string GetDocumentationCommentXml(CultureInfo? preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) { return _underlyingEvent.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken); } public override ImmutableArray<Location> Locations { get { return _underlyingEvent.Locations; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return _underlyingEvent.DeclaringSyntaxReferences; } } public override Accessibility DeclaredAccessibility { get { return _underlyingEvent.DeclaredAccessibility; } } public override bool IsStatic { get { return _underlyingEvent.IsStatic; } } public override bool IsVirtual { get { return _underlyingEvent.IsVirtual; } } public override bool IsOverride { get { return _underlyingEvent.IsOverride; } } public override bool IsAbstract { get { return _underlyingEvent.IsAbstract; } } public override bool IsSealed { get { return _underlyingEvent.IsSealed; } } public override bool IsExtern { get { return _underlyingEvent.IsExtern; } } internal override ObsoleteAttributeData? ObsoleteAttributeData { get { return _underlyingEvent.ObsoleteAttributeData; } } public override bool IsWindowsRuntimeEvent { get { return _underlyingEvent.IsWindowsRuntimeEvent; } } internal override bool HasRuntimeSpecialName { get { return _underlyingEvent.HasRuntimeSpecialName; } } } }
// Licensed to the .NET Foundation under one or more 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.Globalization; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents an event that is based on another event. /// When inheriting from this class, one shouldn't assume that /// the default behavior it has is appropriate for every case. /// That behavior should be carefully reviewed and derived type /// should override behavior as appropriate. /// </summary> internal abstract class WrappedEventSymbol : EventSymbol { /// <summary> /// The underlying EventSymbol. /// </summary> protected readonly EventSymbol _underlyingEvent; public WrappedEventSymbol(EventSymbol underlyingEvent) { RoslynDebug.Assert((object)underlyingEvent != null); _underlyingEvent = underlyingEvent; } public EventSymbol UnderlyingEvent { get { return _underlyingEvent; } } public override bool IsImplicitlyDeclared { get { return _underlyingEvent.IsImplicitlyDeclared; } } internal override bool HasSpecialName { get { return _underlyingEvent.HasSpecialName; } } public override string Name { get { return _underlyingEvent.Name; } } public override string GetDocumentationCommentXml(CultureInfo? preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) { return _underlyingEvent.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken); } public override ImmutableArray<Location> Locations { get { return _underlyingEvent.Locations; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return _underlyingEvent.DeclaringSyntaxReferences; } } public override Accessibility DeclaredAccessibility { get { return _underlyingEvent.DeclaredAccessibility; } } public override bool IsStatic { get { return _underlyingEvent.IsStatic; } } public override bool IsVirtual { get { return _underlyingEvent.IsVirtual; } } public override bool IsOverride { get { return _underlyingEvent.IsOverride; } } public override bool IsAbstract { get { return _underlyingEvent.IsAbstract; } } public override bool IsSealed { get { return _underlyingEvent.IsSealed; } } public override bool IsExtern { get { return _underlyingEvent.IsExtern; } } internal override ObsoleteAttributeData? ObsoleteAttributeData { get { return _underlyingEvent.ObsoleteAttributeData; } } public override bool IsWindowsRuntimeEvent { get { return _underlyingEvent.IsWindowsRuntimeEvent; } } internal override bool HasRuntimeSpecialName { get { return _underlyingEvent.HasRuntimeSpecialName; } } } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/SignatureHelp/ObjectCreationExpressionSignatureHelpProvider_NormalType.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 System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SignatureHelp; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp { internal partial class ObjectCreationExpressionSignatureHelpProvider { private static (IList<SignatureHelpItem> items, int? selectedItem) GetNormalTypeConstructors( Document document, BaseObjectCreationExpressionSyntax objectCreationExpression, SemanticModel semanticModel, IAnonymousTypeDisplayService anonymousTypeDisplayService, IDocumentationCommentFormattingService documentationCommentFormattingService, INamedTypeSymbol normalType, ISymbol within, CancellationToken cancellationToken) { var accessibleConstructors = normalType.InstanceConstructors .WhereAsArray(c => c.IsAccessibleWithin(within)) .WhereAsArray(s => s.IsEditorBrowsable(document.ShouldHideAdvancedMembers(), semanticModel.Compilation)) .Sort(semanticModel, objectCreationExpression.SpanStart); var symbolInfo = semanticModel.GetSymbolInfo(objectCreationExpression, cancellationToken); var selectedItem = TryGetSelectedIndex(accessibleConstructors, symbolInfo.Symbol); var items = accessibleConstructors.SelectAsArray(c => ConvertNormalTypeConstructor(c, objectCreationExpression, semanticModel, anonymousTypeDisplayService, documentationCommentFormattingService)); return (items, selectedItem); } private static SignatureHelpItem ConvertNormalTypeConstructor( IMethodSymbol constructor, BaseObjectCreationExpressionSyntax objectCreationExpression, SemanticModel semanticModel, IAnonymousTypeDisplayService anonymousTypeDisplayService, IDocumentationCommentFormattingService documentationCommentFormattingService) { var position = objectCreationExpression.SpanStart; var item = CreateItem( constructor, semanticModel, position, anonymousTypeDisplayService, constructor.IsParams(), constructor.GetDocumentationPartsFactory(semanticModel, position, documentationCommentFormattingService), GetNormalTypePreambleParts(constructor, semanticModel, position), GetSeparatorParts(), GetNormalTypePostambleParts(), constructor.Parameters.Select(p => Convert(p, semanticModel, position, documentationCommentFormattingService)).ToList()); return item; } private static IList<SymbolDisplayPart> GetNormalTypePreambleParts( IMethodSymbol method, SemanticModel semanticModel, int position) { var result = new List<SymbolDisplayPart>(); result.AddRange(method.ContainingType.ToMinimalDisplayParts(semanticModel, position)); result.Add(Punctuation(SyntaxKind.OpenParenToken)); return result; } private static IList<SymbolDisplayPart> GetNormalTypePostambleParts() { return SpecializedCollections.SingletonList( Punctuation(SyntaxKind.CloseParenToken)); } } }
// Licensed to the .NET Foundation under one or more 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 System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SignatureHelp; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp { internal partial class ObjectCreationExpressionSignatureHelpProvider { private static (IList<SignatureHelpItem> items, int? selectedItem) GetNormalTypeConstructors( Document document, BaseObjectCreationExpressionSyntax objectCreationExpression, SemanticModel semanticModel, IAnonymousTypeDisplayService anonymousTypeDisplayService, IDocumentationCommentFormattingService documentationCommentFormattingService, INamedTypeSymbol normalType, ISymbol within, CancellationToken cancellationToken) { var accessibleConstructors = normalType.InstanceConstructors .WhereAsArray(c => c.IsAccessibleWithin(within)) .WhereAsArray(s => s.IsEditorBrowsable(document.ShouldHideAdvancedMembers(), semanticModel.Compilation)) .Sort(semanticModel, objectCreationExpression.SpanStart); var symbolInfo = semanticModel.GetSymbolInfo(objectCreationExpression, cancellationToken); var selectedItem = TryGetSelectedIndex(accessibleConstructors, symbolInfo.Symbol); var items = accessibleConstructors.SelectAsArray(c => ConvertNormalTypeConstructor(c, objectCreationExpression, semanticModel, anonymousTypeDisplayService, documentationCommentFormattingService)); return (items, selectedItem); } private static SignatureHelpItem ConvertNormalTypeConstructor( IMethodSymbol constructor, BaseObjectCreationExpressionSyntax objectCreationExpression, SemanticModel semanticModel, IAnonymousTypeDisplayService anonymousTypeDisplayService, IDocumentationCommentFormattingService documentationCommentFormattingService) { var position = objectCreationExpression.SpanStart; var item = CreateItem( constructor, semanticModel, position, anonymousTypeDisplayService, constructor.IsParams(), constructor.GetDocumentationPartsFactory(semanticModel, position, documentationCommentFormattingService), GetNormalTypePreambleParts(constructor, semanticModel, position), GetSeparatorParts(), GetNormalTypePostambleParts(), constructor.Parameters.Select(p => Convert(p, semanticModel, position, documentationCommentFormattingService)).ToList()); return item; } private static IList<SymbolDisplayPart> GetNormalTypePreambleParts( IMethodSymbol method, SemanticModel semanticModel, int position) { var result = new List<SymbolDisplayPart>(); result.AddRange(method.ContainingType.ToMinimalDisplayParts(semanticModel, position)); result.Add(Punctuation(SyntaxKind.OpenParenToken)); return result; } private static IList<SymbolDisplayPart> GetNormalTypePostambleParts() { return SpecializedCollections.SingletonList( Punctuation(SyntaxKind.CloseParenToken)); } } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/InternalImplementationOnlyAttribute.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Runtime.CompilerServices { /// <summary> /// This is a marker attribute that can be put on an interface to denote that only internal implementations /// of that interface should exist. /// </summary> [AttributeUsage(AttributeTargets.Interface, AllowMultiple = false)] internal sealed class InternalImplementationOnlyAttribute : Attribute { } }
// Licensed to the .NET Foundation under one or more 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 System.Runtime.CompilerServices { /// <summary> /// This is a marker attribute that can be put on an interface to denote that only internal implementations /// of that interface should exist. /// </summary> [AttributeUsage(AttributeTargets.Interface, AllowMultiple = false)] internal sealed class InternalImplementationOnlyAttribute : Attribute { } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/MakeTypeAbstract/MakeTypeAbstractTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.MakeTypeAbstract; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.MakeTypeAbstract { public class MakeTypeAbstractTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public MakeTypeAbstractTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpMakeTypeAbstractCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task TestMethod() { await TestInRegularAndScript1Async( @" public class Goo { public abstract void [|M|](); }", @" public abstract class Goo { public abstract void M(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task TestMethodEnclosingClassWithoutAccessibility() { await TestInRegularAndScript1Async( @" class Goo { public abstract void [|M|](); }", @" abstract class Goo { public abstract void M(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task TestMethodEnclosingClassDocumentationComment() { await TestInRegularAndScript1Async( @" /// <summary> /// Some class comment. /// </summary> public class Goo { public abstract void [|M|](); }", @" /// <summary> /// Some class comment. /// </summary> public abstract class Goo { public abstract void M(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task TestPropertyGetter() { await TestInRegularAndScript1Async( @" public class Goo { public abstract object P { [|get|]; } }", @" public abstract class Goo { public abstract object P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task TestPropertySetter() { await TestInRegularAndScript1Async( @" public class Goo { public abstract object P { [|set|]; } }", @" public abstract class Goo { public abstract object P { set; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task TestIndexerGetter() { await TestInRegularAndScript1Async( @" public class Goo { public abstract object this[object o] { [|get|]; } }", @" public abstract class Goo { public abstract object this[object o] { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task TestIndexerSetter() { await TestInRegularAndScript1Async( @" public class Goo { public abstract object this[object o] { [|set|]; } }", @" public abstract class Goo { public abstract object this[object o] { set; } }"); } [WorkItem(54218, "https://github.com/dotnet/roslyn/issues/54218")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task TestPartialClass() { await TestInRegularAndScript1Async( @" public partial class Goo { public abstract void [|M|](); } public partial class Goo { }", @" public abstract partial class Goo { public abstract void M(); } public partial class Goo { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task TestEventAdd() { await TestMissingInRegularAndScriptAsync( @" public class Goo { public abstract event System.EventHandler E { [|add|]; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task TestEventRemove() { await TestMissingInRegularAndScriptAsync( @" public class Goo { public abstract event System.EventHandler E { [|remove|]; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task TestMethodWithBody() { await TestMissingInRegularAndScriptAsync( @" public class Goo { public abstract int [|M|]() => 3; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task TestPropertyGetterWithArrowBody() { await TestMissingInRegularAndScriptAsync( @" public class Goo { public abstract int [|P|] => 3; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task TestPropertyGetterWithBody() { await TestMissingInRegularAndScriptAsync( @" public class Goo { public abstract int P { [|get|] { return 1; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task TestStructNestedInClass() { await TestMissingInRegularAndScriptAsync( @" public class C { public struct S { public abstract void [|Goo|](); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task TestMethodEnclosingClassStatic() { await TestMissingInRegularAndScriptAsync( @" public static class Goo { public abstract void [|M|](); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task TestRecord() { await TestInRegularAndScript1Async( @" public record Goo { public abstract void [|M|](); }", @" public abstract record Goo { public abstract void M(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task TestRecordClass() { await TestInRegularAndScript1Async( @" public record class Goo { public abstract void [|M|](); }", @" public abstract record class Goo { public abstract void M(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task TestRecordStruct() { await TestMissingInRegularAndScriptAsync(@" public record struct Goo { public abstract void [|M|](); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task FixAll() { await TestInRegularAndScript1Async( @"namespace NS { using System; public class C1 { public abstract void {|FixAllInDocument:|}M(); public abstract object P { get; set; } public abstract object this[object o] { get; set; } } public class C2 { public abstract void M(); } public class C3 { public class InnerClass { public abstract void M(); } } }", @"namespace NS { using System; public abstract class C1 { public abstract void M(); public abstract object P { get; set; } public abstract object this[object o] { get; set; } } public abstract class C2 { public abstract void M(); } public class C3 { public abstract class InnerClass { public abstract void M(); } } }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.MakeTypeAbstract; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.MakeTypeAbstract { public class MakeTypeAbstractTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public MakeTypeAbstractTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpMakeTypeAbstractCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task TestMethod() { await TestInRegularAndScript1Async( @" public class Goo { public abstract void [|M|](); }", @" public abstract class Goo { public abstract void M(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task TestMethodEnclosingClassWithoutAccessibility() { await TestInRegularAndScript1Async( @" class Goo { public abstract void [|M|](); }", @" abstract class Goo { public abstract void M(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task TestMethodEnclosingClassDocumentationComment() { await TestInRegularAndScript1Async( @" /// <summary> /// Some class comment. /// </summary> public class Goo { public abstract void [|M|](); }", @" /// <summary> /// Some class comment. /// </summary> public abstract class Goo { public abstract void M(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task TestPropertyGetter() { await TestInRegularAndScript1Async( @" public class Goo { public abstract object P { [|get|]; } }", @" public abstract class Goo { public abstract object P { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task TestPropertySetter() { await TestInRegularAndScript1Async( @" public class Goo { public abstract object P { [|set|]; } }", @" public abstract class Goo { public abstract object P { set; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task TestIndexerGetter() { await TestInRegularAndScript1Async( @" public class Goo { public abstract object this[object o] { [|get|]; } }", @" public abstract class Goo { public abstract object this[object o] { get; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task TestIndexerSetter() { await TestInRegularAndScript1Async( @" public class Goo { public abstract object this[object o] { [|set|]; } }", @" public abstract class Goo { public abstract object this[object o] { set; } }"); } [WorkItem(54218, "https://github.com/dotnet/roslyn/issues/54218")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task TestPartialClass() { await TestInRegularAndScript1Async( @" public partial class Goo { public abstract void [|M|](); } public partial class Goo { }", @" public abstract partial class Goo { public abstract void M(); } public partial class Goo { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task TestEventAdd() { await TestMissingInRegularAndScriptAsync( @" public class Goo { public abstract event System.EventHandler E { [|add|]; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task TestEventRemove() { await TestMissingInRegularAndScriptAsync( @" public class Goo { public abstract event System.EventHandler E { [|remove|]; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task TestMethodWithBody() { await TestMissingInRegularAndScriptAsync( @" public class Goo { public abstract int [|M|]() => 3; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task TestPropertyGetterWithArrowBody() { await TestMissingInRegularAndScriptAsync( @" public class Goo { public abstract int [|P|] => 3; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task TestPropertyGetterWithBody() { await TestMissingInRegularAndScriptAsync( @" public class Goo { public abstract int P { [|get|] { return 1; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task TestStructNestedInClass() { await TestMissingInRegularAndScriptAsync( @" public class C { public struct S { public abstract void [|Goo|](); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task TestMethodEnclosingClassStatic() { await TestMissingInRegularAndScriptAsync( @" public static class Goo { public abstract void [|M|](); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task TestRecord() { await TestInRegularAndScript1Async( @" public record Goo { public abstract void [|M|](); }", @" public abstract record Goo { public abstract void M(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task TestRecordClass() { await TestInRegularAndScript1Async( @" public record class Goo { public abstract void [|M|](); }", @" public abstract record class Goo { public abstract void M(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task TestRecordStruct() { await TestMissingInRegularAndScriptAsync(@" public record struct Goo { public abstract void [|M|](); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeTypeAbstract)] public async Task FixAll() { await TestInRegularAndScript1Async( @"namespace NS { using System; public class C1 { public abstract void {|FixAllInDocument:|}M(); public abstract object P { get; set; } public abstract object this[object o] { get; set; } } public class C2 { public abstract void M(); } public class C3 { public class InnerClass { public abstract void M(); } } }", @"namespace NS { using System; public abstract class C1 { public abstract void M(); public abstract object P { get; set; } public abstract object this[object o] { get; set; } } public abstract class C2 { public abstract void M(); } public class C3 { public abstract class InnerClass { public abstract void M(); } } }"); } } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/Test/Core/Compilation/TestOperationVisitor.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.Linq; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Test.Utilities { public sealed class TestOperationVisitor : OperationVisitor { public static readonly TestOperationVisitor Singleton = new TestOperationVisitor(); private TestOperationVisitor() : base() { } public override void DefaultVisit(IOperation operation) { throw new NotImplementedException(operation.GetType().ToString()); } internal override void VisitNoneOperation(IOperation operation) { #if Test_IOperation_None_Kind Assert.True(false, "Encountered an IOperation with `Kind == OperationKind.None` while walking the operation tree."); #endif Assert.Equal(OperationKind.None, operation.Kind); } public override void Visit(IOperation operation) { if (operation != null) { var syntax = operation.Syntax; var type = operation.Type; var constantValue = operation.ConstantValue; Assert.NotNull(syntax); // operation.Language can throw due to https://github.com/dotnet/roslyn/issues/23821 // Conditional logic below should be removed once the issue is fixed if (syntax is Microsoft.CodeAnalysis.Syntax.SyntaxList) { Assert.Equal(OperationKind.None, operation.Kind); Assert.Equal(LanguageNames.CSharp, operation.Parent.Language); } else { var language = operation.Language; } var isImplicit = operation.IsImplicit; foreach (IOperation child in operation.Children) { Assert.NotNull(child); } if (operation.SemanticModel != null) { Assert.Same(operation.SemanticModel, operation.SemanticModel.ContainingModelOrSelf); } } base.Visit(operation); } public override void VisitBlock(IBlockOperation operation) { Assert.Equal(OperationKind.Block, operation.Kind); VisitLocals(operation.Locals); AssertEx.Equal(operation.Operations, operation.Children); } public override void VisitVariableDeclarationGroup(IVariableDeclarationGroupOperation operation) { Assert.Equal(OperationKind.VariableDeclarationGroup, operation.Kind); AssertEx.Equal(operation.Declarations, operation.Children); } public override void VisitVariableDeclarator(IVariableDeclaratorOperation operation) { Assert.Equal(OperationKind.VariableDeclarator, operation.Kind); Assert.NotNull(operation.Symbol); IEnumerable<IOperation> children = operation.IgnoredArguments; var initializer = operation.Initializer; if (initializer != null) { children = children.Concat(new[] { initializer }); } AssertEx.Equal(children, operation.Children); } public override void VisitVariableDeclaration(IVariableDeclarationOperation operation) { Assert.Equal(OperationKind.VariableDeclaration, operation.Kind); IEnumerable<IOperation> children = operation.IgnoredDimensions.Concat(operation.Declarators); var initializer = operation.Initializer; if (initializer != null) { children = children.Concat(new[] { initializer }); } AssertEx.Equal(children, operation.Children); } public override void VisitSwitch(ISwitchOperation operation) { Assert.Equal(OperationKind.Switch, operation.Kind); VisitLocals(operation.Locals); Assert.NotNull(operation.ExitLabel); AssertEx.Equal(new[] { operation.Value }.Concat(operation.Cases), operation.Children); } public override void VisitSwitchCase(ISwitchCaseOperation operation) { Assert.Equal(OperationKind.SwitchCase, operation.Kind); VisitLocals(operation.Locals); AssertEx.Equal(operation.Clauses.Concat(operation.Body), operation.Children); VerifySubTree(((SwitchCaseOperation)operation).Condition, hasNonNullParent: true); } internal static void VerifySubTree(IOperation root, bool hasNonNullParent = false) { if (root != null) { if (hasNonNullParent) { // This is only ever true for ISwitchCaseOperation.Condition. Assert.NotNull(root.Parent); Assert.Same(root, ((SwitchCaseOperation)root.Parent).Condition); } else { Assert.Null(root.Parent); } var explicitNodeMap = new Dictionary<SyntaxNode, IOperation>(); foreach (IOperation descendant in root.DescendantsAndSelf()) { if (!descendant.IsImplicit) { try { explicitNodeMap.Add(descendant.Syntax, descendant); } catch (ArgumentException) { Assert.False(true, $"Duplicate explicit node for syntax ({descendant.Syntax.RawKind}): {descendant.Syntax.ToString()}"); } } Singleton.Visit(descendant); } } } public override void VisitSingleValueCaseClause(ISingleValueCaseClauseOperation operation) { VisitCaseClauseOperation(operation); Assert.Equal(CaseKind.SingleValue, operation.CaseKind); AssertEx.Equal(new[] { operation.Value }, operation.Children); } private static void VisitCaseClauseOperation(ICaseClauseOperation operation) { Assert.Equal(OperationKind.CaseClause, operation.Kind); _ = operation.Label; } public override void VisitRelationalCaseClause(IRelationalCaseClauseOperation operation) { VisitCaseClauseOperation(operation); Assert.Equal(CaseKind.Relational, operation.CaseKind); var relation = operation.Relation; AssertEx.Equal(new[] { operation.Value }, operation.Children); } public override void VisitDefaultCaseClause(IDefaultCaseClauseOperation operation) { VisitCaseClauseOperation(operation); Assert.Equal(CaseKind.Default, operation.CaseKind); Assert.Empty(operation.Children); } private static void VisitLocals(ImmutableArray<ILocalSymbol> locals) { foreach (var local in locals) { Assert.NotNull(local); } } public override void VisitWhileLoop(IWhileLoopOperation operation) { VisitLoop(operation); Assert.Equal(LoopKind.While, operation.LoopKind); var conditionIsTop = operation.ConditionIsTop; var conditionIsUntil = operation.ConditionIsUntil; IEnumerable<IOperation> children; if (conditionIsTop) { if (operation.IgnoredCondition != null) { children = new[] { operation.Condition, operation.Body, operation.IgnoredCondition }; } else { children = new[] { operation.Condition, operation.Body }; } } else { Assert.Null(operation.IgnoredCondition); if (operation.Condition != null) { children = new[] { operation.Body, operation.Condition }; } else { children = new[] { operation.Body }; } } AssertEx.Equal(children, operation.Children); } public override void VisitForLoop(IForLoopOperation operation) { VisitLoop(operation); Assert.Equal(LoopKind.For, operation.LoopKind); VisitLocals(operation.Locals); VisitLocals(operation.ConditionLocals); IEnumerable<IOperation> children = operation.Before; if (operation.Condition != null) { children = children.Concat(new[] { operation.Condition }); } children = children.Concat(new[] { operation.Body }); children = children.Concat(operation.AtLoopBottom); AssertEx.Equal(children, operation.Children); } public override void VisitForToLoop(IForToLoopOperation operation) { VisitLoop(operation); Assert.Equal(LoopKind.ForTo, operation.LoopKind); _ = operation.IsChecked; (ILocalSymbol loopObject, ForToLoopOperationUserDefinedInfo userDefinedInfo) = ((ForToLoopOperation)operation).Info; if (userDefinedInfo != null) { VerifySubTree(userDefinedInfo.Addition); VerifySubTree(userDefinedInfo.Subtraction); VerifySubTree(userDefinedInfo.LessThanOrEqual); VerifySubTree(userDefinedInfo.GreaterThanOrEqual); } IEnumerable<IOperation> children; children = new[] { operation.LoopControlVariable, operation.InitialValue, operation.LimitValue, operation.StepValue, operation.Body }; children = children.Concat(operation.NextVariables); AssertEx.Equal(children, operation.Children); } public override void VisitForEachLoop(IForEachLoopOperation operation) { VisitLoop(operation); Assert.Equal(LoopKind.ForEach, operation.LoopKind); IEnumerable<IOperation> children = new[] { operation.Collection, operation.LoopControlVariable, operation.Body }.Concat(operation.NextVariables); AssertEx.Equal(children, operation.Children); ForEachLoopOperationInfo info = ((ForEachLoopOperation)operation).Info; if (info != null) { visitArguments(info.GetEnumeratorArguments); visitArguments(info.MoveNextArguments); visitArguments(info.CurrentArguments); visitArguments(info.DisposeArguments); } void visitArguments(ImmutableArray<IArgumentOperation> arguments) { if (arguments != null) { foreach (IArgumentOperation arg in arguments) { VerifySubTree(arg); } } } } private static void VisitLoop(ILoopOperation operation) { Assert.Equal(OperationKind.Loop, operation.Kind); VisitLocals(operation.Locals); Assert.NotNull(operation.ContinueLabel); Assert.NotNull(operation.ExitLabel); } public override void VisitLabeled(ILabeledOperation operation) { Assert.Equal(OperationKind.Labeled, operation.Kind); Assert.NotNull(operation.Label); if (operation.Operation == null) { Assert.Empty(operation.Children); } else { Assert.Same(operation.Operation, operation.Children.Single()); } } public override void VisitBranch(IBranchOperation operation) { Assert.Equal(OperationKind.Branch, operation.Kind); Assert.NotNull(operation.Target); switch (operation.BranchKind) { case BranchKind.Break: case BranchKind.Continue: case BranchKind.GoTo: break; default: Assert.False(true); break; } Assert.Empty(operation.Children); } public override void VisitEmpty(IEmptyOperation operation) { Assert.Equal(OperationKind.Empty, operation.Kind); Assert.Empty(operation.Children); } public override void VisitReturn(IReturnOperation operation) { Assert.Contains(operation.Kind, new[] { OperationKind.Return, OperationKind.YieldReturn, OperationKind.YieldBreak }); if (operation.ReturnedValue == null) { Assert.NotEqual(OperationKind.YieldReturn, operation.Kind); Assert.Empty(operation.Children); } else { Assert.Same(operation.ReturnedValue, operation.Children.Single()); } } public override void VisitLock(ILockOperation operation) { Assert.Equal(OperationKind.Lock, operation.Kind); AssertEx.Equal(new[] { operation.LockedValue, operation.Body }, operation.Children); } public override void VisitTry(ITryOperation operation) { Assert.Equal(OperationKind.Try, operation.Kind); IEnumerable<IOperation> children = new[] { operation.Body }; _ = operation.ExitLabel; children = children.Concat(operation.Catches); if (operation.Finally != null) { children = children.Concat(new[] { operation.Finally }); } AssertEx.Equal(children, operation.Children); } public override void VisitCatchClause(ICatchClauseOperation operation) { Assert.Equal(OperationKind.CatchClause, operation.Kind); var exceptionType = operation.ExceptionType; VisitLocals(operation.Locals); IEnumerable<IOperation> children = Array.Empty<IOperation>(); if (operation.ExceptionDeclarationOrExpression != null) { children = children.Concat(new[] { operation.ExceptionDeclarationOrExpression }); } if (operation.Filter != null) { children = children.Concat(new[] { operation.Filter }); } children = children.Concat(new[] { operation.Handler }); AssertEx.Equal(children, operation.Children); } public override void VisitUsing(IUsingOperation operation) { Assert.Equal(OperationKind.Using, operation.Kind); VisitLocals(operation.Locals); AssertEx.Equal(new[] { operation.Resources, operation.Body }, operation.Children); Assert.NotEqual(OperationKind.VariableDeclaration, operation.Resources.Kind); Assert.NotEqual(OperationKind.VariableDeclarator, operation.Resources.Kind); _ = ((UsingOperation)operation).DisposeInfo.DisposeMethod; var disposeArgs = ((UsingOperation)operation).DisposeInfo.DisposeArguments; if (!disposeArgs.IsDefaultOrEmpty) { foreach (var arg in disposeArgs) { VerifySubTree(arg); } } } // https://github.com/dotnet/roslyn/issues/21281 internal override void VisitFixed(IFixedOperation operation) { Assert.Equal(OperationKind.None, operation.Kind); VisitLocals(operation.Locals); AssertEx.Equal(new[] { operation.Variables, operation.Body }, operation.Children); } internal override void VisitAggregateQuery(IAggregateQueryOperation operation) { Assert.Equal(OperationKind.None, operation.Kind); AssertEx.Equal(new[] { operation.Group, operation.Aggregation }, operation.Children); } public override void VisitExpressionStatement(IExpressionStatementOperation operation) { Assert.Equal(OperationKind.ExpressionStatement, operation.Kind); Assert.Same(operation.Operation, operation.Children.Single()); } internal override void VisitWithStatement(IWithStatementOperation operation) { Assert.Equal(OperationKind.None, operation.Kind); AssertEx.Equal(new[] { operation.Value, operation.Body }, operation.Children); } public override void VisitStop(IStopOperation operation) { Assert.Equal(OperationKind.Stop, operation.Kind); Assert.Empty(operation.Children); } public override void VisitEnd(IEndOperation operation) { Assert.Equal(OperationKind.End, operation.Kind); Assert.Empty(operation.Children); } public override void VisitInvocation(IInvocationOperation operation) { Assert.Equal(OperationKind.Invocation, operation.Kind); Assert.NotNull(operation.TargetMethod); var isVirtual = operation.IsVirtual; IEnumerable<IOperation> children; if (operation.Instance != null) { children = new[] { operation.Instance }.Concat(operation.Arguments); } else { children = operation.Arguments; } AssertEx.Equal(children, operation.Children); // Make sure that all static member references or invocations of static methods do not have implicit IInstanceReferenceOperations // as their receivers if (operation.TargetMethod.IsStatic && operation.Instance is IInstanceReferenceOperation) { Assert.False(operation.Instance.IsImplicit, $"Implicit {nameof(IInstanceReferenceOperation)} on {operation.Syntax}"); } } public override void VisitArgument(IArgumentOperation operation) { Assert.Equal(OperationKind.Argument, operation.Kind); Assert.Contains(operation.ArgumentKind, new[] { ArgumentKind.DefaultValue, ArgumentKind.Explicit, ArgumentKind.ParamArray }); var parameter = operation.Parameter; Assert.Same(operation.Value, operation.Children.Single()); var inConversion = operation.InConversion; var outConversion = operation.OutConversion; if (operation.ArgumentKind == ArgumentKind.DefaultValue) { Assert.True(operation.Descendants().All(n => n.IsImplicit), $"Explicit node in default argument value ({operation.Syntax.RawKind}): {operation.Syntax.ToString()}"); } } public override void VisitOmittedArgument(IOmittedArgumentOperation operation) { Assert.Equal(OperationKind.OmittedArgument, operation.Kind); Assert.Empty(operation.Children); } public override void VisitArrayElementReference(IArrayElementReferenceOperation operation) { Assert.Equal(OperationKind.ArrayElementReference, operation.Kind); AssertEx.Equal(new[] { operation.ArrayReference }.Concat(operation.Indices), operation.Children); } internal override void VisitPointerIndirectionReference(IPointerIndirectionReferenceOperation operation) { Assert.Equal(OperationKind.None, operation.Kind); Assert.Same(operation.Pointer, operation.Children.Single()); } public override void VisitLocalReference(ILocalReferenceOperation operation) { Assert.Equal(OperationKind.LocalReference, operation.Kind); Assert.NotNull(operation.Local); var isDeclaration = operation.IsDeclaration; Assert.Empty(operation.Children); } public override void VisitParameterReference(IParameterReferenceOperation operation) { Assert.Equal(OperationKind.ParameterReference, operation.Kind); Assert.NotNull(operation.Parameter); Assert.Empty(operation.Children); } public override void VisitInstanceReference(IInstanceReferenceOperation operation) { Assert.Equal(OperationKind.InstanceReference, operation.Kind); Assert.Empty(operation.Children); var referenceKind = operation.ReferenceKind; } private void VisitMemberReference(IMemberReferenceOperation operation) { VisitMemberReference(operation, Array.Empty<IOperation>()); } private void VisitMemberReference(IMemberReferenceOperation operation, IEnumerable<IOperation> additionalChildren) { Assert.NotNull(operation.Member); IEnumerable<IOperation> children; if (operation.Instance != null) { children = new[] { operation.Instance }.Concat(additionalChildren); // Make sure that all static member references or invocations of static methods do not have implicit IInstanceReferenceOperations // as their receivers if (operation.Member.IsStatic && operation.Instance is IInstanceReferenceOperation) { Assert.False(operation.Instance.IsImplicit, $"Implicit {nameof(IInstanceReferenceOperation)} on {operation.Syntax}"); } } else { children = additionalChildren; } AssertEx.Equal(children, operation.Children); } public override void VisitFieldReference(IFieldReferenceOperation operation) { Assert.Equal(OperationKind.FieldReference, operation.Kind); VisitMemberReference(operation); Assert.Same(operation.Member, operation.Field); var isDeclaration = operation.IsDeclaration; } public override void VisitMethodReference(IMethodReferenceOperation operation) { Assert.Equal(OperationKind.MethodReference, operation.Kind); VisitMemberReference(operation); Assert.Same(operation.Member, operation.Method); var isVirtual = operation.IsVirtual; } public override void VisitPropertyReference(IPropertyReferenceOperation operation) { Assert.Equal(OperationKind.PropertyReference, operation.Kind); VisitMemberReference(operation, operation.Arguments); Assert.Same(operation.Member, operation.Property); } public override void VisitEventReference(IEventReferenceOperation operation) { Assert.Equal(OperationKind.EventReference, operation.Kind); VisitMemberReference(operation); Assert.Same(operation.Member, operation.Event); } public override void VisitEventAssignment(IEventAssignmentOperation operation) { Assert.Equal(OperationKind.EventAssignment, operation.Kind); var adds = operation.Adds; AssertEx.Equal(new[] { operation.EventReference, operation.HandlerValue }, operation.Children); } public override void VisitConditionalAccess(IConditionalAccessOperation operation) { Assert.Equal(OperationKind.ConditionalAccess, operation.Kind); Assert.NotNull(operation.Type); AssertEx.Equal(new[] { operation.Operation, operation.WhenNotNull }, operation.Children); } public override void VisitConditionalAccessInstance(IConditionalAccessInstanceOperation operation) { Assert.Equal(OperationKind.ConditionalAccessInstance, operation.Kind); Assert.Empty(operation.Children); } internal override void VisitPlaceholder(IPlaceholderOperation operation) { Assert.Equal(OperationKind.None, operation.Kind); Assert.Empty(operation.Children); } public override void VisitUnaryOperator(IUnaryOperation operation) { Assert.Equal(OperationKind.UnaryOperator, operation.Kind); Assert.Equal(OperationKind.Unary, operation.Kind); var operatorMethod = operation.OperatorMethod; var unaryOperationKind = operation.OperatorKind; var isLifted = operation.IsLifted; var isChecked = operation.IsChecked; Assert.Same(operation.Operand, operation.Children.Single()); } public override void VisitBinaryOperator(IBinaryOperation operation) { Assert.Equal(OperationKind.BinaryOperator, operation.Kind); Assert.Equal(OperationKind.Binary, operation.Kind); var operatorMethod = operation.OperatorMethod; var unaryOperatorMethod = ((BinaryOperation)operation).UnaryOperatorMethod; var binaryOperationKind = operation.OperatorKind; var isLifted = operation.IsLifted; var isChecked = operation.IsChecked; var isCompareText = operation.IsCompareText; AssertEx.Equal(new[] { operation.LeftOperand, operation.RightOperand }, operation.Children); } public override void VisitTupleBinaryOperator(ITupleBinaryOperation operation) { Assert.Equal(OperationKind.TupleBinaryOperator, operation.Kind); Assert.Equal(OperationKind.TupleBinary, operation.Kind); var binaryOperationKind = operation.OperatorKind; AssertEx.Equal(new[] { operation.LeftOperand, operation.RightOperand }, operation.Children); } public override void VisitConversion(IConversionOperation operation) { Assert.Equal(OperationKind.Conversion, operation.Kind); var operatorMethod = operation.OperatorMethod; var conversion = operation.Conversion; var isChecked = operation.IsChecked; var isTryCast = operation.IsTryCast; switch (operation.Language) { case LanguageNames.CSharp: CSharp.Conversion csharpConversion = CSharp.CSharpExtensions.GetConversion(operation); Assert.Throws<ArgumentException>(() => VisualBasic.VisualBasicExtensions.GetConversion(operation)); break; case LanguageNames.VisualBasic: VisualBasic.Conversion visualBasicConversion = VisualBasic.VisualBasicExtensions.GetConversion(operation); Assert.Throws<ArgumentException>(() => CSharp.CSharpExtensions.GetConversion(operation)); break; default: Debug.Fail($"Language {operation.Language} is unknown!"); break; } Assert.Same(operation.Operand, operation.Children.Single()); } public override void VisitConditional(IConditionalOperation operation) { Assert.Equal(OperationKind.Conditional, operation.Kind); bool isRef = operation.IsRef; if (operation.WhenFalse != null) { AssertEx.Equal(new[] { operation.Condition, operation.WhenTrue, operation.WhenFalse }, operation.Children); } else { AssertEx.Equal(new[] { operation.Condition, operation.WhenTrue }, operation.Children); } } public override void VisitCoalesce(ICoalesceOperation operation) { Assert.Equal(OperationKind.Coalesce, operation.Kind); AssertEx.Equal(new[] { operation.Value, operation.WhenNull }, operation.Children); var valueConversion = operation.ValueConversion; } public override void VisitCoalesceAssignment(ICoalesceAssignmentOperation operation) { Assert.Equal(OperationKind.CoalesceAssignment, operation.Kind); AssertEx.Equal(new[] { operation.Target, operation.Value }, operation.Children); } public override void VisitIsType(IIsTypeOperation operation) { Assert.Equal(OperationKind.IsType, operation.Kind); Assert.NotNull(operation.TypeOperand); bool isNegated = operation.IsNegated; Assert.Same(operation.ValueOperand, operation.Children.Single()); } public override void VisitSizeOf(ISizeOfOperation operation) { Assert.Equal(OperationKind.SizeOf, operation.Kind); Assert.NotNull(operation.TypeOperand); Assert.Empty(operation.Children); } public override void VisitTypeOf(ITypeOfOperation operation) { Assert.Equal(OperationKind.TypeOf, operation.Kind); Assert.NotNull(operation.TypeOperand); Assert.Empty(operation.Children); } public override void VisitAnonymousFunction(IAnonymousFunctionOperation operation) { Assert.Equal(OperationKind.AnonymousFunction, operation.Kind); Assert.NotNull(operation.Symbol); Assert.Same(operation.Body, operation.Children.Single()); } public override void VisitFlowAnonymousFunction(IFlowAnonymousFunctionOperation operation) { Assert.Equal(OperationKind.FlowAnonymousFunction, operation.Kind); Assert.NotNull(operation.Symbol); Assert.Empty(operation.Children); } public override void VisitLocalFunction(ILocalFunctionOperation operation) { Assert.Equal(OperationKind.LocalFunction, operation.Kind); Assert.NotNull(operation.Symbol); if (operation.Body != null) { var children = operation.Children.ToImmutableArray(); Assert.Same(operation.Body, children[0]); if (operation.IgnoredBody != null) { Assert.Same(operation.IgnoredBody, children[1]); Assert.Equal(2, children.Length); } else { Assert.Equal(1, children.Length); } } else { Assert.Null(operation.IgnoredBody); Assert.Empty(operation.Children); } } public override void VisitLiteral(ILiteralOperation operation) { Assert.Equal(OperationKind.Literal, operation.Kind); Assert.Empty(operation.Children); } public override void VisitAwait(IAwaitOperation operation) { Assert.Equal(OperationKind.Await, operation.Kind); Assert.Same(operation.Operation, operation.Children.Single()); } public override void VisitNameOf(INameOfOperation operation) { Assert.Equal(OperationKind.NameOf, operation.Kind); Assert.Same(operation.Argument, operation.Children.Single()); } public override void VisitThrow(IThrowOperation operation) { Assert.Equal(OperationKind.Throw, operation.Kind); if (operation.Exception == null) { Assert.Empty(operation.Children); } else { Assert.Same(operation.Exception, operation.Children.Single()); } } public override void VisitAddressOf(IAddressOfOperation operation) { Assert.Equal(OperationKind.AddressOf, operation.Kind); Assert.Same(operation.Reference, operation.Children.Single()); } public override void VisitObjectCreation(IObjectCreationOperation operation) { Assert.Equal(OperationKind.ObjectCreation, operation.Kind); var constructor = operation.Constructor; // When parameter-less struct constructor is inaccessible, the constructor symbol is null if (!operation.Type.IsValueType) { Assert.NotNull(constructor); if (constructor == null) { Assert.Empty(operation.Arguments); } } IEnumerable<IOperation> children = operation.Arguments; if (operation.Initializer != null) { children = children.Concat(new[] { operation.Initializer }); } AssertEx.Equal(children, operation.Children); } public override void VisitAnonymousObjectCreation(IAnonymousObjectCreationOperation operation) { Assert.Equal(OperationKind.AnonymousObjectCreation, operation.Kind); AssertEx.Equal(operation.Initializers, operation.Children); foreach (var initializer in operation.Initializers) { var simpleAssignment = (ISimpleAssignmentOperation)initializer; var propertyReference = (IPropertyReferenceOperation)simpleAssignment.Target; Assert.Empty(propertyReference.Arguments); Assert.Equal(OperationKind.InstanceReference, propertyReference.Instance.Kind); Assert.Equal(InstanceReferenceKind.ImplicitReceiver, ((IInstanceReferenceOperation)propertyReference.Instance).ReferenceKind); } } public override void VisitDynamicObjectCreation(IDynamicObjectCreationOperation operation) { Assert.Equal(OperationKind.DynamicObjectCreation, operation.Kind); IEnumerable<IOperation> children = operation.Arguments; if (operation.Initializer != null) { children = children.Concat(new[] { operation.Initializer }); } AssertEx.Equal(children, operation.Children); } public override void VisitDynamicInvocation(IDynamicInvocationOperation operation) { Assert.Equal(OperationKind.DynamicInvocation, operation.Kind); AssertEx.Equal(new[] { operation.Operation }.Concat(operation.Arguments), operation.Children); } public override void VisitDynamicIndexerAccess(IDynamicIndexerAccessOperation operation) { Assert.Equal(OperationKind.DynamicIndexerAccess, operation.Kind); AssertEx.Equal(new[] { operation.Operation }.Concat(operation.Arguments), operation.Children); } public override void VisitObjectOrCollectionInitializer(IObjectOrCollectionInitializerOperation operation) { Assert.Equal(OperationKind.ObjectOrCollectionInitializer, operation.Kind); AssertEx.Equal(operation.Initializers, operation.Children); } public override void VisitMemberInitializer(IMemberInitializerOperation operation) { Assert.Equal(OperationKind.MemberInitializer, operation.Kind); AssertEx.Equal(new[] { operation.InitializedMember, operation.Initializer }, operation.Children); } private void VisitSymbolInitializer(ISymbolInitializerOperation operation) { VisitLocals(operation.Locals); Assert.Same(operation.Value, operation.Children.Single()); } public override void VisitFieldInitializer(IFieldInitializerOperation operation) { Assert.Equal(OperationKind.FieldInitializer, operation.Kind); foreach (var field in operation.InitializedFields) { Assert.NotNull(field); } VisitSymbolInitializer(operation); } public override void VisitVariableInitializer(IVariableInitializerOperation operation) { Assert.Equal(OperationKind.VariableInitializer, operation.Kind); Assert.Empty(operation.Locals); VisitSymbolInitializer(operation); } public override void VisitPropertyInitializer(IPropertyInitializerOperation operation) { Assert.Equal(OperationKind.PropertyInitializer, operation.Kind); foreach (var property in operation.InitializedProperties) { Assert.NotNull(property); } VisitSymbolInitializer(operation); } public override void VisitParameterInitializer(IParameterInitializerOperation operation) { Assert.Equal(OperationKind.ParameterInitializer, operation.Kind); Assert.NotNull(operation.Parameter); VisitSymbolInitializer(operation); } public override void VisitArrayCreation(IArrayCreationOperation operation) { Assert.Equal(OperationKind.ArrayCreation, operation.Kind); IEnumerable<IOperation> children = operation.DimensionSizes; if (operation.Initializer != null) { children = children.Concat(new[] { operation.Initializer }); } AssertEx.Equal(children, operation.Children); } public override void VisitArrayInitializer(IArrayInitializerOperation operation) { Assert.Equal(OperationKind.ArrayInitializer, operation.Kind); Assert.Null(operation.Type); AssertEx.Equal(operation.ElementValues, operation.Children); } private void VisitAssignment(IAssignmentOperation operation) { AssertEx.Equal(new[] { operation.Target, operation.Value }, operation.Children); } public override void VisitSimpleAssignment(ISimpleAssignmentOperation operation) { Assert.Equal(OperationKind.SimpleAssignment, operation.Kind); bool isRef = operation.IsRef; VisitAssignment(operation); } public override void VisitCompoundAssignment(ICompoundAssignmentOperation operation) { Assert.Equal(OperationKind.CompoundAssignment, operation.Kind); var operatorMethod = operation.OperatorMethod; var binaryOperationKind = operation.OperatorKind; var inConversion = operation.InConversion; var outConversion = operation.OutConversion; if (operation.Syntax.Language == LanguageNames.CSharp) { Assert.Throws<ArgumentException>("compoundAssignment", () => VisualBasic.VisualBasicExtensions.GetInConversion(operation)); Assert.Throws<ArgumentException>("compoundAssignment", () => VisualBasic.VisualBasicExtensions.GetOutConversion(operation)); var inConversionInternal = CSharp.CSharpExtensions.GetInConversion(operation); var outConversionInternal = CSharp.CSharpExtensions.GetOutConversion(operation); } else { Assert.Throws<ArgumentException>("compoundAssignment", () => CSharp.CSharpExtensions.GetInConversion(operation)); Assert.Throws<ArgumentException>("compoundAssignment", () => CSharp.CSharpExtensions.GetOutConversion(operation)); var inConversionInternal = VisualBasic.VisualBasicExtensions.GetInConversion(operation); var outConversionInternal = VisualBasic.VisualBasicExtensions.GetOutConversion(operation); } var isLifted = operation.IsLifted; var isChecked = operation.IsChecked; VisitAssignment(operation); } public override void VisitIncrementOrDecrement(IIncrementOrDecrementOperation operation) { Assert.Contains(operation.Kind, new[] { OperationKind.Increment, OperationKind.Decrement }); var operatorMethod = operation.OperatorMethod; var isPostFix = operation.IsPostfix; var isLifted = operation.IsLifted; var isChecked = operation.IsChecked; Assert.Same(operation.Target, operation.Children.Single()); } public override void VisitParenthesized(IParenthesizedOperation operation) { Assert.Equal(OperationKind.Parenthesized, operation.Kind); Assert.Same(operation.Operand, operation.Children.Single()); } public override void VisitDynamicMemberReference(IDynamicMemberReferenceOperation operation) { Assert.Equal(OperationKind.DynamicMemberReference, operation.Kind); Assert.NotNull(operation.MemberName); foreach (var typeArg in operation.TypeArguments) { Assert.NotNull(typeArg); } var containingType = operation.ContainingType; if (operation.Instance == null) { Assert.Empty(operation.Children); } else { Assert.Same(operation.Instance, operation.Children.Single()); } } public override void VisitDefaultValue(IDefaultValueOperation operation) { Assert.Equal(OperationKind.DefaultValue, operation.Kind); Assert.Empty(operation.Children); } public override void VisitTypeParameterObjectCreation(ITypeParameterObjectCreationOperation operation) { Assert.Equal(OperationKind.TypeParameterObjectCreation, operation.Kind); if (operation.Initializer == null) { Assert.Empty(operation.Children); } else { Assert.Same(operation.Initializer, operation.Children.Single()); } } internal override void VisitNoPiaObjectCreation(INoPiaObjectCreationOperation operation) { Assert.Equal(OperationKind.None, operation.Kind); if (operation.Initializer == null) { Assert.Empty(operation.Children); } else { Assert.Same(operation.Initializer, operation.Children.Single()); } } public override void VisitInvalid(IInvalidOperation operation) { Assert.Equal(OperationKind.Invalid, operation.Kind); } public override void VisitTuple(ITupleOperation operation) { Assert.Equal(OperationKind.Tuple, operation.Kind); var naturalType = operation.NaturalType; AssertEx.Equal(operation.Elements, operation.Children); } public override void VisitInterpolatedString(IInterpolatedStringOperation operation) { Assert.Equal(OperationKind.InterpolatedString, operation.Kind); AssertEx.Equal(operation.Parts, operation.Children); } public override void VisitInterpolatedStringText(IInterpolatedStringTextOperation operation) { Assert.Equal(OperationKind.InterpolatedStringText, operation.Kind); if (operation.Text.Kind != OperationKind.Literal) { Assert.Equal(OperationKind.Literal, ((IConversionOperation)operation.Text).Operand.Kind); } Assert.Same(operation.Text, operation.Children.Single()); } public override void VisitInterpolation(IInterpolationOperation operation) { Assert.Equal(OperationKind.Interpolation, operation.Kind); IEnumerable<IOperation> children = new[] { operation.Expression }; if (operation.Alignment != null) { children = children.Concat(new[] { operation.Alignment }); } if (operation.FormatString != null) { if (operation.FormatString.Kind != OperationKind.Literal) { Assert.Equal(OperationKind.Literal, ((IConversionOperation)operation.FormatString).Operand.Kind); } children = children.Concat(new[] { operation.FormatString }); } AssertEx.Equal(children, operation.Children); } private void VisitPatternCommon(IPatternOperation pattern) { Assert.NotNull(pattern.InputType); Assert.NotNull(pattern.NarrowedType); Assert.Null(pattern.Type); Assert.False(pattern.ConstantValue.HasValue); } public override void VisitConstantPattern(IConstantPatternOperation operation) { Assert.Equal(OperationKind.ConstantPattern, operation.Kind); VisitPatternCommon(operation); Assert.Same(operation.Value, operation.Children.Single()); } public override void VisitRelationalPattern(IRelationalPatternOperation operation) { Assert.Equal(OperationKind.RelationalPattern, operation.Kind); Assert.True(operation.OperatorKind is Operations.BinaryOperatorKind.LessThan or Operations.BinaryOperatorKind.LessThanOrEqual or Operations.BinaryOperatorKind.GreaterThan or Operations.BinaryOperatorKind.GreaterThanOrEqual or Operations.BinaryOperatorKind.Equals or // Error cases Operations.BinaryOperatorKind.NotEquals); VisitPatternCommon(operation); Assert.Same(operation.Value, operation.Children.Single()); } public override void VisitBinaryPattern(IBinaryPatternOperation operation) { Assert.Equal(OperationKind.BinaryPattern, operation.Kind); VisitPatternCommon(operation); Assert.True(operation.OperatorKind switch { Operations.BinaryOperatorKind.Or => true, Operations.BinaryOperatorKind.And => true, _ => false }); var children = operation.Children.ToArray(); Assert.Equal(2, children.Length); Assert.Same(operation.LeftPattern, children[0]); Assert.Same(operation.RightPattern, children[1]); } public override void VisitNegatedPattern(INegatedPatternOperation operation) { Assert.Equal(OperationKind.NegatedPattern, operation.Kind); VisitPatternCommon(operation); Assert.Same(operation.Pattern, operation.Children.Single()); } public override void VisitTypePattern(ITypePatternOperation operation) { Assert.Equal(OperationKind.TypePattern, operation.Kind); Assert.NotNull(operation.MatchedType); VisitPatternCommon(operation); Assert.Empty(operation.Children); } public override void VisitDeclarationPattern(IDeclarationPatternOperation operation) { Assert.Equal(OperationKind.DeclarationPattern, operation.Kind); VisitPatternCommon(operation); if (operation.Syntax.IsKind(CSharp.SyntaxKind.VarPattern) || // in `var (x, y)`, the syntax here is the designation `x`. operation.Syntax.IsKind(CSharp.SyntaxKind.SingleVariableDesignation)) { Assert.True(operation.MatchesNull); Assert.Null(operation.MatchedType); } else { Assert.False(operation.MatchesNull); Assert.NotNull(operation.MatchedType); } var designation = (operation.Syntax as CSharp.Syntax.DeclarationPatternSyntax)?.Designation ?? (operation.Syntax as CSharp.Syntax.VarPatternSyntax)?.Designation ?? (operation.Syntax as CSharp.Syntax.VariableDesignationSyntax); if (designation.IsKind(CSharp.SyntaxKind.SingleVariableDesignation)) { Assert.NotNull(operation.DeclaredSymbol); } else { Assert.Null(operation.DeclaredSymbol); } Assert.Empty(operation.Children); } public override void VisitRecursivePattern(IRecursivePatternOperation operation) { Assert.Equal(OperationKind.RecursivePattern, operation.Kind); VisitPatternCommon(operation); Assert.NotNull(operation.MatchedType); switch (operation.DeconstructSymbol) { case IErrorTypeSymbol error: case null: // OK: indicates deconstruction of a tuple, or an error case break; case IMethodSymbol method: // when we have a method, it is a `Deconstruct` method Assert.Equal("Deconstruct", method.Name); break; case ITypeSymbol type: // when we have a type, it is the type "ITuple" Assert.Equal("ITuple", type.Name); break; default: Assert.True(false, $"Unexpected symbol {operation.DeconstructSymbol}"); break; } var designation = (operation.Syntax as CSharp.Syntax.RecursivePatternSyntax)?.Designation; if (designation.IsKind(CSharp.SyntaxKind.SingleVariableDesignation)) { Assert.NotNull(operation.DeclaredSymbol); } else { Assert.Null(operation.DeclaredSymbol); } foreach (var subpat in operation.PropertySubpatterns) { Assert.True(subpat is IPropertySubpatternOperation); } IEnumerable<IOperation> children = operation.DeconstructionSubpatterns.Cast<IOperation>(); children = children.Concat(operation.PropertySubpatterns); AssertEx.Equal(children, operation.Children); } public override void VisitPropertySubpattern(IPropertySubpatternOperation operation) { Assert.NotNull(operation.Pattern); var children = new IOperation[] { operation.Member, operation.Pattern }; AssertEx.Equal(children, operation.Children); if (operation.Member.Kind == OperationKind.Invalid) { return; } Assert.True(operation.Member is IMemberReferenceOperation); var member = (IMemberReferenceOperation)operation.Member; switch (member.Member) { case IFieldSymbol field: case IPropertySymbol prop: break; case var symbol: Assert.True(false, $"Unexpected symbol {symbol}"); break; } } public override void VisitSwitchExpression(ISwitchExpressionOperation operation) { //force the existence of IsExhaustive _ = operation.IsExhaustive; Assert.NotNull(operation.Type); Assert.False(operation.ConstantValue.HasValue); Assert.Equal(OperationKind.SwitchExpression, operation.Kind); Assert.NotNull(operation.Value); var children = operation.Arms.Cast<IOperation>().Prepend(operation.Value); AssertEx.Equal(children, operation.Children); } public override void VisitSwitchExpressionArm(ISwitchExpressionArmOperation operation) { Assert.Null(operation.Type); Assert.False(operation.ConstantValue.HasValue); Assert.NotNull(operation.Pattern); _ = operation.Guard; Assert.NotNull(operation.Value); VisitLocals(operation.Locals); var children = operation.Guard == null ? new[] { operation.Pattern, operation.Value } : new[] { operation.Pattern, operation.Guard, operation.Value }; AssertEx.Equal(children, operation.Children); } public override void VisitIsPattern(IIsPatternOperation operation) { Assert.Equal(OperationKind.IsPattern, operation.Kind); AssertEx.Equal(new[] { operation.Value, operation.Pattern }, operation.Children); } public override void VisitPatternCaseClause(IPatternCaseClauseOperation operation) { VisitCaseClauseOperation(operation); Assert.Equal(CaseKind.Pattern, operation.CaseKind); Assert.Same(((ICaseClauseOperation)operation).Label, operation.Label); if (operation.Guard != null) { AssertEx.Equal(new[] { operation.Pattern, operation.Guard }, operation.Children); } else { Assert.Same(operation.Pattern, operation.Children.Single()); } } public override void VisitTranslatedQuery(ITranslatedQueryOperation operation) { Assert.Equal(OperationKind.TranslatedQuery, operation.Kind); Assert.Same(operation.Operation, operation.Children.Single()); } public override void VisitDeclarationExpression(IDeclarationExpressionOperation operation) { Assert.Equal(OperationKind.DeclarationExpression, operation.Kind); Assert.Same(operation.Expression, operation.Children.Single()); } public override void VisitDeconstructionAssignment(IDeconstructionAssignmentOperation operation) { Assert.Equal(OperationKind.DeconstructionAssignment, operation.Kind); VisitAssignment(operation); } public override void VisitDelegateCreation(IDelegateCreationOperation operation) { Assert.Equal(OperationKind.DelegateCreation, operation.Kind); Assert.Same(operation.Target, operation.Children.Single()); } public override void VisitRaiseEvent(IRaiseEventOperation operation) { Assert.Equal(OperationKind.RaiseEvent, operation.Kind); AssertEx.Equal(new IOperation[] { operation.EventReference }.Concat(operation.Arguments), operation.Children); } public override void VisitRangeCaseClause(IRangeCaseClauseOperation operation) { VisitCaseClauseOperation(operation); Assert.Equal(CaseKind.Range, operation.CaseKind); AssertEx.Equal(new[] { operation.MinimumValue, operation.MaximumValue }, operation.Children); } public override void VisitConstructorBodyOperation(IConstructorBodyOperation operation) { Assert.Equal(OperationKind.ConstructorBodyOperation, operation.Kind); Assert.Equal(OperationKind.ConstructorBody, operation.Kind); VisitLocals(operation.Locals); var builder = ArrayBuilder<IOperation>.GetInstance(); if (operation.Initializer != null) { builder.Add(operation.Initializer); } if (operation.BlockBody != null) { builder.Add(operation.BlockBody); } if (operation.ExpressionBody != null) { builder.Add(operation.ExpressionBody); } AssertEx.Equal(builder, operation.Children); builder.Free(); } public override void VisitMethodBodyOperation(IMethodBodyOperation operation) { Assert.Equal(OperationKind.MethodBodyOperation, operation.Kind); Assert.Equal(OperationKind.MethodBody, operation.Kind); if (operation.BlockBody != null) { if (operation.ExpressionBody != null) { AssertEx.Equal(new[] { operation.BlockBody, operation.ExpressionBody }, operation.Children); } else { Assert.Same(operation.BlockBody, operation.Children.Single()); } } else if (operation.ExpressionBody != null) { Assert.Same(operation.ExpressionBody, operation.Children.Single()); } else { Assert.Empty(operation.Children); } } public override void VisitDiscardOperation(IDiscardOperation operation) { Assert.Equal(OperationKind.Discard, operation.Kind); Assert.Empty(operation.Children); var discardSymbol = operation.DiscardSymbol; Assert.Equal(operation.Type, discardSymbol.Type); } public override void VisitDiscardPattern(IDiscardPatternOperation operation) { Assert.Equal(OperationKind.DiscardPattern, operation.Kind); VisitPatternCommon(operation); Assert.Empty(operation.Children); } public override void VisitFlowCapture(IFlowCaptureOperation operation) { Assert.Equal(OperationKind.FlowCapture, operation.Kind); Assert.True(operation.IsImplicit); Assert.Same(operation.Value, operation.Children.Single()); switch (operation.Value.Kind) { case OperationKind.Invalid: case OperationKind.None: case OperationKind.AnonymousFunction: case OperationKind.FlowCaptureReference: case OperationKind.DefaultValue: case OperationKind.FlowAnonymousFunction: // must be an error case like in Microsoft.CodeAnalysis.CSharp.UnitTests.ConditionalOperatorTests.TestBothUntyped unit-test break; case OperationKind.OmittedArgument: case OperationKind.DeclarationExpression: case OperationKind.Discard: Assert.False(true, $"A {operation.Value.Kind} node should not be spilled or captured."); break; default: // Only values can be spilled/captured if (!operation.Value.ConstantValue.HasValue || operation.Value.ConstantValue.Value != null) { Assert.NotNull(operation.Value.Type); } break; } } public override void VisitFlowCaptureReference(IFlowCaptureReferenceOperation operation) { Assert.Equal(OperationKind.FlowCaptureReference, operation.Kind); Assert.True(operation.IsImplicit); Assert.Empty(operation.Children); } public override void VisitIsNull(IIsNullOperation operation) { Assert.Equal(OperationKind.IsNull, operation.Kind); Assert.True(operation.IsImplicit); Assert.Same(operation.Operand, operation.Children.Single()); } public override void VisitCaughtException(ICaughtExceptionOperation operation) { Assert.Equal(OperationKind.CaughtException, operation.Kind); Assert.True(operation.IsImplicit); Assert.Empty(operation.Children); } public override void VisitStaticLocalInitializationSemaphore(IStaticLocalInitializationSemaphoreOperation operation) { Assert.Equal(OperationKind.StaticLocalInitializationSemaphore, operation.Kind); Assert.True(operation.IsImplicit); Assert.Empty(operation.Children); Assert.NotNull(operation.Local); Assert.True(operation.Local.IsStatic); } public override void VisitRangeOperation(IRangeOperation operation) { Assert.Equal(OperationKind.Range, operation.Kind); IOperation[] children = operation.Children.ToArray(); int index = 0; if (operation.LeftOperand != null) { Assert.Same(operation.LeftOperand, children[index++]); } if (operation.RightOperand != null) { Assert.Same(operation.RightOperand, children[index++]); } Assert.Equal(index, children.Length); } public override void VisitReDim(IReDimOperation operation) { Assert.Equal(OperationKind.ReDim, operation.Kind); AssertEx.Equal(operation.Clauses, operation.Children); var preserve = operation.Preserve; } public override void VisitReDimClause(IReDimClauseOperation operation) { Assert.Equal(OperationKind.ReDimClause, operation.Kind); AssertEx.Equal(SpecializedCollections.SingletonEnumerable(operation.Operand).Concat(operation.DimensionSizes), operation.Children); } public override void VisitUsingDeclaration(IUsingDeclarationOperation operation) { Assert.NotNull(operation.DeclarationGroup); AssertEx.Equal(SpecializedCollections.SingletonEnumerable(operation.DeclarationGroup), operation.Children); Assert.True(operation.DeclarationGroup.IsImplicit); Assert.Null(operation.Type); Assert.False(operation.ConstantValue.HasValue); _ = operation.IsAsynchronous; _ = operation.IsImplicit; _ = ((UsingDeclarationOperation)operation).DisposeInfo.DisposeMethod; var disposeArgs = ((UsingDeclarationOperation)operation).DisposeInfo.DisposeArguments; if (!disposeArgs.IsDefaultOrEmpty) { foreach (var arg in disposeArgs) { VerifySubTree(arg); } } } public override void VisitWith(IWithOperation operation) { Assert.Equal(OperationKind.With, operation.Kind); _ = operation.CloneMethod; IEnumerable<IOperation> children = SpecializedCollections.SingletonEnumerable(operation.Operand).Concat(operation.Initializer); AssertEx.Equal(children, operation.Children); } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Test.Utilities { public sealed class TestOperationVisitor : OperationVisitor { public static readonly TestOperationVisitor Singleton = new TestOperationVisitor(); private TestOperationVisitor() : base() { } public override void DefaultVisit(IOperation operation) { throw new NotImplementedException(operation.GetType().ToString()); } internal override void VisitNoneOperation(IOperation operation) { #if Test_IOperation_None_Kind Assert.True(false, "Encountered an IOperation with `Kind == OperationKind.None` while walking the operation tree."); #endif Assert.Equal(OperationKind.None, operation.Kind); } public override void Visit(IOperation operation) { if (operation != null) { var syntax = operation.Syntax; var type = operation.Type; var constantValue = operation.ConstantValue; Assert.NotNull(syntax); // operation.Language can throw due to https://github.com/dotnet/roslyn/issues/23821 // Conditional logic below should be removed once the issue is fixed if (syntax is Microsoft.CodeAnalysis.Syntax.SyntaxList) { Assert.Equal(OperationKind.None, operation.Kind); Assert.Equal(LanguageNames.CSharp, operation.Parent.Language); } else { var language = operation.Language; } var isImplicit = operation.IsImplicit; foreach (IOperation child in operation.Children) { Assert.NotNull(child); } if (operation.SemanticModel != null) { Assert.Same(operation.SemanticModel, operation.SemanticModel.ContainingModelOrSelf); } } base.Visit(operation); } public override void VisitBlock(IBlockOperation operation) { Assert.Equal(OperationKind.Block, operation.Kind); VisitLocals(operation.Locals); AssertEx.Equal(operation.Operations, operation.Children); } public override void VisitVariableDeclarationGroup(IVariableDeclarationGroupOperation operation) { Assert.Equal(OperationKind.VariableDeclarationGroup, operation.Kind); AssertEx.Equal(operation.Declarations, operation.Children); } public override void VisitVariableDeclarator(IVariableDeclaratorOperation operation) { Assert.Equal(OperationKind.VariableDeclarator, operation.Kind); Assert.NotNull(operation.Symbol); IEnumerable<IOperation> children = operation.IgnoredArguments; var initializer = operation.Initializer; if (initializer != null) { children = children.Concat(new[] { initializer }); } AssertEx.Equal(children, operation.Children); } public override void VisitVariableDeclaration(IVariableDeclarationOperation operation) { Assert.Equal(OperationKind.VariableDeclaration, operation.Kind); IEnumerable<IOperation> children = operation.IgnoredDimensions.Concat(operation.Declarators); var initializer = operation.Initializer; if (initializer != null) { children = children.Concat(new[] { initializer }); } AssertEx.Equal(children, operation.Children); } public override void VisitSwitch(ISwitchOperation operation) { Assert.Equal(OperationKind.Switch, operation.Kind); VisitLocals(operation.Locals); Assert.NotNull(operation.ExitLabel); AssertEx.Equal(new[] { operation.Value }.Concat(operation.Cases), operation.Children); } public override void VisitSwitchCase(ISwitchCaseOperation operation) { Assert.Equal(OperationKind.SwitchCase, operation.Kind); VisitLocals(operation.Locals); AssertEx.Equal(operation.Clauses.Concat(operation.Body), operation.Children); VerifySubTree(((SwitchCaseOperation)operation).Condition, hasNonNullParent: true); } internal static void VerifySubTree(IOperation root, bool hasNonNullParent = false) { if (root != null) { if (hasNonNullParent) { // This is only ever true for ISwitchCaseOperation.Condition. Assert.NotNull(root.Parent); Assert.Same(root, ((SwitchCaseOperation)root.Parent).Condition); } else { Assert.Null(root.Parent); } var explicitNodeMap = new Dictionary<SyntaxNode, IOperation>(); foreach (IOperation descendant in root.DescendantsAndSelf()) { if (!descendant.IsImplicit) { try { explicitNodeMap.Add(descendant.Syntax, descendant); } catch (ArgumentException) { Assert.False(true, $"Duplicate explicit node for syntax ({descendant.Syntax.RawKind}): {descendant.Syntax.ToString()}"); } } Singleton.Visit(descendant); } } } public override void VisitSingleValueCaseClause(ISingleValueCaseClauseOperation operation) { VisitCaseClauseOperation(operation); Assert.Equal(CaseKind.SingleValue, operation.CaseKind); AssertEx.Equal(new[] { operation.Value }, operation.Children); } private static void VisitCaseClauseOperation(ICaseClauseOperation operation) { Assert.Equal(OperationKind.CaseClause, operation.Kind); _ = operation.Label; } public override void VisitRelationalCaseClause(IRelationalCaseClauseOperation operation) { VisitCaseClauseOperation(operation); Assert.Equal(CaseKind.Relational, operation.CaseKind); var relation = operation.Relation; AssertEx.Equal(new[] { operation.Value }, operation.Children); } public override void VisitDefaultCaseClause(IDefaultCaseClauseOperation operation) { VisitCaseClauseOperation(operation); Assert.Equal(CaseKind.Default, operation.CaseKind); Assert.Empty(operation.Children); } private static void VisitLocals(ImmutableArray<ILocalSymbol> locals) { foreach (var local in locals) { Assert.NotNull(local); } } public override void VisitWhileLoop(IWhileLoopOperation operation) { VisitLoop(operation); Assert.Equal(LoopKind.While, operation.LoopKind); var conditionIsTop = operation.ConditionIsTop; var conditionIsUntil = operation.ConditionIsUntil; IEnumerable<IOperation> children; if (conditionIsTop) { if (operation.IgnoredCondition != null) { children = new[] { operation.Condition, operation.Body, operation.IgnoredCondition }; } else { children = new[] { operation.Condition, operation.Body }; } } else { Assert.Null(operation.IgnoredCondition); if (operation.Condition != null) { children = new[] { operation.Body, operation.Condition }; } else { children = new[] { operation.Body }; } } AssertEx.Equal(children, operation.Children); } public override void VisitForLoop(IForLoopOperation operation) { VisitLoop(operation); Assert.Equal(LoopKind.For, operation.LoopKind); VisitLocals(operation.Locals); VisitLocals(operation.ConditionLocals); IEnumerable<IOperation> children = operation.Before; if (operation.Condition != null) { children = children.Concat(new[] { operation.Condition }); } children = children.Concat(new[] { operation.Body }); children = children.Concat(operation.AtLoopBottom); AssertEx.Equal(children, operation.Children); } public override void VisitForToLoop(IForToLoopOperation operation) { VisitLoop(operation); Assert.Equal(LoopKind.ForTo, operation.LoopKind); _ = operation.IsChecked; (ILocalSymbol loopObject, ForToLoopOperationUserDefinedInfo userDefinedInfo) = ((ForToLoopOperation)operation).Info; if (userDefinedInfo != null) { VerifySubTree(userDefinedInfo.Addition); VerifySubTree(userDefinedInfo.Subtraction); VerifySubTree(userDefinedInfo.LessThanOrEqual); VerifySubTree(userDefinedInfo.GreaterThanOrEqual); } IEnumerable<IOperation> children; children = new[] { operation.LoopControlVariable, operation.InitialValue, operation.LimitValue, operation.StepValue, operation.Body }; children = children.Concat(operation.NextVariables); AssertEx.Equal(children, operation.Children); } public override void VisitForEachLoop(IForEachLoopOperation operation) { VisitLoop(operation); Assert.Equal(LoopKind.ForEach, operation.LoopKind); IEnumerable<IOperation> children = new[] { operation.Collection, operation.LoopControlVariable, operation.Body }.Concat(operation.NextVariables); AssertEx.Equal(children, operation.Children); ForEachLoopOperationInfo info = ((ForEachLoopOperation)operation).Info; if (info != null) { visitArguments(info.GetEnumeratorArguments); visitArguments(info.MoveNextArguments); visitArguments(info.CurrentArguments); visitArguments(info.DisposeArguments); } void visitArguments(ImmutableArray<IArgumentOperation> arguments) { if (arguments != null) { foreach (IArgumentOperation arg in arguments) { VerifySubTree(arg); } } } } private static void VisitLoop(ILoopOperation operation) { Assert.Equal(OperationKind.Loop, operation.Kind); VisitLocals(operation.Locals); Assert.NotNull(operation.ContinueLabel); Assert.NotNull(operation.ExitLabel); } public override void VisitLabeled(ILabeledOperation operation) { Assert.Equal(OperationKind.Labeled, operation.Kind); Assert.NotNull(operation.Label); if (operation.Operation == null) { Assert.Empty(operation.Children); } else { Assert.Same(operation.Operation, operation.Children.Single()); } } public override void VisitBranch(IBranchOperation operation) { Assert.Equal(OperationKind.Branch, operation.Kind); Assert.NotNull(operation.Target); switch (operation.BranchKind) { case BranchKind.Break: case BranchKind.Continue: case BranchKind.GoTo: break; default: Assert.False(true); break; } Assert.Empty(operation.Children); } public override void VisitEmpty(IEmptyOperation operation) { Assert.Equal(OperationKind.Empty, operation.Kind); Assert.Empty(operation.Children); } public override void VisitReturn(IReturnOperation operation) { Assert.Contains(operation.Kind, new[] { OperationKind.Return, OperationKind.YieldReturn, OperationKind.YieldBreak }); if (operation.ReturnedValue == null) { Assert.NotEqual(OperationKind.YieldReturn, operation.Kind); Assert.Empty(operation.Children); } else { Assert.Same(operation.ReturnedValue, operation.Children.Single()); } } public override void VisitLock(ILockOperation operation) { Assert.Equal(OperationKind.Lock, operation.Kind); AssertEx.Equal(new[] { operation.LockedValue, operation.Body }, operation.Children); } public override void VisitTry(ITryOperation operation) { Assert.Equal(OperationKind.Try, operation.Kind); IEnumerable<IOperation> children = new[] { operation.Body }; _ = operation.ExitLabel; children = children.Concat(operation.Catches); if (operation.Finally != null) { children = children.Concat(new[] { operation.Finally }); } AssertEx.Equal(children, operation.Children); } public override void VisitCatchClause(ICatchClauseOperation operation) { Assert.Equal(OperationKind.CatchClause, operation.Kind); var exceptionType = operation.ExceptionType; VisitLocals(operation.Locals); IEnumerable<IOperation> children = Array.Empty<IOperation>(); if (operation.ExceptionDeclarationOrExpression != null) { children = children.Concat(new[] { operation.ExceptionDeclarationOrExpression }); } if (operation.Filter != null) { children = children.Concat(new[] { operation.Filter }); } children = children.Concat(new[] { operation.Handler }); AssertEx.Equal(children, operation.Children); } public override void VisitUsing(IUsingOperation operation) { Assert.Equal(OperationKind.Using, operation.Kind); VisitLocals(operation.Locals); AssertEx.Equal(new[] { operation.Resources, operation.Body }, operation.Children); Assert.NotEqual(OperationKind.VariableDeclaration, operation.Resources.Kind); Assert.NotEqual(OperationKind.VariableDeclarator, operation.Resources.Kind); _ = ((UsingOperation)operation).DisposeInfo.DisposeMethod; var disposeArgs = ((UsingOperation)operation).DisposeInfo.DisposeArguments; if (!disposeArgs.IsDefaultOrEmpty) { foreach (var arg in disposeArgs) { VerifySubTree(arg); } } } // https://github.com/dotnet/roslyn/issues/21281 internal override void VisitFixed(IFixedOperation operation) { Assert.Equal(OperationKind.None, operation.Kind); VisitLocals(operation.Locals); AssertEx.Equal(new[] { operation.Variables, operation.Body }, operation.Children); } internal override void VisitAggregateQuery(IAggregateQueryOperation operation) { Assert.Equal(OperationKind.None, operation.Kind); AssertEx.Equal(new[] { operation.Group, operation.Aggregation }, operation.Children); } public override void VisitExpressionStatement(IExpressionStatementOperation operation) { Assert.Equal(OperationKind.ExpressionStatement, operation.Kind); Assert.Same(operation.Operation, operation.Children.Single()); } internal override void VisitWithStatement(IWithStatementOperation operation) { Assert.Equal(OperationKind.None, operation.Kind); AssertEx.Equal(new[] { operation.Value, operation.Body }, operation.Children); } public override void VisitStop(IStopOperation operation) { Assert.Equal(OperationKind.Stop, operation.Kind); Assert.Empty(operation.Children); } public override void VisitEnd(IEndOperation operation) { Assert.Equal(OperationKind.End, operation.Kind); Assert.Empty(operation.Children); } public override void VisitInvocation(IInvocationOperation operation) { Assert.Equal(OperationKind.Invocation, operation.Kind); Assert.NotNull(operation.TargetMethod); var isVirtual = operation.IsVirtual; IEnumerable<IOperation> children; if (operation.Instance != null) { children = new[] { operation.Instance }.Concat(operation.Arguments); } else { children = operation.Arguments; } AssertEx.Equal(children, operation.Children); // Make sure that all static member references or invocations of static methods do not have implicit IInstanceReferenceOperations // as their receivers if (operation.TargetMethod.IsStatic && operation.Instance is IInstanceReferenceOperation) { Assert.False(operation.Instance.IsImplicit, $"Implicit {nameof(IInstanceReferenceOperation)} on {operation.Syntax}"); } } public override void VisitArgument(IArgumentOperation operation) { Assert.Equal(OperationKind.Argument, operation.Kind); Assert.Contains(operation.ArgumentKind, new[] { ArgumentKind.DefaultValue, ArgumentKind.Explicit, ArgumentKind.ParamArray }); var parameter = operation.Parameter; Assert.Same(operation.Value, operation.Children.Single()); var inConversion = operation.InConversion; var outConversion = operation.OutConversion; if (operation.ArgumentKind == ArgumentKind.DefaultValue) { Assert.True(operation.Descendants().All(n => n.IsImplicit), $"Explicit node in default argument value ({operation.Syntax.RawKind}): {operation.Syntax.ToString()}"); } } public override void VisitOmittedArgument(IOmittedArgumentOperation operation) { Assert.Equal(OperationKind.OmittedArgument, operation.Kind); Assert.Empty(operation.Children); } public override void VisitArrayElementReference(IArrayElementReferenceOperation operation) { Assert.Equal(OperationKind.ArrayElementReference, operation.Kind); AssertEx.Equal(new[] { operation.ArrayReference }.Concat(operation.Indices), operation.Children); } internal override void VisitPointerIndirectionReference(IPointerIndirectionReferenceOperation operation) { Assert.Equal(OperationKind.None, operation.Kind); Assert.Same(operation.Pointer, operation.Children.Single()); } public override void VisitLocalReference(ILocalReferenceOperation operation) { Assert.Equal(OperationKind.LocalReference, operation.Kind); Assert.NotNull(operation.Local); var isDeclaration = operation.IsDeclaration; Assert.Empty(operation.Children); } public override void VisitParameterReference(IParameterReferenceOperation operation) { Assert.Equal(OperationKind.ParameterReference, operation.Kind); Assert.NotNull(operation.Parameter); Assert.Empty(operation.Children); } public override void VisitInstanceReference(IInstanceReferenceOperation operation) { Assert.Equal(OperationKind.InstanceReference, operation.Kind); Assert.Empty(operation.Children); var referenceKind = operation.ReferenceKind; } private void VisitMemberReference(IMemberReferenceOperation operation) { VisitMemberReference(operation, Array.Empty<IOperation>()); } private void VisitMemberReference(IMemberReferenceOperation operation, IEnumerable<IOperation> additionalChildren) { Assert.NotNull(operation.Member); IEnumerable<IOperation> children; if (operation.Instance != null) { children = new[] { operation.Instance }.Concat(additionalChildren); // Make sure that all static member references or invocations of static methods do not have implicit IInstanceReferenceOperations // as their receivers if (operation.Member.IsStatic && operation.Instance is IInstanceReferenceOperation) { Assert.False(operation.Instance.IsImplicit, $"Implicit {nameof(IInstanceReferenceOperation)} on {operation.Syntax}"); } } else { children = additionalChildren; } AssertEx.Equal(children, operation.Children); } public override void VisitFieldReference(IFieldReferenceOperation operation) { Assert.Equal(OperationKind.FieldReference, operation.Kind); VisitMemberReference(operation); Assert.Same(operation.Member, operation.Field); var isDeclaration = operation.IsDeclaration; } public override void VisitMethodReference(IMethodReferenceOperation operation) { Assert.Equal(OperationKind.MethodReference, operation.Kind); VisitMemberReference(operation); Assert.Same(operation.Member, operation.Method); var isVirtual = operation.IsVirtual; } public override void VisitPropertyReference(IPropertyReferenceOperation operation) { Assert.Equal(OperationKind.PropertyReference, operation.Kind); VisitMemberReference(operation, operation.Arguments); Assert.Same(operation.Member, operation.Property); } public override void VisitEventReference(IEventReferenceOperation operation) { Assert.Equal(OperationKind.EventReference, operation.Kind); VisitMemberReference(operation); Assert.Same(operation.Member, operation.Event); } public override void VisitEventAssignment(IEventAssignmentOperation operation) { Assert.Equal(OperationKind.EventAssignment, operation.Kind); var adds = operation.Adds; AssertEx.Equal(new[] { operation.EventReference, operation.HandlerValue }, operation.Children); } public override void VisitConditionalAccess(IConditionalAccessOperation operation) { Assert.Equal(OperationKind.ConditionalAccess, operation.Kind); Assert.NotNull(operation.Type); AssertEx.Equal(new[] { operation.Operation, operation.WhenNotNull }, operation.Children); } public override void VisitConditionalAccessInstance(IConditionalAccessInstanceOperation operation) { Assert.Equal(OperationKind.ConditionalAccessInstance, operation.Kind); Assert.Empty(operation.Children); } internal override void VisitPlaceholder(IPlaceholderOperation operation) { Assert.Equal(OperationKind.None, operation.Kind); Assert.Empty(operation.Children); } public override void VisitUnaryOperator(IUnaryOperation operation) { Assert.Equal(OperationKind.UnaryOperator, operation.Kind); Assert.Equal(OperationKind.Unary, operation.Kind); var operatorMethod = operation.OperatorMethod; var unaryOperationKind = operation.OperatorKind; var isLifted = operation.IsLifted; var isChecked = operation.IsChecked; Assert.Same(operation.Operand, operation.Children.Single()); } public override void VisitBinaryOperator(IBinaryOperation operation) { Assert.Equal(OperationKind.BinaryOperator, operation.Kind); Assert.Equal(OperationKind.Binary, operation.Kind); var operatorMethod = operation.OperatorMethod; var unaryOperatorMethod = ((BinaryOperation)operation).UnaryOperatorMethod; var binaryOperationKind = operation.OperatorKind; var isLifted = operation.IsLifted; var isChecked = operation.IsChecked; var isCompareText = operation.IsCompareText; AssertEx.Equal(new[] { operation.LeftOperand, operation.RightOperand }, operation.Children); } public override void VisitTupleBinaryOperator(ITupleBinaryOperation operation) { Assert.Equal(OperationKind.TupleBinaryOperator, operation.Kind); Assert.Equal(OperationKind.TupleBinary, operation.Kind); var binaryOperationKind = operation.OperatorKind; AssertEx.Equal(new[] { operation.LeftOperand, operation.RightOperand }, operation.Children); } public override void VisitConversion(IConversionOperation operation) { Assert.Equal(OperationKind.Conversion, operation.Kind); var operatorMethod = operation.OperatorMethod; var conversion = operation.Conversion; var isChecked = operation.IsChecked; var isTryCast = operation.IsTryCast; switch (operation.Language) { case LanguageNames.CSharp: CSharp.Conversion csharpConversion = CSharp.CSharpExtensions.GetConversion(operation); Assert.Throws<ArgumentException>(() => VisualBasic.VisualBasicExtensions.GetConversion(operation)); break; case LanguageNames.VisualBasic: VisualBasic.Conversion visualBasicConversion = VisualBasic.VisualBasicExtensions.GetConversion(operation); Assert.Throws<ArgumentException>(() => CSharp.CSharpExtensions.GetConversion(operation)); break; default: Debug.Fail($"Language {operation.Language} is unknown!"); break; } Assert.Same(operation.Operand, operation.Children.Single()); } public override void VisitConditional(IConditionalOperation operation) { Assert.Equal(OperationKind.Conditional, operation.Kind); bool isRef = operation.IsRef; if (operation.WhenFalse != null) { AssertEx.Equal(new[] { operation.Condition, operation.WhenTrue, operation.WhenFalse }, operation.Children); } else { AssertEx.Equal(new[] { operation.Condition, operation.WhenTrue }, operation.Children); } } public override void VisitCoalesce(ICoalesceOperation operation) { Assert.Equal(OperationKind.Coalesce, operation.Kind); AssertEx.Equal(new[] { operation.Value, operation.WhenNull }, operation.Children); var valueConversion = operation.ValueConversion; } public override void VisitCoalesceAssignment(ICoalesceAssignmentOperation operation) { Assert.Equal(OperationKind.CoalesceAssignment, operation.Kind); AssertEx.Equal(new[] { operation.Target, operation.Value }, operation.Children); } public override void VisitIsType(IIsTypeOperation operation) { Assert.Equal(OperationKind.IsType, operation.Kind); Assert.NotNull(operation.TypeOperand); bool isNegated = operation.IsNegated; Assert.Same(operation.ValueOperand, operation.Children.Single()); } public override void VisitSizeOf(ISizeOfOperation operation) { Assert.Equal(OperationKind.SizeOf, operation.Kind); Assert.NotNull(operation.TypeOperand); Assert.Empty(operation.Children); } public override void VisitTypeOf(ITypeOfOperation operation) { Assert.Equal(OperationKind.TypeOf, operation.Kind); Assert.NotNull(operation.TypeOperand); Assert.Empty(operation.Children); } public override void VisitAnonymousFunction(IAnonymousFunctionOperation operation) { Assert.Equal(OperationKind.AnonymousFunction, operation.Kind); Assert.NotNull(operation.Symbol); Assert.Same(operation.Body, operation.Children.Single()); } public override void VisitFlowAnonymousFunction(IFlowAnonymousFunctionOperation operation) { Assert.Equal(OperationKind.FlowAnonymousFunction, operation.Kind); Assert.NotNull(operation.Symbol); Assert.Empty(operation.Children); } public override void VisitLocalFunction(ILocalFunctionOperation operation) { Assert.Equal(OperationKind.LocalFunction, operation.Kind); Assert.NotNull(operation.Symbol); if (operation.Body != null) { var children = operation.Children.ToImmutableArray(); Assert.Same(operation.Body, children[0]); if (operation.IgnoredBody != null) { Assert.Same(operation.IgnoredBody, children[1]); Assert.Equal(2, children.Length); } else { Assert.Equal(1, children.Length); } } else { Assert.Null(operation.IgnoredBody); Assert.Empty(operation.Children); } } public override void VisitLiteral(ILiteralOperation operation) { Assert.Equal(OperationKind.Literal, operation.Kind); Assert.Empty(operation.Children); } public override void VisitAwait(IAwaitOperation operation) { Assert.Equal(OperationKind.Await, operation.Kind); Assert.Same(operation.Operation, operation.Children.Single()); } public override void VisitNameOf(INameOfOperation operation) { Assert.Equal(OperationKind.NameOf, operation.Kind); Assert.Same(operation.Argument, operation.Children.Single()); } public override void VisitThrow(IThrowOperation operation) { Assert.Equal(OperationKind.Throw, operation.Kind); if (operation.Exception == null) { Assert.Empty(operation.Children); } else { Assert.Same(operation.Exception, operation.Children.Single()); } } public override void VisitAddressOf(IAddressOfOperation operation) { Assert.Equal(OperationKind.AddressOf, operation.Kind); Assert.Same(operation.Reference, operation.Children.Single()); } public override void VisitObjectCreation(IObjectCreationOperation operation) { Assert.Equal(OperationKind.ObjectCreation, operation.Kind); var constructor = operation.Constructor; // When parameter-less struct constructor is inaccessible, the constructor symbol is null if (!operation.Type.IsValueType) { Assert.NotNull(constructor); if (constructor == null) { Assert.Empty(operation.Arguments); } } IEnumerable<IOperation> children = operation.Arguments; if (operation.Initializer != null) { children = children.Concat(new[] { operation.Initializer }); } AssertEx.Equal(children, operation.Children); } public override void VisitAnonymousObjectCreation(IAnonymousObjectCreationOperation operation) { Assert.Equal(OperationKind.AnonymousObjectCreation, operation.Kind); AssertEx.Equal(operation.Initializers, operation.Children); foreach (var initializer in operation.Initializers) { var simpleAssignment = (ISimpleAssignmentOperation)initializer; var propertyReference = (IPropertyReferenceOperation)simpleAssignment.Target; Assert.Empty(propertyReference.Arguments); Assert.Equal(OperationKind.InstanceReference, propertyReference.Instance.Kind); Assert.Equal(InstanceReferenceKind.ImplicitReceiver, ((IInstanceReferenceOperation)propertyReference.Instance).ReferenceKind); } } public override void VisitDynamicObjectCreation(IDynamicObjectCreationOperation operation) { Assert.Equal(OperationKind.DynamicObjectCreation, operation.Kind); IEnumerable<IOperation> children = operation.Arguments; if (operation.Initializer != null) { children = children.Concat(new[] { operation.Initializer }); } AssertEx.Equal(children, operation.Children); } public override void VisitDynamicInvocation(IDynamicInvocationOperation operation) { Assert.Equal(OperationKind.DynamicInvocation, operation.Kind); AssertEx.Equal(new[] { operation.Operation }.Concat(operation.Arguments), operation.Children); } public override void VisitDynamicIndexerAccess(IDynamicIndexerAccessOperation operation) { Assert.Equal(OperationKind.DynamicIndexerAccess, operation.Kind); AssertEx.Equal(new[] { operation.Operation }.Concat(operation.Arguments), operation.Children); } public override void VisitObjectOrCollectionInitializer(IObjectOrCollectionInitializerOperation operation) { Assert.Equal(OperationKind.ObjectOrCollectionInitializer, operation.Kind); AssertEx.Equal(operation.Initializers, operation.Children); } public override void VisitMemberInitializer(IMemberInitializerOperation operation) { Assert.Equal(OperationKind.MemberInitializer, operation.Kind); AssertEx.Equal(new[] { operation.InitializedMember, operation.Initializer }, operation.Children); } private void VisitSymbolInitializer(ISymbolInitializerOperation operation) { VisitLocals(operation.Locals); Assert.Same(operation.Value, operation.Children.Single()); } public override void VisitFieldInitializer(IFieldInitializerOperation operation) { Assert.Equal(OperationKind.FieldInitializer, operation.Kind); foreach (var field in operation.InitializedFields) { Assert.NotNull(field); } VisitSymbolInitializer(operation); } public override void VisitVariableInitializer(IVariableInitializerOperation operation) { Assert.Equal(OperationKind.VariableInitializer, operation.Kind); Assert.Empty(operation.Locals); VisitSymbolInitializer(operation); } public override void VisitPropertyInitializer(IPropertyInitializerOperation operation) { Assert.Equal(OperationKind.PropertyInitializer, operation.Kind); foreach (var property in operation.InitializedProperties) { Assert.NotNull(property); } VisitSymbolInitializer(operation); } public override void VisitParameterInitializer(IParameterInitializerOperation operation) { Assert.Equal(OperationKind.ParameterInitializer, operation.Kind); Assert.NotNull(operation.Parameter); VisitSymbolInitializer(operation); } public override void VisitArrayCreation(IArrayCreationOperation operation) { Assert.Equal(OperationKind.ArrayCreation, operation.Kind); IEnumerable<IOperation> children = operation.DimensionSizes; if (operation.Initializer != null) { children = children.Concat(new[] { operation.Initializer }); } AssertEx.Equal(children, operation.Children); } public override void VisitArrayInitializer(IArrayInitializerOperation operation) { Assert.Equal(OperationKind.ArrayInitializer, operation.Kind); Assert.Null(operation.Type); AssertEx.Equal(operation.ElementValues, operation.Children); } private void VisitAssignment(IAssignmentOperation operation) { AssertEx.Equal(new[] { operation.Target, operation.Value }, operation.Children); } public override void VisitSimpleAssignment(ISimpleAssignmentOperation operation) { Assert.Equal(OperationKind.SimpleAssignment, operation.Kind); bool isRef = operation.IsRef; VisitAssignment(operation); } public override void VisitCompoundAssignment(ICompoundAssignmentOperation operation) { Assert.Equal(OperationKind.CompoundAssignment, operation.Kind); var operatorMethod = operation.OperatorMethod; var binaryOperationKind = operation.OperatorKind; var inConversion = operation.InConversion; var outConversion = operation.OutConversion; if (operation.Syntax.Language == LanguageNames.CSharp) { Assert.Throws<ArgumentException>("compoundAssignment", () => VisualBasic.VisualBasicExtensions.GetInConversion(operation)); Assert.Throws<ArgumentException>("compoundAssignment", () => VisualBasic.VisualBasicExtensions.GetOutConversion(operation)); var inConversionInternal = CSharp.CSharpExtensions.GetInConversion(operation); var outConversionInternal = CSharp.CSharpExtensions.GetOutConversion(operation); } else { Assert.Throws<ArgumentException>("compoundAssignment", () => CSharp.CSharpExtensions.GetInConversion(operation)); Assert.Throws<ArgumentException>("compoundAssignment", () => CSharp.CSharpExtensions.GetOutConversion(operation)); var inConversionInternal = VisualBasic.VisualBasicExtensions.GetInConversion(operation); var outConversionInternal = VisualBasic.VisualBasicExtensions.GetOutConversion(operation); } var isLifted = operation.IsLifted; var isChecked = operation.IsChecked; VisitAssignment(operation); } public override void VisitIncrementOrDecrement(IIncrementOrDecrementOperation operation) { Assert.Contains(operation.Kind, new[] { OperationKind.Increment, OperationKind.Decrement }); var operatorMethod = operation.OperatorMethod; var isPostFix = operation.IsPostfix; var isLifted = operation.IsLifted; var isChecked = operation.IsChecked; Assert.Same(operation.Target, operation.Children.Single()); } public override void VisitParenthesized(IParenthesizedOperation operation) { Assert.Equal(OperationKind.Parenthesized, operation.Kind); Assert.Same(operation.Operand, operation.Children.Single()); } public override void VisitDynamicMemberReference(IDynamicMemberReferenceOperation operation) { Assert.Equal(OperationKind.DynamicMemberReference, operation.Kind); Assert.NotNull(operation.MemberName); foreach (var typeArg in operation.TypeArguments) { Assert.NotNull(typeArg); } var containingType = operation.ContainingType; if (operation.Instance == null) { Assert.Empty(operation.Children); } else { Assert.Same(operation.Instance, operation.Children.Single()); } } public override void VisitDefaultValue(IDefaultValueOperation operation) { Assert.Equal(OperationKind.DefaultValue, operation.Kind); Assert.Empty(operation.Children); } public override void VisitTypeParameterObjectCreation(ITypeParameterObjectCreationOperation operation) { Assert.Equal(OperationKind.TypeParameterObjectCreation, operation.Kind); if (operation.Initializer == null) { Assert.Empty(operation.Children); } else { Assert.Same(operation.Initializer, operation.Children.Single()); } } internal override void VisitNoPiaObjectCreation(INoPiaObjectCreationOperation operation) { Assert.Equal(OperationKind.None, operation.Kind); if (operation.Initializer == null) { Assert.Empty(operation.Children); } else { Assert.Same(operation.Initializer, operation.Children.Single()); } } public override void VisitInvalid(IInvalidOperation operation) { Assert.Equal(OperationKind.Invalid, operation.Kind); } public override void VisitTuple(ITupleOperation operation) { Assert.Equal(OperationKind.Tuple, operation.Kind); var naturalType = operation.NaturalType; AssertEx.Equal(operation.Elements, operation.Children); } public override void VisitInterpolatedString(IInterpolatedStringOperation operation) { Assert.Equal(OperationKind.InterpolatedString, operation.Kind); AssertEx.Equal(operation.Parts, operation.Children); } public override void VisitInterpolatedStringText(IInterpolatedStringTextOperation operation) { Assert.Equal(OperationKind.InterpolatedStringText, operation.Kind); if (operation.Text.Kind != OperationKind.Literal) { Assert.Equal(OperationKind.Literal, ((IConversionOperation)operation.Text).Operand.Kind); } Assert.Same(operation.Text, operation.Children.Single()); } public override void VisitInterpolation(IInterpolationOperation operation) { Assert.Equal(OperationKind.Interpolation, operation.Kind); IEnumerable<IOperation> children = new[] { operation.Expression }; if (operation.Alignment != null) { children = children.Concat(new[] { operation.Alignment }); } if (operation.FormatString != null) { if (operation.FormatString.Kind != OperationKind.Literal) { Assert.Equal(OperationKind.Literal, ((IConversionOperation)operation.FormatString).Operand.Kind); } children = children.Concat(new[] { operation.FormatString }); } AssertEx.Equal(children, operation.Children); } private void VisitPatternCommon(IPatternOperation pattern) { Assert.NotNull(pattern.InputType); Assert.NotNull(pattern.NarrowedType); Assert.Null(pattern.Type); Assert.False(pattern.ConstantValue.HasValue); } public override void VisitConstantPattern(IConstantPatternOperation operation) { Assert.Equal(OperationKind.ConstantPattern, operation.Kind); VisitPatternCommon(operation); Assert.Same(operation.Value, operation.Children.Single()); } public override void VisitRelationalPattern(IRelationalPatternOperation operation) { Assert.Equal(OperationKind.RelationalPattern, operation.Kind); Assert.True(operation.OperatorKind is Operations.BinaryOperatorKind.LessThan or Operations.BinaryOperatorKind.LessThanOrEqual or Operations.BinaryOperatorKind.GreaterThan or Operations.BinaryOperatorKind.GreaterThanOrEqual or Operations.BinaryOperatorKind.Equals or // Error cases Operations.BinaryOperatorKind.NotEquals); VisitPatternCommon(operation); Assert.Same(operation.Value, operation.Children.Single()); } public override void VisitBinaryPattern(IBinaryPatternOperation operation) { Assert.Equal(OperationKind.BinaryPattern, operation.Kind); VisitPatternCommon(operation); Assert.True(operation.OperatorKind switch { Operations.BinaryOperatorKind.Or => true, Operations.BinaryOperatorKind.And => true, _ => false }); var children = operation.Children.ToArray(); Assert.Equal(2, children.Length); Assert.Same(operation.LeftPattern, children[0]); Assert.Same(operation.RightPattern, children[1]); } public override void VisitNegatedPattern(INegatedPatternOperation operation) { Assert.Equal(OperationKind.NegatedPattern, operation.Kind); VisitPatternCommon(operation); Assert.Same(operation.Pattern, operation.Children.Single()); } public override void VisitTypePattern(ITypePatternOperation operation) { Assert.Equal(OperationKind.TypePattern, operation.Kind); Assert.NotNull(operation.MatchedType); VisitPatternCommon(operation); Assert.Empty(operation.Children); } public override void VisitDeclarationPattern(IDeclarationPatternOperation operation) { Assert.Equal(OperationKind.DeclarationPattern, operation.Kind); VisitPatternCommon(operation); if (operation.Syntax.IsKind(CSharp.SyntaxKind.VarPattern) || // in `var (x, y)`, the syntax here is the designation `x`. operation.Syntax.IsKind(CSharp.SyntaxKind.SingleVariableDesignation)) { Assert.True(operation.MatchesNull); Assert.Null(operation.MatchedType); } else { Assert.False(operation.MatchesNull); Assert.NotNull(operation.MatchedType); } var designation = (operation.Syntax as CSharp.Syntax.DeclarationPatternSyntax)?.Designation ?? (operation.Syntax as CSharp.Syntax.VarPatternSyntax)?.Designation ?? (operation.Syntax as CSharp.Syntax.VariableDesignationSyntax); if (designation.IsKind(CSharp.SyntaxKind.SingleVariableDesignation)) { Assert.NotNull(operation.DeclaredSymbol); } else { Assert.Null(operation.DeclaredSymbol); } Assert.Empty(operation.Children); } public override void VisitRecursivePattern(IRecursivePatternOperation operation) { Assert.Equal(OperationKind.RecursivePattern, operation.Kind); VisitPatternCommon(operation); Assert.NotNull(operation.MatchedType); switch (operation.DeconstructSymbol) { case IErrorTypeSymbol error: case null: // OK: indicates deconstruction of a tuple, or an error case break; case IMethodSymbol method: // when we have a method, it is a `Deconstruct` method Assert.Equal("Deconstruct", method.Name); break; case ITypeSymbol type: // when we have a type, it is the type "ITuple" Assert.Equal("ITuple", type.Name); break; default: Assert.True(false, $"Unexpected symbol {operation.DeconstructSymbol}"); break; } var designation = (operation.Syntax as CSharp.Syntax.RecursivePatternSyntax)?.Designation; if (designation.IsKind(CSharp.SyntaxKind.SingleVariableDesignation)) { Assert.NotNull(operation.DeclaredSymbol); } else { Assert.Null(operation.DeclaredSymbol); } foreach (var subpat in operation.PropertySubpatterns) { Assert.True(subpat is IPropertySubpatternOperation); } IEnumerable<IOperation> children = operation.DeconstructionSubpatterns.Cast<IOperation>(); children = children.Concat(operation.PropertySubpatterns); AssertEx.Equal(children, operation.Children); } public override void VisitPropertySubpattern(IPropertySubpatternOperation operation) { Assert.NotNull(operation.Pattern); var children = new IOperation[] { operation.Member, operation.Pattern }; AssertEx.Equal(children, operation.Children); if (operation.Member.Kind == OperationKind.Invalid) { return; } Assert.True(operation.Member is IMemberReferenceOperation); var member = (IMemberReferenceOperation)operation.Member; switch (member.Member) { case IFieldSymbol field: case IPropertySymbol prop: break; case var symbol: Assert.True(false, $"Unexpected symbol {symbol}"); break; } } public override void VisitSwitchExpression(ISwitchExpressionOperation operation) { //force the existence of IsExhaustive _ = operation.IsExhaustive; Assert.NotNull(operation.Type); Assert.False(operation.ConstantValue.HasValue); Assert.Equal(OperationKind.SwitchExpression, operation.Kind); Assert.NotNull(operation.Value); var children = operation.Arms.Cast<IOperation>().Prepend(operation.Value); AssertEx.Equal(children, operation.Children); } public override void VisitSwitchExpressionArm(ISwitchExpressionArmOperation operation) { Assert.Null(operation.Type); Assert.False(operation.ConstantValue.HasValue); Assert.NotNull(operation.Pattern); _ = operation.Guard; Assert.NotNull(operation.Value); VisitLocals(operation.Locals); var children = operation.Guard == null ? new[] { operation.Pattern, operation.Value } : new[] { operation.Pattern, operation.Guard, operation.Value }; AssertEx.Equal(children, operation.Children); } public override void VisitIsPattern(IIsPatternOperation operation) { Assert.Equal(OperationKind.IsPattern, operation.Kind); AssertEx.Equal(new[] { operation.Value, operation.Pattern }, operation.Children); } public override void VisitPatternCaseClause(IPatternCaseClauseOperation operation) { VisitCaseClauseOperation(operation); Assert.Equal(CaseKind.Pattern, operation.CaseKind); Assert.Same(((ICaseClauseOperation)operation).Label, operation.Label); if (operation.Guard != null) { AssertEx.Equal(new[] { operation.Pattern, operation.Guard }, operation.Children); } else { Assert.Same(operation.Pattern, operation.Children.Single()); } } public override void VisitTranslatedQuery(ITranslatedQueryOperation operation) { Assert.Equal(OperationKind.TranslatedQuery, operation.Kind); Assert.Same(operation.Operation, operation.Children.Single()); } public override void VisitDeclarationExpression(IDeclarationExpressionOperation operation) { Assert.Equal(OperationKind.DeclarationExpression, operation.Kind); Assert.Same(operation.Expression, operation.Children.Single()); } public override void VisitDeconstructionAssignment(IDeconstructionAssignmentOperation operation) { Assert.Equal(OperationKind.DeconstructionAssignment, operation.Kind); VisitAssignment(operation); } public override void VisitDelegateCreation(IDelegateCreationOperation operation) { Assert.Equal(OperationKind.DelegateCreation, operation.Kind); Assert.Same(operation.Target, operation.Children.Single()); } public override void VisitRaiseEvent(IRaiseEventOperation operation) { Assert.Equal(OperationKind.RaiseEvent, operation.Kind); AssertEx.Equal(new IOperation[] { operation.EventReference }.Concat(operation.Arguments), operation.Children); } public override void VisitRangeCaseClause(IRangeCaseClauseOperation operation) { VisitCaseClauseOperation(operation); Assert.Equal(CaseKind.Range, operation.CaseKind); AssertEx.Equal(new[] { operation.MinimumValue, operation.MaximumValue }, operation.Children); } public override void VisitConstructorBodyOperation(IConstructorBodyOperation operation) { Assert.Equal(OperationKind.ConstructorBodyOperation, operation.Kind); Assert.Equal(OperationKind.ConstructorBody, operation.Kind); VisitLocals(operation.Locals); var builder = ArrayBuilder<IOperation>.GetInstance(); if (operation.Initializer != null) { builder.Add(operation.Initializer); } if (operation.BlockBody != null) { builder.Add(operation.BlockBody); } if (operation.ExpressionBody != null) { builder.Add(operation.ExpressionBody); } AssertEx.Equal(builder, operation.Children); builder.Free(); } public override void VisitMethodBodyOperation(IMethodBodyOperation operation) { Assert.Equal(OperationKind.MethodBodyOperation, operation.Kind); Assert.Equal(OperationKind.MethodBody, operation.Kind); if (operation.BlockBody != null) { if (operation.ExpressionBody != null) { AssertEx.Equal(new[] { operation.BlockBody, operation.ExpressionBody }, operation.Children); } else { Assert.Same(operation.BlockBody, operation.Children.Single()); } } else if (operation.ExpressionBody != null) { Assert.Same(operation.ExpressionBody, operation.Children.Single()); } else { Assert.Empty(operation.Children); } } public override void VisitDiscardOperation(IDiscardOperation operation) { Assert.Equal(OperationKind.Discard, operation.Kind); Assert.Empty(operation.Children); var discardSymbol = operation.DiscardSymbol; Assert.Equal(operation.Type, discardSymbol.Type); } public override void VisitDiscardPattern(IDiscardPatternOperation operation) { Assert.Equal(OperationKind.DiscardPattern, operation.Kind); VisitPatternCommon(operation); Assert.Empty(operation.Children); } public override void VisitFlowCapture(IFlowCaptureOperation operation) { Assert.Equal(OperationKind.FlowCapture, operation.Kind); Assert.True(operation.IsImplicit); Assert.Same(operation.Value, operation.Children.Single()); switch (operation.Value.Kind) { case OperationKind.Invalid: case OperationKind.None: case OperationKind.AnonymousFunction: case OperationKind.FlowCaptureReference: case OperationKind.DefaultValue: case OperationKind.FlowAnonymousFunction: // must be an error case like in Microsoft.CodeAnalysis.CSharp.UnitTests.ConditionalOperatorTests.TestBothUntyped unit-test break; case OperationKind.OmittedArgument: case OperationKind.DeclarationExpression: case OperationKind.Discard: Assert.False(true, $"A {operation.Value.Kind} node should not be spilled or captured."); break; default: // Only values can be spilled/captured if (!operation.Value.ConstantValue.HasValue || operation.Value.ConstantValue.Value != null) { Assert.NotNull(operation.Value.Type); } break; } } public override void VisitFlowCaptureReference(IFlowCaptureReferenceOperation operation) { Assert.Equal(OperationKind.FlowCaptureReference, operation.Kind); Assert.True(operation.IsImplicit); Assert.Empty(operation.Children); } public override void VisitIsNull(IIsNullOperation operation) { Assert.Equal(OperationKind.IsNull, operation.Kind); Assert.True(operation.IsImplicit); Assert.Same(operation.Operand, operation.Children.Single()); } public override void VisitCaughtException(ICaughtExceptionOperation operation) { Assert.Equal(OperationKind.CaughtException, operation.Kind); Assert.True(operation.IsImplicit); Assert.Empty(operation.Children); } public override void VisitStaticLocalInitializationSemaphore(IStaticLocalInitializationSemaphoreOperation operation) { Assert.Equal(OperationKind.StaticLocalInitializationSemaphore, operation.Kind); Assert.True(operation.IsImplicit); Assert.Empty(operation.Children); Assert.NotNull(operation.Local); Assert.True(operation.Local.IsStatic); } public override void VisitRangeOperation(IRangeOperation operation) { Assert.Equal(OperationKind.Range, operation.Kind); IOperation[] children = operation.Children.ToArray(); int index = 0; if (operation.LeftOperand != null) { Assert.Same(operation.LeftOperand, children[index++]); } if (operation.RightOperand != null) { Assert.Same(operation.RightOperand, children[index++]); } Assert.Equal(index, children.Length); } public override void VisitReDim(IReDimOperation operation) { Assert.Equal(OperationKind.ReDim, operation.Kind); AssertEx.Equal(operation.Clauses, operation.Children); var preserve = operation.Preserve; } public override void VisitReDimClause(IReDimClauseOperation operation) { Assert.Equal(OperationKind.ReDimClause, operation.Kind); AssertEx.Equal(SpecializedCollections.SingletonEnumerable(operation.Operand).Concat(operation.DimensionSizes), operation.Children); } public override void VisitUsingDeclaration(IUsingDeclarationOperation operation) { Assert.NotNull(operation.DeclarationGroup); AssertEx.Equal(SpecializedCollections.SingletonEnumerable(operation.DeclarationGroup), operation.Children); Assert.True(operation.DeclarationGroup.IsImplicit); Assert.Null(operation.Type); Assert.False(operation.ConstantValue.HasValue); _ = operation.IsAsynchronous; _ = operation.IsImplicit; _ = ((UsingDeclarationOperation)operation).DisposeInfo.DisposeMethod; var disposeArgs = ((UsingDeclarationOperation)operation).DisposeInfo.DisposeArguments; if (!disposeArgs.IsDefaultOrEmpty) { foreach (var arg in disposeArgs) { VerifySubTree(arg); } } } public override void VisitWith(IWithOperation operation) { Assert.Equal(OperationKind.With, operation.Kind); _ = operation.CloneMethod; IEnumerable<IOperation> children = SpecializedCollections.SingletonEnumerable(operation.Operand).Concat(operation.Initializer); AssertEx.Equal(children, operation.Children); } } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/Completion/CompletionProviders/SnippetCompletionProvider.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.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Snippets; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportCompletionProvider(nameof(SnippetCompletionProvider), LanguageNames.CSharp)] [ExtensionOrder(After = nameof(CrefCompletionProvider))] [Shared] internal sealed class SnippetCompletionProvider : LSPCompletionProvider { internal override bool IsSnippetProvider => true; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public SnippetCompletionProvider() { } public override bool IsInsertionTrigger(SourceText text, int characterPosition, OptionSet options) => CompletionUtilities.IsTriggerCharacter(text, characterPosition, options); public override ImmutableHashSet<char> TriggerCharacters { get; } = CompletionUtilities.CommonTriggerCharacters; public override async Task ProvideCompletionsAsync(CompletionContext context) { try { var document = context.Document; var position = context.Position; var options = context.Options; var cancellationToken = context.CancellationToken; using (Logger.LogBlock(FunctionId.Completion_SnippetCompletionProvider_GetItemsWorker_CSharp, cancellationToken)) { // TODO (https://github.com/dotnet/roslyn/issues/5107): Enable in Interactive. var workspace = document.Project.Solution.Workspace; if (!workspace.CanApplyChange(ApplyChangesKind.ChangeDocument) || workspace.Kind == WorkspaceKind.Debugger || workspace.Kind == WorkspaceKind.Interactive) { return; } context.AddItems(await document.GetUnionItemsFromDocumentAndLinkedDocumentsAsync( UnionCompletionItemComparer.Instance, d => GetSnippetsForDocumentAsync(d, position, cancellationToken)).ConfigureAwait(false)); } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e)) { // nop } } private static async Task<ImmutableArray<CompletionItem>> GetSnippetsForDocumentAsync( Document document, int position, CancellationToken cancellationToken) { var syntaxTree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var semanticFacts = document.GetRequiredLanguageService<ISemanticFactsService>(); var leftToken = syntaxTree.GetRoot(cancellationToken).FindTokenOnLeftOfPosition(position, includeDirectives: true); var targetToken = leftToken.GetPreviousTokenIfTouchingWord(position); if (syntaxFacts.IsInNonUserCode(syntaxTree, position, cancellationToken) || syntaxTree.IsRightOfDotOrArrowOrColonColon(position, targetToken, cancellationToken) || syntaxFacts.GetContainingTypeDeclaration(await syntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false), position) is EnumDeclarationSyntax) { return ImmutableArray<CompletionItem>.Empty; } var isPossibleTupleContext = syntaxFacts.IsPossibleTupleContext(syntaxTree, position, cancellationToken); if (syntaxFacts.IsPreProcessorDirectiveContext(syntaxTree, position, cancellationToken)) { var directive = leftToken.GetAncestor<DirectiveTriviaSyntax>(); Contract.ThrowIfNull(directive); if (!directive.DirectiveNameToken.IsKind( SyntaxKind.IfKeyword, SyntaxKind.RegionKeyword, SyntaxKind.ElseKeyword, SyntaxKind.ElifKeyword, SyntaxKind.ErrorKeyword, SyntaxKind.LineKeyword, SyntaxKind.PragmaKeyword, SyntaxKind.EndIfKeyword, SyntaxKind.UndefKeyword, SyntaxKind.EndRegionKeyword, SyntaxKind.WarningKeyword)) { var semanticModel = await document.ReuseExistingSpeculativeModelAsync(position, cancellationToken).ConfigureAwait(false); return GetSnippetCompletionItems( document.Project.Solution.Workspace, semanticModel, isPreProcessorContext: true, isTupleContext: isPossibleTupleContext, cancellationToken: cancellationToken); } } else { var semanticModel = await document.ReuseExistingSpeculativeModelAsync(position, cancellationToken).ConfigureAwait(false); if (semanticFacts.IsGlobalStatementContext(semanticModel, position, cancellationToken) || semanticFacts.IsExpressionContext(semanticModel, position, cancellationToken) || semanticFacts.IsStatementContext(semanticModel, position, cancellationToken) || semanticFacts.IsTypeContext(semanticModel, position, cancellationToken) || semanticFacts.IsTypeDeclarationContext(semanticModel, position, cancellationToken) || semanticFacts.IsNamespaceContext(semanticModel, position, cancellationToken) || semanticFacts.IsNamespaceDeclarationNameContext(semanticModel, position, cancellationToken) || semanticFacts.IsMemberDeclarationContext(semanticModel, position, cancellationToken) || semanticFacts.IsLabelContext(semanticModel, position, cancellationToken)) { return GetSnippetCompletionItems( document.Project.Solution.Workspace, semanticModel, isPreProcessorContext: false, isTupleContext: isPossibleTupleContext, cancellationToken: cancellationToken); } } return ImmutableArray<CompletionItem>.Empty; } private static readonly CompletionItemRules s_tupleRules = CompletionItemRules.Default. WithCommitCharacterRule(CharacterSetModificationRule.Create(CharacterSetModificationKind.Remove, ':')); private static ImmutableArray<CompletionItem> GetSnippetCompletionItems( Workspace workspace, SemanticModel semanticModel, bool isPreProcessorContext, bool isTupleContext, CancellationToken cancellationToken) { var service = workspace.Services.GetLanguageServices(semanticModel.Language).GetService<ISnippetInfoService>(); if (service == null) return ImmutableArray<CompletionItem>.Empty; var snippets = service.GetSnippetsIfAvailable(); if (isPreProcessorContext) { snippets = snippets.Where(snippet => snippet.Shortcut != null && snippet.Shortcut.StartsWith("#", StringComparison.Ordinal)); } return snippets.SelectAsArray(snippet => { var rules = isTupleContext ? s_tupleRules : CompletionItemRules.Default; rules = rules.WithFormatOnCommit(service.ShouldFormatSnippet(snippet)); return CommonCompletionItem.Create( displayText: isPreProcessorContext ? snippet.Shortcut[1..] : snippet.Shortcut, displayTextSuffix: "", sortText: isPreProcessorContext ? snippet.Shortcut[1..] : snippet.Shortcut, description: (snippet.Title + Environment.NewLine + snippet.Description).ToSymbolDisplayParts(), glyph: Glyph.Snippet, rules: rules); }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Snippets; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportCompletionProvider(nameof(SnippetCompletionProvider), LanguageNames.CSharp)] [ExtensionOrder(After = nameof(CrefCompletionProvider))] [Shared] internal sealed class SnippetCompletionProvider : LSPCompletionProvider { internal override bool IsSnippetProvider => true; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public SnippetCompletionProvider() { } public override bool IsInsertionTrigger(SourceText text, int characterPosition, OptionSet options) => CompletionUtilities.IsTriggerCharacter(text, characterPosition, options); public override ImmutableHashSet<char> TriggerCharacters { get; } = CompletionUtilities.CommonTriggerCharacters; public override async Task ProvideCompletionsAsync(CompletionContext context) { try { var document = context.Document; var position = context.Position; var options = context.Options; var cancellationToken = context.CancellationToken; using (Logger.LogBlock(FunctionId.Completion_SnippetCompletionProvider_GetItemsWorker_CSharp, cancellationToken)) { // TODO (https://github.com/dotnet/roslyn/issues/5107): Enable in Interactive. var workspace = document.Project.Solution.Workspace; if (!workspace.CanApplyChange(ApplyChangesKind.ChangeDocument) || workspace.Kind == WorkspaceKind.Debugger || workspace.Kind == WorkspaceKind.Interactive) { return; } context.AddItems(await document.GetUnionItemsFromDocumentAndLinkedDocumentsAsync( UnionCompletionItemComparer.Instance, d => GetSnippetsForDocumentAsync(d, position, cancellationToken)).ConfigureAwait(false)); } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e)) { // nop } } private static async Task<ImmutableArray<CompletionItem>> GetSnippetsForDocumentAsync( Document document, int position, CancellationToken cancellationToken) { var syntaxTree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var semanticFacts = document.GetRequiredLanguageService<ISemanticFactsService>(); var leftToken = syntaxTree.GetRoot(cancellationToken).FindTokenOnLeftOfPosition(position, includeDirectives: true); var targetToken = leftToken.GetPreviousTokenIfTouchingWord(position); if (syntaxFacts.IsInNonUserCode(syntaxTree, position, cancellationToken) || syntaxTree.IsRightOfDotOrArrowOrColonColon(position, targetToken, cancellationToken) || syntaxFacts.GetContainingTypeDeclaration(await syntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false), position) is EnumDeclarationSyntax) { return ImmutableArray<CompletionItem>.Empty; } var isPossibleTupleContext = syntaxFacts.IsPossibleTupleContext(syntaxTree, position, cancellationToken); if (syntaxFacts.IsPreProcessorDirectiveContext(syntaxTree, position, cancellationToken)) { var directive = leftToken.GetAncestor<DirectiveTriviaSyntax>(); Contract.ThrowIfNull(directive); if (!directive.DirectiveNameToken.IsKind( SyntaxKind.IfKeyword, SyntaxKind.RegionKeyword, SyntaxKind.ElseKeyword, SyntaxKind.ElifKeyword, SyntaxKind.ErrorKeyword, SyntaxKind.LineKeyword, SyntaxKind.PragmaKeyword, SyntaxKind.EndIfKeyword, SyntaxKind.UndefKeyword, SyntaxKind.EndRegionKeyword, SyntaxKind.WarningKeyword)) { var semanticModel = await document.ReuseExistingSpeculativeModelAsync(position, cancellationToken).ConfigureAwait(false); return GetSnippetCompletionItems( document.Project.Solution.Workspace, semanticModel, isPreProcessorContext: true, isTupleContext: isPossibleTupleContext, cancellationToken: cancellationToken); } } else { var semanticModel = await document.ReuseExistingSpeculativeModelAsync(position, cancellationToken).ConfigureAwait(false); if (semanticFacts.IsGlobalStatementContext(semanticModel, position, cancellationToken) || semanticFacts.IsExpressionContext(semanticModel, position, cancellationToken) || semanticFacts.IsStatementContext(semanticModel, position, cancellationToken) || semanticFacts.IsTypeContext(semanticModel, position, cancellationToken) || semanticFacts.IsTypeDeclarationContext(semanticModel, position, cancellationToken) || semanticFacts.IsNamespaceContext(semanticModel, position, cancellationToken) || semanticFacts.IsNamespaceDeclarationNameContext(semanticModel, position, cancellationToken) || semanticFacts.IsMemberDeclarationContext(semanticModel, position, cancellationToken) || semanticFacts.IsLabelContext(semanticModel, position, cancellationToken)) { return GetSnippetCompletionItems( document.Project.Solution.Workspace, semanticModel, isPreProcessorContext: false, isTupleContext: isPossibleTupleContext, cancellationToken: cancellationToken); } } return ImmutableArray<CompletionItem>.Empty; } private static readonly CompletionItemRules s_tupleRules = CompletionItemRules.Default. WithCommitCharacterRule(CharacterSetModificationRule.Create(CharacterSetModificationKind.Remove, ':')); private static ImmutableArray<CompletionItem> GetSnippetCompletionItems( Workspace workspace, SemanticModel semanticModel, bool isPreProcessorContext, bool isTupleContext, CancellationToken cancellationToken) { var service = workspace.Services.GetLanguageServices(semanticModel.Language).GetService<ISnippetInfoService>(); if (service == null) return ImmutableArray<CompletionItem>.Empty; var snippets = service.GetSnippetsIfAvailable(); if (isPreProcessorContext) { snippets = snippets.Where(snippet => snippet.Shortcut != null && snippet.Shortcut.StartsWith("#", StringComparison.Ordinal)); } return snippets.SelectAsArray(snippet => { var rules = isTupleContext ? s_tupleRules : CompletionItemRules.Default; rules = rules.WithFormatOnCommit(service.ShouldFormatSnippet(snippet)); return CommonCompletionItem.Create( displayText: isPreProcessorContext ? snippet.Shortcut[1..] : snippet.Shortcut, displayTextSuffix: "", sortText: isPreProcessorContext ? snippet.Shortcut[1..] : snippet.Shortcut, description: (snippet.Title + Environment.NewLine + snippet.Description).ToSymbolDisplayParts(), glyph: Glyph.Snippet, rules: rules); }); } } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/TestUtilities/ReassignedVariable/AbstractReassignedVariableTests.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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.ReassignedVariable; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.ReassignedVariable { [UseExportProvider] public abstract class AbstractReassignedVariableTests { protected abstract TestWorkspace CreateWorkspace(string markup); protected async Task TestAsync(string markup) { using var workspace = CreateWorkspace(markup); var project = workspace.CurrentSolution.Projects.Single(); var language = project.Language; var document = project.Documents.Single(); var text = await document.GetTextAsync(); var service = document.GetRequiredLanguageService<IReassignedVariableService>(); var result = await service.GetLocationsAsync(document, new TextSpan(0, text.Length), CancellationToken.None); var expectedSpans = workspace.Documents.Single().SelectedSpans.OrderBy(s => s.Start); var actualSpans = result.OrderBy(s => s.Start); Assert.Equal(expectedSpans, actualSpans); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.ReassignedVariable; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.ReassignedVariable { [UseExportProvider] public abstract class AbstractReassignedVariableTests { protected abstract TestWorkspace CreateWorkspace(string markup); protected async Task TestAsync(string markup) { using var workspace = CreateWorkspace(markup); var project = workspace.CurrentSolution.Projects.Single(); var language = project.Language; var document = project.Documents.Single(); var text = await document.GetTextAsync(); var service = document.GetRequiredLanguageService<IReassignedVariableService>(); var result = await service.GetLocationsAsync(document, new TextSpan(0, text.Length), CancellationToken.None); var expectedSpans = workspace.Documents.Single().SelectedSpans.OrderBy(s => s.Start); var actualSpans = result.OrderBy(s => s.Start); Assert.Equal(expectedSpans, actualSpans); } } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/VisualBasic/Portable/InvertIf/VisualBasicInvertIfCodeRefactoringProvider.SingleLine.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.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.InvertIf <ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeRefactoringProviderNames.InvertIf), [Shared]> Friend NotInheritable Class VisualBasicInvertSingleLineIfCodeRefactoringProvider Inherits VisualBasicInvertIfCodeRefactoringProvider(Of SingleLineIfStatementSyntax) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Protected Overrides Function IsElseless(ifNode As SingleLineIfStatementSyntax) As Boolean Return ifNode.ElseClause Is Nothing End Function Protected Overrides Function CanInvert(ifNode As SingleLineIfStatementSyntax) As Boolean Return TypeOf ifNode.Parent IsNot SingleLineLambdaExpressionSyntax AndAlso Not ifNode.Statements.Any(Function(n) n.IsKind(SyntaxKind.LocalDeclarationStatement)) AndAlso Not If(ifNode.ElseClause?.Statements.Any(Function(n) n.IsKind(SyntaxKind.LocalDeclarationStatement)), False) End Function Protected Overrides Function GetCondition(ifNode As SingleLineIfStatementSyntax) As SyntaxNode Return ifNode.Condition End Function Protected Overrides Function GetIfBody(ifNode As SingleLineIfStatementSyntax) As SyntaxList(Of StatementSyntax) Return ifNode.Statements End Function Protected Overrides Function GetElseBody(ifNode As SingleLineIfStatementSyntax) As SyntaxList(Of StatementSyntax) Return ifNode.ElseClause.Statements End Function Protected Overrides Function UpdateIf( sourceText As SourceText, ifNode As SingleLineIfStatementSyntax, condition As SyntaxNode, trueStatements As SyntaxList(Of StatementSyntax), Optional falseStatements As SyntaxList(Of StatementSyntax) = Nothing) As SingleLineIfStatementSyntax Dim isSingleLine = sourceText.AreOnSameLine(ifNode.GetFirstToken(), ifNode.GetLastToken()) If isSingleLine AndAlso falseStatements.Count > 0 Then ' If statement Is on a single line, And we're swapping the true/false parts. ' In that case, try to swap the trailing trivia between the true/false parts. ' That way the trailing comments/newlines at the end of the 'if' stay there, ' And the spaces after the true-part stay where they are. Dim lastTrue = trueStatements.LastOrDefault() Dim lastFalse = falseStatements.LastOrDefault() If lastTrue IsNot Nothing AndAlso lastFalse IsNot Nothing Then Dim newLastTrue = lastTrue.WithTrailingTrivia(lastFalse.GetTrailingTrivia()) Dim newLastFalse = lastFalse.WithTrailingTrivia(lastTrue.GetTrailingTrivia()) trueStatements = trueStatements.Replace(lastTrue, newLastTrue) falseStatements = falseStatements.Replace(lastFalse, newLastFalse) End If End If Dim updatedIf = ifNode _ .WithCondition(DirectCast(condition, ExpressionSyntax)) _ .WithStatements(trueStatements) If falseStatements.Count <> 0 Then Dim elseClause = If(updatedIf.ElseClause IsNot Nothing, updatedIf.ElseClause.WithStatements(falseStatements), SyntaxFactory.SingleLineElseClause(falseStatements)) updatedIf = updatedIf.WithElseClause(elseClause) End If Return updatedIf 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.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.InvertIf <ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeRefactoringProviderNames.InvertIf), [Shared]> Friend NotInheritable Class VisualBasicInvertSingleLineIfCodeRefactoringProvider Inherits VisualBasicInvertIfCodeRefactoringProvider(Of SingleLineIfStatementSyntax) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Protected Overrides Function IsElseless(ifNode As SingleLineIfStatementSyntax) As Boolean Return ifNode.ElseClause Is Nothing End Function Protected Overrides Function CanInvert(ifNode As SingleLineIfStatementSyntax) As Boolean Return TypeOf ifNode.Parent IsNot SingleLineLambdaExpressionSyntax AndAlso Not ifNode.Statements.Any(Function(n) n.IsKind(SyntaxKind.LocalDeclarationStatement)) AndAlso Not If(ifNode.ElseClause?.Statements.Any(Function(n) n.IsKind(SyntaxKind.LocalDeclarationStatement)), False) End Function Protected Overrides Function GetCondition(ifNode As SingleLineIfStatementSyntax) As SyntaxNode Return ifNode.Condition End Function Protected Overrides Function GetIfBody(ifNode As SingleLineIfStatementSyntax) As SyntaxList(Of StatementSyntax) Return ifNode.Statements End Function Protected Overrides Function GetElseBody(ifNode As SingleLineIfStatementSyntax) As SyntaxList(Of StatementSyntax) Return ifNode.ElseClause.Statements End Function Protected Overrides Function UpdateIf( sourceText As SourceText, ifNode As SingleLineIfStatementSyntax, condition As SyntaxNode, trueStatements As SyntaxList(Of StatementSyntax), Optional falseStatements As SyntaxList(Of StatementSyntax) = Nothing) As SingleLineIfStatementSyntax Dim isSingleLine = sourceText.AreOnSameLine(ifNode.GetFirstToken(), ifNode.GetLastToken()) If isSingleLine AndAlso falseStatements.Count > 0 Then ' If statement Is on a single line, And we're swapping the true/false parts. ' In that case, try to swap the trailing trivia between the true/false parts. ' That way the trailing comments/newlines at the end of the 'if' stay there, ' And the spaces after the true-part stay where they are. Dim lastTrue = trueStatements.LastOrDefault() Dim lastFalse = falseStatements.LastOrDefault() If lastTrue IsNot Nothing AndAlso lastFalse IsNot Nothing Then Dim newLastTrue = lastTrue.WithTrailingTrivia(lastFalse.GetTrailingTrivia()) Dim newLastFalse = lastFalse.WithTrailingTrivia(lastTrue.GetTrailingTrivia()) trueStatements = trueStatements.Replace(lastTrue, newLastTrue) falseStatements = falseStatements.Replace(lastFalse, newLastFalse) End If End If Dim updatedIf = ifNode _ .WithCondition(DirectCast(condition, ExpressionSyntax)) _ .WithStatements(trueStatements) If falseStatements.Count <> 0 Then Dim elseClause = If(updatedIf.ElseClause IsNot Nothing, updatedIf.ElseClause.WithStatements(falseStatements), SyntaxFactory.SingleLineElseClause(falseStatements)) updatedIf = updatedIf.WithElseClause(elseClause) End If Return updatedIf End Function End Class End Namespace
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/EditorConfigSettings/Data/Formatting/FormattingSetting.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data { internal abstract class FormattingSetting { protected OptionUpdater Updater { get; } protected string? Language { get; } protected FormattingSetting(string description, OptionUpdater updater, SettingLocation location, string? language = null) { Description = description ?? throw new ArgumentNullException(nameof(description)); Updater = updater; Location = location; Language = language; } public string Description { get; } public abstract string Category { get; } public abstract Type Type { get; } public abstract OptionKey2 Key { get; } public abstract void SetValue(object value); public abstract object? GetValue(); public abstract bool IsDefinedInEditorConfig { get; } public SettingLocation Location { get; protected set; } public static PerLanguageFormattingSetting<TOption> Create<TOption>(PerLanguageOption2<TOption> option, string description, AnalyzerConfigOptions editorConfigOptions, OptionSet visualStudioOptions, OptionUpdater updater, string fileName) where TOption : notnull { var isDefinedInEditorConfig = editorConfigOptions.TryGetEditorConfigOption<TOption>(option, out _); var location = new SettingLocation(isDefinedInEditorConfig ? LocationKind.EditorConfig : LocationKind.VisualStudio, fileName); return new PerLanguageFormattingSetting<TOption>(option, description, editorConfigOptions, visualStudioOptions, updater, location); } public static FormattingSetting<TOption> Create<TOption>(Option2<TOption> option, string description, AnalyzerConfigOptions editorConfigOptions, OptionSet visualStudioOptions, OptionUpdater updater, string fileName) where TOption : struct { var isDefinedInEditorConfig = editorConfigOptions.TryGetEditorConfigOption<TOption>(option, out _); var location = new SettingLocation(isDefinedInEditorConfig ? LocationKind.EditorConfig : LocationKind.VisualStudio, fileName); return new FormattingSetting<TOption>(option, description, editorConfigOptions, visualStudioOptions, updater, location); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data { internal abstract class FormattingSetting { protected OptionUpdater Updater { get; } protected string? Language { get; } protected FormattingSetting(string description, OptionUpdater updater, SettingLocation location, string? language = null) { Description = description ?? throw new ArgumentNullException(nameof(description)); Updater = updater; Location = location; Language = language; } public string Description { get; } public abstract string Category { get; } public abstract Type Type { get; } public abstract OptionKey2 Key { get; } public abstract void SetValue(object value); public abstract object? GetValue(); public abstract bool IsDefinedInEditorConfig { get; } public SettingLocation Location { get; protected set; } public static PerLanguageFormattingSetting<TOption> Create<TOption>(PerLanguageOption2<TOption> option, string description, AnalyzerConfigOptions editorConfigOptions, OptionSet visualStudioOptions, OptionUpdater updater, string fileName) where TOption : notnull { var isDefinedInEditorConfig = editorConfigOptions.TryGetEditorConfigOption<TOption>(option, out _); var location = new SettingLocation(isDefinedInEditorConfig ? LocationKind.EditorConfig : LocationKind.VisualStudio, fileName); return new PerLanguageFormattingSetting<TOption>(option, description, editorConfigOptions, visualStudioOptions, updater, location); } public static FormattingSetting<TOption> Create<TOption>(Option2<TOption> option, string description, AnalyzerConfigOptions editorConfigOptions, OptionSet visualStudioOptions, OptionUpdater updater, string fileName) where TOption : struct { var isDefinedInEditorConfig = editorConfigOptions.TryGetEditorConfigOption<TOption>(option, out _); var location = new SettingLocation(isDefinedInEditorConfig ? LocationKind.EditorConfig : LocationKind.VisualStudio, fileName); return new FormattingSetting<TOption>(option, description, editorConfigOptions, visualStudioOptions, updater, location); } } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/CodeGeneration/Symbols/CodeGenerationConstructorInfo.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.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationConstructorInfo { private static readonly ConditionalWeakTable<IMethodSymbol, CodeGenerationConstructorInfo> s_constructorToInfoMap = new(); private readonly bool _isPrimaryConstructor; private readonly bool _isUnsafe; private readonly string _typeName; private readonly ImmutableArray<SyntaxNode> _baseConstructorArguments; private readonly ImmutableArray<SyntaxNode> _thisConstructorArguments; private readonly ImmutableArray<SyntaxNode> _statements; private CodeGenerationConstructorInfo( bool isPrimaryConstructor, bool isUnsafe, string typeName, ImmutableArray<SyntaxNode> statements, ImmutableArray<SyntaxNode> baseConstructorArguments, ImmutableArray<SyntaxNode> thisConstructorArguments) { _isPrimaryConstructor = isPrimaryConstructor; _isUnsafe = isUnsafe; _typeName = typeName; _statements = statements; _baseConstructorArguments = baseConstructorArguments; _thisConstructorArguments = thisConstructorArguments; } public static void Attach( IMethodSymbol constructor, bool isPrimaryConstructor, bool isUnsafe, string typeName, ImmutableArray<SyntaxNode> statements, ImmutableArray<SyntaxNode> baseConstructorArguments, ImmutableArray<SyntaxNode> thisConstructorArguments) { var info = new CodeGenerationConstructorInfo(isPrimaryConstructor, isUnsafe, typeName, statements, baseConstructorArguments, thisConstructorArguments); s_constructorToInfoMap.Add(constructor, info); } private static CodeGenerationConstructorInfo? GetInfo(IMethodSymbol method) { s_constructorToInfoMap.TryGetValue(method, out var info); return info; } public static ImmutableArray<SyntaxNode> GetThisConstructorArgumentsOpt(IMethodSymbol constructor) => GetThisConstructorArgumentsOpt(GetInfo(constructor)); public static ImmutableArray<SyntaxNode> GetBaseConstructorArgumentsOpt(IMethodSymbol constructor) => GetBaseConstructorArgumentsOpt(GetInfo(constructor)); public static ImmutableArray<SyntaxNode> GetStatements(IMethodSymbol constructor) => GetStatements(GetInfo(constructor)); public static string GetTypeName(IMethodSymbol constructor) => GetTypeName(GetInfo(constructor), constructor); public static bool GetIsUnsafe(IMethodSymbol constructor) => GetIsUnsafe(GetInfo(constructor)); public static bool GetIsPrimaryConstructor(IMethodSymbol constructor) => GetIsPrimaryConstructor(GetInfo(constructor)); private static ImmutableArray<SyntaxNode> GetThisConstructorArgumentsOpt(CodeGenerationConstructorInfo? info) => info?._thisConstructorArguments ?? default; private static ImmutableArray<SyntaxNode> GetBaseConstructorArgumentsOpt(CodeGenerationConstructorInfo? info) => info?._baseConstructorArguments ?? default; private static ImmutableArray<SyntaxNode> GetStatements(CodeGenerationConstructorInfo? info) => info?._statements ?? default; private static string GetTypeName(CodeGenerationConstructorInfo? info, IMethodSymbol constructor) => info == null ? constructor.ContainingType.Name : info._typeName; private static bool GetIsUnsafe(CodeGenerationConstructorInfo? info) => info?._isUnsafe ?? false; private static bool GetIsPrimaryConstructor(CodeGenerationConstructorInfo? info) => info?._isPrimaryConstructor ?? 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.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationConstructorInfo { private static readonly ConditionalWeakTable<IMethodSymbol, CodeGenerationConstructorInfo> s_constructorToInfoMap = new(); private readonly bool _isPrimaryConstructor; private readonly bool _isUnsafe; private readonly string _typeName; private readonly ImmutableArray<SyntaxNode> _baseConstructorArguments; private readonly ImmutableArray<SyntaxNode> _thisConstructorArguments; private readonly ImmutableArray<SyntaxNode> _statements; private CodeGenerationConstructorInfo( bool isPrimaryConstructor, bool isUnsafe, string typeName, ImmutableArray<SyntaxNode> statements, ImmutableArray<SyntaxNode> baseConstructorArguments, ImmutableArray<SyntaxNode> thisConstructorArguments) { _isPrimaryConstructor = isPrimaryConstructor; _isUnsafe = isUnsafe; _typeName = typeName; _statements = statements; _baseConstructorArguments = baseConstructorArguments; _thisConstructorArguments = thisConstructorArguments; } public static void Attach( IMethodSymbol constructor, bool isPrimaryConstructor, bool isUnsafe, string typeName, ImmutableArray<SyntaxNode> statements, ImmutableArray<SyntaxNode> baseConstructorArguments, ImmutableArray<SyntaxNode> thisConstructorArguments) { var info = new CodeGenerationConstructorInfo(isPrimaryConstructor, isUnsafe, typeName, statements, baseConstructorArguments, thisConstructorArguments); s_constructorToInfoMap.Add(constructor, info); } private static CodeGenerationConstructorInfo? GetInfo(IMethodSymbol method) { s_constructorToInfoMap.TryGetValue(method, out var info); return info; } public static ImmutableArray<SyntaxNode> GetThisConstructorArgumentsOpt(IMethodSymbol constructor) => GetThisConstructorArgumentsOpt(GetInfo(constructor)); public static ImmutableArray<SyntaxNode> GetBaseConstructorArgumentsOpt(IMethodSymbol constructor) => GetBaseConstructorArgumentsOpt(GetInfo(constructor)); public static ImmutableArray<SyntaxNode> GetStatements(IMethodSymbol constructor) => GetStatements(GetInfo(constructor)); public static string GetTypeName(IMethodSymbol constructor) => GetTypeName(GetInfo(constructor), constructor); public static bool GetIsUnsafe(IMethodSymbol constructor) => GetIsUnsafe(GetInfo(constructor)); public static bool GetIsPrimaryConstructor(IMethodSymbol constructor) => GetIsPrimaryConstructor(GetInfo(constructor)); private static ImmutableArray<SyntaxNode> GetThisConstructorArgumentsOpt(CodeGenerationConstructorInfo? info) => info?._thisConstructorArguments ?? default; private static ImmutableArray<SyntaxNode> GetBaseConstructorArgumentsOpt(CodeGenerationConstructorInfo? info) => info?._baseConstructorArguments ?? default; private static ImmutableArray<SyntaxNode> GetStatements(CodeGenerationConstructorInfo? info) => info?._statements ?? default; private static string GetTypeName(CodeGenerationConstructorInfo? info, IMethodSymbol constructor) => info == null ? constructor.ContainingType.Name : info._typeName; private static bool GetIsUnsafe(CodeGenerationConstructorInfo? info) => info?._isUnsafe ?? false; private static bool GetIsPrimaryConstructor(CodeGenerationConstructorInfo? info) => info?._isPrimaryConstructor ?? false; } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/CodeModel/ProjectCodeModel.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 EnvDTE; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { /// <summary> /// The root type that is held by a project to provide CodeModel support. /// </summary> internal sealed class ProjectCodeModel : IProjectCodeModel { private readonly NonReentrantLock _guard = new NonReentrantLock(); private readonly IThreadingContext _threadingContext; private readonly ProjectId _projectId; private readonly ICodeModelInstanceFactory _codeModelInstanceFactory; private readonly VisualStudioWorkspace _visualStudioWorkspace; private readonly IServiceProvider _serviceProvider; private readonly ProjectCodeModelFactory _projectCodeModelFactory; private CodeModelProjectCache _codeModelCache; public ProjectCodeModel(IThreadingContext threadingContext, ProjectId projectId, ICodeModelInstanceFactory codeModelInstanceFactory, VisualStudioWorkspace visualStudioWorkspace, IServiceProvider serviceProvider, ProjectCodeModelFactory projectCodeModelFactory) { _threadingContext = threadingContext; _projectId = projectId; _codeModelInstanceFactory = codeModelInstanceFactory; _visualStudioWorkspace = visualStudioWorkspace; _serviceProvider = serviceProvider; _projectCodeModelFactory = projectCodeModelFactory; } public void OnProjectClosed() { _codeModelCache?.OnProjectClosed(); _projectCodeModelFactory.OnProjectClosed(_projectId); } private CodeModelProjectCache GetCodeModelCache() { Contract.ThrowIfNull(_projectId); Contract.ThrowIfNull(_visualStudioWorkspace); using (_guard.DisposableWait()) { if (_codeModelCache == null) { var workspaceProject = _visualStudioWorkspace.CurrentSolution.GetProject(_projectId); if (workspaceProject != null) { _codeModelCache = new CodeModelProjectCache(_threadingContext, _projectId, _codeModelInstanceFactory, _projectCodeModelFactory, _serviceProvider, workspaceProject.LanguageServices, _visualStudioWorkspace); } } return _codeModelCache; } } internal IEnumerable<ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>> GetCachedFileCodeModelInstances() => GetCodeModelCache().GetFileCodeModelInstances(); internal bool TryGetCachedFileCodeModel(string fileName, out ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> fileCodeModelHandle) { var handle = GetCodeModelCache()?.GetComHandleForFileCodeModel(fileName); fileCodeModelHandle = handle != null ? handle.Value : default; return handle != null; } /// <summary> /// Gets or creates a <see cref="FileCodeModel"/> for the given file name. Because we don't have /// a parent object, this will call back to the project system to provide us the parent object. /// </summary> public ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> GetOrCreateFileCodeModel(string filePath) => GetCodeModelCache().GetOrCreateFileCodeModel(filePath); public ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> GetOrCreateFileCodeModel(string filePath, object parent) => GetCodeModelCache().GetOrCreateFileCodeModel(filePath, parent); public EnvDTE.CodeModel GetOrCreateRootCodeModel(EnvDTE.Project parent) => GetCodeModelCache().GetOrCreateRootCodeModel(parent); public void OnSourceFileRemoved(string fileName) { // This uses the field directly. If we haven't yet created the CodeModelProjectCache, then we most definitely // don't have any source files we need to zombie when they go away. There's no reason to create a cache in that case. _codeModelCache?.OnSourceFileRemoved(fileName); } public void OnSourceFileRenaming(string filePath, string newFilePath) { // This uses the field directly. If we haven't yet created the CodeModelProjectCache, then we most definitely // don't have any source files we need to handle a rename for. There's no reason to create a cache in that case. _codeModelCache?.OnSourceFileRenaming(filePath, newFilePath); } EnvDTE.FileCodeModel IProjectCodeModel.GetOrCreateFileCodeModel(string filePath, object parent) => this.GetOrCreateFileCodeModel(filePath, parent).Handle; } }
// Licensed to the .NET Foundation under one or more 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 EnvDTE; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { /// <summary> /// The root type that is held by a project to provide CodeModel support. /// </summary> internal sealed class ProjectCodeModel : IProjectCodeModel { private readonly NonReentrantLock _guard = new NonReentrantLock(); private readonly IThreadingContext _threadingContext; private readonly ProjectId _projectId; private readonly ICodeModelInstanceFactory _codeModelInstanceFactory; private readonly VisualStudioWorkspace _visualStudioWorkspace; private readonly IServiceProvider _serviceProvider; private readonly ProjectCodeModelFactory _projectCodeModelFactory; private CodeModelProjectCache _codeModelCache; public ProjectCodeModel(IThreadingContext threadingContext, ProjectId projectId, ICodeModelInstanceFactory codeModelInstanceFactory, VisualStudioWorkspace visualStudioWorkspace, IServiceProvider serviceProvider, ProjectCodeModelFactory projectCodeModelFactory) { _threadingContext = threadingContext; _projectId = projectId; _codeModelInstanceFactory = codeModelInstanceFactory; _visualStudioWorkspace = visualStudioWorkspace; _serviceProvider = serviceProvider; _projectCodeModelFactory = projectCodeModelFactory; } public void OnProjectClosed() { _codeModelCache?.OnProjectClosed(); _projectCodeModelFactory.OnProjectClosed(_projectId); } private CodeModelProjectCache GetCodeModelCache() { Contract.ThrowIfNull(_projectId); Contract.ThrowIfNull(_visualStudioWorkspace); using (_guard.DisposableWait()) { if (_codeModelCache == null) { var workspaceProject = _visualStudioWorkspace.CurrentSolution.GetProject(_projectId); if (workspaceProject != null) { _codeModelCache = new CodeModelProjectCache(_threadingContext, _projectId, _codeModelInstanceFactory, _projectCodeModelFactory, _serviceProvider, workspaceProject.LanguageServices, _visualStudioWorkspace); } } return _codeModelCache; } } internal IEnumerable<ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>> GetCachedFileCodeModelInstances() => GetCodeModelCache().GetFileCodeModelInstances(); internal bool TryGetCachedFileCodeModel(string fileName, out ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> fileCodeModelHandle) { var handle = GetCodeModelCache()?.GetComHandleForFileCodeModel(fileName); fileCodeModelHandle = handle != null ? handle.Value : default; return handle != null; } /// <summary> /// Gets or creates a <see cref="FileCodeModel"/> for the given file name. Because we don't have /// a parent object, this will call back to the project system to provide us the parent object. /// </summary> public ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> GetOrCreateFileCodeModel(string filePath) => GetCodeModelCache().GetOrCreateFileCodeModel(filePath); public ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> GetOrCreateFileCodeModel(string filePath, object parent) => GetCodeModelCache().GetOrCreateFileCodeModel(filePath, parent); public EnvDTE.CodeModel GetOrCreateRootCodeModel(EnvDTE.Project parent) => GetCodeModelCache().GetOrCreateRootCodeModel(parent); public void OnSourceFileRemoved(string fileName) { // This uses the field directly. If we haven't yet created the CodeModelProjectCache, then we most definitely // don't have any source files we need to zombie when they go away. There's no reason to create a cache in that case. _codeModelCache?.OnSourceFileRemoved(fileName); } public void OnSourceFileRenaming(string filePath, string newFilePath) { // This uses the field directly. If we haven't yet created the CodeModelProjectCache, then we most definitely // don't have any source files we need to handle a rename for. There's no reason to create a cache in that case. _codeModelCache?.OnSourceFileRenaming(filePath, newFilePath); } EnvDTE.FileCodeModel IProjectCodeModel.GetOrCreateFileCodeModel(string filePath, object parent) => this.GetOrCreateFileCodeModel(filePath, parent).Handle; } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/VisualBasic/Portable/Simplification/Reducers/AbstractVisualBasicReducer.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification Partial Friend MustInherit Class AbstractVisualBasicReducer Inherits AbstractReducer Protected Sub New(pool As ObjectPool(Of IReductionRewriter)) MyBase.New(pool) End Sub Protected Shared ReadOnly s_reduceParentheses As Func(Of ParenthesizedExpressionSyntax, SemanticModel, OptionSet, CancellationToken, SyntaxNode) = AddressOf ReduceParentheses Protected Shared Function ReduceParentheses( node As ParenthesizedExpressionSyntax, semanticModel As SemanticModel, optionSet As OptionSet, cancellationToken As CancellationToken ) As SyntaxNode If node.CanRemoveParentheses(semanticModel, cancellationToken) Then ' TODO(DustinCa): We should not be skipping elastic trivia below. ' However, the formatter seems to mess up trailing trivia in some ' cases if elastic trivia is there -- and it's not clear why. ' Specifically removing the elastic trivia formatting rule doesn't ' have any effect. Dim resultNode = VisualBasicSyntaxFacts.Instance.Unparenthesize(node) resultNode = SimplificationHelpers.CopyAnnotations(node, resultNode) Return resultNode End If ' We don't know how to simplify this. Return node End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification Partial Friend MustInherit Class AbstractVisualBasicReducer Inherits AbstractReducer Protected Sub New(pool As ObjectPool(Of IReductionRewriter)) MyBase.New(pool) End Sub Protected Shared ReadOnly s_reduceParentheses As Func(Of ParenthesizedExpressionSyntax, SemanticModel, OptionSet, CancellationToken, SyntaxNode) = AddressOf ReduceParentheses Protected Shared Function ReduceParentheses( node As ParenthesizedExpressionSyntax, semanticModel As SemanticModel, optionSet As OptionSet, cancellationToken As CancellationToken ) As SyntaxNode If node.CanRemoveParentheses(semanticModel, cancellationToken) Then ' TODO(DustinCa): We should not be skipping elastic trivia below. ' However, the formatter seems to mess up trailing trivia in some ' cases if elastic trivia is there -- and it's not clear why. ' Specifically removing the elastic trivia formatting rule doesn't ' have any effect. Dim resultNode = VisualBasicSyntaxFacts.Instance.Unparenthesize(node) resultNode = SimplificationHelpers.CopyAnnotations(node, resultNode) Return resultNode End If ' We don't know how to simplify this. Return node End Function End Class End Namespace
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/Queries/AggregateKeywordRecommenderTests.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.Queries Public Class AggregateKeywordRecommenderTests <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateNotInStatementTest() VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterReturnTest() VerifyRecommendationsContain(<MethodBody>Return |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterArgument1Test() VerifyRecommendationsContain(<MethodBody>Goo(|</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterArgument2Test() VerifyRecommendationsContain(<MethodBody>Goo(bar, |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterBinaryExpressionTest() VerifyRecommendationsContain(<MethodBody>Goo(bar + |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterNotTest() VerifyRecommendationsContain(<MethodBody>Goo(Not |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterTypeOfTest() VerifyRecommendationsContain(<MethodBody>If TypeOf |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterDoWhileTest() VerifyRecommendationsContain(<MethodBody>Do While |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterDoUntilTest() VerifyRecommendationsContain(<MethodBody>Do Until |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterLoopWhileTest() VerifyRecommendationsContain(<MethodBody> Do Loop While |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterLoopUntilTest() VerifyRecommendationsContain(<MethodBody> Do Loop Until |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterIfTest() VerifyRecommendationsContain(<MethodBody>If |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterElseIfTest() VerifyRecommendationsContain(<MethodBody>ElseIf |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterElseSpaceIfTest() VerifyRecommendationsContain(<MethodBody>Else If |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterErrorTest() VerifyRecommendationsContain(<MethodBody>Error |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterThrowTest() VerifyRecommendationsContain(<MethodBody>Throw |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterArrayInitializerSquiggleTest() VerifyRecommendationsContain(<MethodBody>Dim x = {|</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterArrayInitializerCommaTest() VerifyRecommendationsContain(<MethodBody>Dim x = {0, |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SpecExample1Test() VerifyRecommendationsContain( <MethodBody> Dim orderTotals = _ From cust In Customers _ Where cust.State = "WA" _ | </MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SpecExample2Test() VerifyRecommendationsContain( <MethodBody> Dim ordersTotal = _ | </MethodBody>, "Aggregate") End Sub <WorkItem(543173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543173")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterMultiLineFunctionLambdaExprTest() VerifyRecommendationsContain(<MethodBody>Dim q2 = From i1 In arr Order By Function() Return 5 End Function |</MethodBody>, "Aggregate") End Sub <WorkItem(543174, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543174")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterAnonymousObjectCreationExprTest() VerifyRecommendationsContain(<MethodBody>Dim q2 = From i1 In arr Order By New With {.Key = 10} |</MethodBody>, "Aggregate") End Sub <WorkItem(543219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543219")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterIntoClauseTest() VerifyRecommendationsContain(<MethodBody>Dim q1 = From i1 In arr Group By i1 Into Count |</MethodBody>, "Aggregate") End Sub <WorkItem(543232, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543232")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterNestedAggregateFromClauseTest() VerifyRecommendationsContain(<MethodBody>Dim q1 = Aggregate i1 In arr From i4 In arr |</MethodBody>, "Aggregate") End Sub <WorkItem(543270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543270")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInDelegateCreationTest() Dim code = <File> Module Program Sub Main(args As String()) Dim f1 As New Goo2( | End Sub Delegate Sub Goo2() Function Bar2() As Object Return Nothing End Function End Module </File> VerifyRecommendationsMissing(code, "Aggregate") 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.Queries Public Class AggregateKeywordRecommenderTests <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateNotInStatementTest() VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterReturnTest() VerifyRecommendationsContain(<MethodBody>Return |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterArgument1Test() VerifyRecommendationsContain(<MethodBody>Goo(|</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterArgument2Test() VerifyRecommendationsContain(<MethodBody>Goo(bar, |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterBinaryExpressionTest() VerifyRecommendationsContain(<MethodBody>Goo(bar + |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterNotTest() VerifyRecommendationsContain(<MethodBody>Goo(Not |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterTypeOfTest() VerifyRecommendationsContain(<MethodBody>If TypeOf |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterDoWhileTest() VerifyRecommendationsContain(<MethodBody>Do While |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterDoUntilTest() VerifyRecommendationsContain(<MethodBody>Do Until |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterLoopWhileTest() VerifyRecommendationsContain(<MethodBody> Do Loop While |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterLoopUntilTest() VerifyRecommendationsContain(<MethodBody> Do Loop Until |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterIfTest() VerifyRecommendationsContain(<MethodBody>If |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterElseIfTest() VerifyRecommendationsContain(<MethodBody>ElseIf |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterElseSpaceIfTest() VerifyRecommendationsContain(<MethodBody>Else If |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterErrorTest() VerifyRecommendationsContain(<MethodBody>Error |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterThrowTest() VerifyRecommendationsContain(<MethodBody>Throw |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterArrayInitializerSquiggleTest() VerifyRecommendationsContain(<MethodBody>Dim x = {|</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterArrayInitializerCommaTest() VerifyRecommendationsContain(<MethodBody>Dim x = {0, |</MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SpecExample1Test() VerifyRecommendationsContain( <MethodBody> Dim orderTotals = _ From cust In Customers _ Where cust.State = "WA" _ | </MethodBody>, "Aggregate") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SpecExample2Test() VerifyRecommendationsContain( <MethodBody> Dim ordersTotal = _ | </MethodBody>, "Aggregate") End Sub <WorkItem(543173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543173")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterMultiLineFunctionLambdaExprTest() VerifyRecommendationsContain(<MethodBody>Dim q2 = From i1 In arr Order By Function() Return 5 End Function |</MethodBody>, "Aggregate") End Sub <WorkItem(543174, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543174")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterAnonymousObjectCreationExprTest() VerifyRecommendationsContain(<MethodBody>Dim q2 = From i1 In arr Order By New With {.Key = 10} |</MethodBody>, "Aggregate") End Sub <WorkItem(543219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543219")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterIntoClauseTest() VerifyRecommendationsContain(<MethodBody>Dim q1 = From i1 In arr Group By i1 Into Count |</MethodBody>, "Aggregate") End Sub <WorkItem(543232, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543232")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AggregateAfterNestedAggregateFromClauseTest() VerifyRecommendationsContain(<MethodBody>Dim q1 = Aggregate i1 In arr From i4 In arr |</MethodBody>, "Aggregate") End Sub <WorkItem(543270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543270")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInDelegateCreationTest() Dim code = <File> Module Program Sub Main(args As String()) Dim f1 As New Goo2( | End Sub Delegate Sub Goo2() Function Bar2() As Object Return Nothing End Function End Module </File> VerifyRecommendationsMissing(code, "Aggregate") End Sub End Class End Namespace
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/Tools/ExternalAccess/FSharp/Editor/Implementation/Debugging/FSharpDebugDataTipInfo.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.Debugging; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor.Implementation.Debugging { internal readonly struct FSharpDebugDataTipInfo { internal readonly DebugDataTipInfo UnderlyingObject; public FSharpDebugDataTipInfo(TextSpan span, string text) => UnderlyingObject = new DebugDataTipInfo(span, text); public readonly TextSpan Span => UnderlyingObject.Span; public readonly string Text => UnderlyingObject.Text; public bool IsDefault => UnderlyingObject.IsDefault; } }
// Licensed to the .NET Foundation under one or more 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.Debugging; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor.Implementation.Debugging { internal readonly struct FSharpDebugDataTipInfo { internal readonly DebugDataTipInfo UnderlyingObject; public FSharpDebugDataTipInfo(TextSpan span, string text) => UnderlyingObject = new DebugDataTipInfo(span, text); public readonly TextSpan Span => UnderlyingObject.Span; public readonly string Text => UnderlyingObject.Text; public bool IsDefault => UnderlyingObject.IsDefault; } }
-1
dotnet/roslyn
55,256
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-07-30T00:02:02Z
2021-07-30T09:17:54Z
6ce9c0048d37026337701fac035ac0745f6fe49f
88b59775dc6375635957ef229116460f290072aa
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/Completion/KeywordRecommenders/ParamsKeywordRecommender.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 ParamsKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public ParamsKeywordRecommender() : base(SyntaxKind.ParamsKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) => context.SyntaxTree.IsParamsModifierContext(context.Position, context.LeftToken); } }
// Licensed to the .NET Foundation under one or more 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 ParamsKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public ParamsKeywordRecommender() : base(SyntaxKind.ParamsKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) => context.SyntaxTree.IsParamsModifierContext(context.Position, context.LeftToken); } }
-1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/DecisionDagBuilder.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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// <para> /// A utility class for making a decision dag (directed acyclic graph) for a pattern-matching construct. /// A decision dag is represented by /// the class <see cref="BoundDecisionDag"/> and is a representation of a finite state automaton that performs a /// sequence of binary tests. Each node is represented by a <see cref="BoundDecisionDagNode"/>. There are four /// kind of nodes: <see cref="BoundTestDecisionDagNode"/> performs one of the binary tests; /// <see cref="BoundEvaluationDecisionDagNode"/> simply performs some computation and stores it in one or more /// temporary variables for use in subsequent nodes (think of it as a node with a single successor); /// <see cref="BoundWhenDecisionDagNode"/> represents the test performed by evaluating the expression of the /// when-clause of a switch case; and <see cref="BoundLeafDecisionDagNode"/> represents a leaf node when we /// have finally determined exactly which case matches. Each test processes a single input, and there are /// four kinds:<see cref="BoundDagExplicitNullTest"/> tests a value for null; <see cref="BoundDagNonNullTest"/> /// tests that a value is not null; <see cref="BoundDagTypeTest"/> checks if the value is of a given type; /// and <see cref="BoundDagValueTest"/> checks if the value is equal to a given constant. Of the evaluations, /// there are <see cref="BoundDagDeconstructEvaluation"/> which represents an invocation of a type's /// "Deconstruct" method; <see cref="BoundDagFieldEvaluation"/> reads a field; <see cref="BoundDagPropertyEvaluation"/> /// reads a property; and <see cref="BoundDagTypeEvaluation"/> converts a value from one type to another (which /// is performed only after testing that the value is of that type). /// </para> /// <para> /// In order to build this automaton, we start (in /// <see cref="MakeBoundDecisionDag(SyntaxNode, ImmutableArray{DecisionDagBuilder.StateForCase})"/> /// by computing a description of the initial state in a <see cref="DagState"/>, and then /// for each such state description we decide what the test or evaluation will be at /// that state, and compute the successor state descriptions. /// A state description represented by a <see cref="DagState"/> is a collection of partially matched /// cases represented /// by <see cref="StateForCase"/>, in which some number of the tests have already been performed /// for each case. /// When we have computed <see cref="DagState"/> descriptions for all of the states, we create a new /// <see cref="BoundDecisionDagNode"/> for each of them, containing /// the state transitions (including the test to perform at each node and the successor nodes) but /// not the state descriptions. A <see cref="BoundDecisionDag"/> containing this /// set of nodes becomes part of the bound nodes (e.g. in <see cref="BoundSwitchStatement"/> and /// <see cref="BoundUnconvertedSwitchExpression"/>) and is used for semantic analysis and lowering. /// </para> /// </summary> internal sealed class DecisionDagBuilder { private readonly CSharpCompilation _compilation; private readonly Conversions _conversions; private readonly BindingDiagnosticBag _diagnostics; private readonly LabelSymbol _defaultLabel; private DecisionDagBuilder(CSharpCompilation compilation, LabelSymbol defaultLabel, BindingDiagnosticBag diagnostics) { this._compilation = compilation; this._conversions = compilation.Conversions; _diagnostics = diagnostics; _defaultLabel = defaultLabel; } /// <summary> /// Create a decision dag for a switch statement. /// </summary> public static BoundDecisionDag CreateDecisionDagForSwitchStatement( CSharpCompilation compilation, SyntaxNode syntax, BoundExpression switchGoverningExpression, ImmutableArray<BoundSwitchSection> switchSections, LabelSymbol defaultLabel, BindingDiagnosticBag diagnostics) { var builder = new DecisionDagBuilder(compilation, defaultLabel, diagnostics); return builder.CreateDecisionDagForSwitchStatement(syntax, switchGoverningExpression, switchSections); } /// <summary> /// Create a decision dag for a switch expression. /// </summary> public static BoundDecisionDag CreateDecisionDagForSwitchExpression( CSharpCompilation compilation, SyntaxNode syntax, BoundExpression switchExpressionInput, ImmutableArray<BoundSwitchExpressionArm> switchArms, LabelSymbol defaultLabel, BindingDiagnosticBag diagnostics) { var builder = new DecisionDagBuilder(compilation, defaultLabel, diagnostics); return builder.CreateDecisionDagForSwitchExpression(syntax, switchExpressionInput, switchArms); } /// <summary> /// Translate the pattern of an is-pattern expression. /// </summary> public static BoundDecisionDag CreateDecisionDagForIsPattern( CSharpCompilation compilation, SyntaxNode syntax, BoundExpression inputExpression, BoundPattern pattern, LabelSymbol whenTrueLabel, LabelSymbol whenFalseLabel, BindingDiagnosticBag diagnostics) { var builder = new DecisionDagBuilder(compilation, defaultLabel: whenFalseLabel, diagnostics); return builder.CreateDecisionDagForIsPattern(syntax, inputExpression, pattern, whenTrueLabel); } private BoundDecisionDag CreateDecisionDagForIsPattern( SyntaxNode syntax, BoundExpression inputExpression, BoundPattern pattern, LabelSymbol whenTrueLabel) { var rootIdentifier = BoundDagTemp.ForOriginalInput(inputExpression); return MakeBoundDecisionDag(syntax, ImmutableArray.Create(MakeTestsForPattern(index: 1, pattern.Syntax, rootIdentifier, pattern, whenClause: null, whenTrueLabel))); } private BoundDecisionDag CreateDecisionDagForSwitchStatement( SyntaxNode syntax, BoundExpression switchGoverningExpression, ImmutableArray<BoundSwitchSection> switchSections) { var rootIdentifier = BoundDagTemp.ForOriginalInput(switchGoverningExpression); int i = 0; var builder = ArrayBuilder<StateForCase>.GetInstance(switchSections.Length); foreach (BoundSwitchSection section in switchSections) { foreach (BoundSwitchLabel label in section.SwitchLabels) { if (label.Syntax.Kind() != SyntaxKind.DefaultSwitchLabel) { builder.Add(MakeTestsForPattern(++i, label.Syntax, rootIdentifier, label.Pattern, label.WhenClause, label.Label)); } } } return MakeBoundDecisionDag(syntax, builder.ToImmutableAndFree()); } /// <summary> /// Used to create a decision dag for a switch expression. /// </summary> private BoundDecisionDag CreateDecisionDagForSwitchExpression( SyntaxNode syntax, BoundExpression switchExpressionInput, ImmutableArray<BoundSwitchExpressionArm> switchArms) { var rootIdentifier = BoundDagTemp.ForOriginalInput(switchExpressionInput); int i = 0; var builder = ArrayBuilder<StateForCase>.GetInstance(switchArms.Length); foreach (BoundSwitchExpressionArm arm in switchArms) builder.Add(MakeTestsForPattern(++i, arm.Syntax, rootIdentifier, arm.Pattern, arm.WhenClause, arm.Label)); return MakeBoundDecisionDag(syntax, builder.ToImmutableAndFree()); } /// <summary> /// Compute the set of remaining tests for a pattern. /// </summary> private StateForCase MakeTestsForPattern( int index, SyntaxNode syntax, BoundDagTemp input, BoundPattern pattern, BoundExpression? whenClause, LabelSymbol label) { Tests tests = MakeAndSimplifyTestsAndBindings(input, pattern, out ImmutableArray<BoundPatternBinding> bindings); return new StateForCase(index, syntax, tests, bindings, whenClause, label); } private Tests MakeAndSimplifyTestsAndBindings( BoundDagTemp input, BoundPattern pattern, out ImmutableArray<BoundPatternBinding> bindings) { var bindingsBuilder = ArrayBuilder<BoundPatternBinding>.GetInstance(); Tests tests = MakeTestsAndBindings(input, pattern, bindingsBuilder); tests = SimplifyTestsAndBindings(tests, bindingsBuilder); bindings = bindingsBuilder.ToImmutableAndFree(); return tests; } private static Tests SimplifyTestsAndBindings( Tests tests, ArrayBuilder<BoundPatternBinding> bindingsBuilder) { // Now simplify the tests and bindings. We don't need anything in tests that does not // contribute to the result. This will, for example, permit us to match `(2, 3) is (2, _)` without // fetching `Item2` from the input. var usedValues = PooledHashSet<BoundDagEvaluation>.GetInstance(); foreach (BoundPatternBinding binding in bindingsBuilder) { BoundDagTemp temp = binding.TempContainingValue; if (temp.Source is { }) { usedValues.Add(temp.Source); } } var result = scanAndSimplify(tests); usedValues.Free(); return result; Tests scanAndSimplify(Tests tests) { switch (tests) { case Tests.SequenceTests seq: var testSequence = seq.RemainingTests; var length = testSequence.Length; var newSequence = ArrayBuilder<Tests>.GetInstance(length); newSequence.AddRange(testSequence); for (int i = length - 1; i >= 0; i--) { newSequence[i] = scanAndSimplify(newSequence[i]); } return seq.Update(newSequence); case Tests.True _: case Tests.False _: return tests; case Tests.One(BoundDagEvaluation e): if (usedValues.Contains(e)) { if (e.Input.Source is { }) usedValues.Add(e.Input.Source); return tests; } else { return Tests.True.Instance; } case Tests.One(BoundDagTest d): if (d.Input.Source is { }) usedValues.Add(d.Input.Source); return tests; case Tests.Not n: return Tests.Not.Create(scanAndSimplify(n.Negated)); default: throw ExceptionUtilities.UnexpectedValue(tests); } } } private Tests MakeTestsAndBindings( BoundDagTemp input, BoundPattern pattern, ArrayBuilder<BoundPatternBinding> bindings) { return MakeTestsAndBindings(input, pattern, out _, bindings); } /// <summary> /// Make the tests and variable bindings for the given pattern with the given input. The pattern's /// "output" value is placed in <paramref name="output"/>. The output is defined as the input /// narrowed according to the pattern's *narrowed type*; see https://github.com/dotnet/csharplang/issues/2850. /// </summary> private Tests MakeTestsAndBindings( BoundDagTemp input, BoundPattern pattern, out BoundDagTemp output, ArrayBuilder<BoundPatternBinding> bindings) { Debug.Assert(pattern.HasErrors || pattern.InputType.Equals(input.Type, TypeCompareKind.AllIgnoreOptions) || pattern.InputType.IsErrorType()); switch (pattern) { case BoundDeclarationPattern declaration: return MakeTestsAndBindingsForDeclarationPattern(input, declaration, out output, bindings); case BoundConstantPattern constant: return MakeTestsForConstantPattern(input, constant, out output); case BoundDiscardPattern _: output = input; return Tests.True.Instance; case BoundRecursivePattern recursive: return MakeTestsAndBindingsForRecursivePattern(input, recursive, out output, bindings); case BoundITuplePattern iTuple: return MakeTestsAndBindingsForITuplePattern(input, iTuple, out output, bindings); case BoundTypePattern type: return MakeTestsForTypePattern(input, type, out output); case BoundRelationalPattern rel: return MakeTestsAndBindingsForRelationalPattern(input, rel, out output); case BoundNegatedPattern neg: output = input; return MakeTestsAndBindingsForNegatedPattern(input, neg, bindings); case BoundBinaryPattern bin: return MakeTestsAndBindingsForBinaryPattern(input, bin, out output, bindings); default: throw ExceptionUtilities.UnexpectedValue(pattern.Kind); } } private Tests MakeTestsAndBindingsForITuplePattern( BoundDagTemp input, BoundITuplePattern pattern, out BoundDagTemp output, ArrayBuilder<BoundPatternBinding> bindings) { var syntax = pattern.Syntax; var patternLength = pattern.Subpatterns.Length; var objectType = this._compilation.GetSpecialType(SpecialType.System_Object); var getLengthProperty = (PropertySymbol)pattern.GetLengthMethod.AssociatedSymbol; RoslynDebug.Assert(getLengthProperty.Type.SpecialType == SpecialType.System_Int32); var getItemProperty = (PropertySymbol)pattern.GetItemMethod.AssociatedSymbol; var iTupleType = getLengthProperty.ContainingType; RoslynDebug.Assert(iTupleType.Name == "ITuple"); var tests = ArrayBuilder<Tests>.GetInstance(4 + patternLength * 2); tests.Add(new Tests.One(new BoundDagTypeTest(syntax, iTupleType, input))); var valueAsITupleEvaluation = new BoundDagTypeEvaluation(syntax, iTupleType, input); tests.Add(new Tests.One(valueAsITupleEvaluation)); var valueAsITuple = new BoundDagTemp(syntax, iTupleType, valueAsITupleEvaluation); output = valueAsITuple; var lengthEvaluation = new BoundDagPropertyEvaluation(syntax, getLengthProperty, OriginalInput(valueAsITuple, getLengthProperty)); tests.Add(new Tests.One(lengthEvaluation)); var lengthTemp = new BoundDagTemp(syntax, this._compilation.GetSpecialType(SpecialType.System_Int32), lengthEvaluation); tests.Add(new Tests.One(new BoundDagValueTest(syntax, ConstantValue.Create(patternLength), lengthTemp))); var getItemPropertyInput = OriginalInput(valueAsITuple, getItemProperty); for (int i = 0; i < patternLength; i++) { var indexEvaluation = new BoundDagIndexEvaluation(syntax, getItemProperty, i, getItemPropertyInput); tests.Add(new Tests.One(indexEvaluation)); var indexTemp = new BoundDagTemp(syntax, objectType, indexEvaluation); tests.Add(MakeTestsAndBindings(indexTemp, pattern.Subpatterns[i].Pattern, bindings)); } return Tests.AndSequence.Create(tests); } /// <summary> /// Get the earliest input of which the symbol is a member. /// A BoundDagTypeEvaluation doesn't change the underlying object being pointed to. /// So two evaluations act on the same input so long as they have the same original input. /// We use this method to compute the original input for an evaluation. /// </summary> private BoundDagTemp OriginalInput(BoundDagTemp input, Symbol symbol) { while (input.Source is BoundDagTypeEvaluation source && IsDerivedType(source.Input.Type, symbol.ContainingType)) { input = source.Input; } return input; } bool IsDerivedType(TypeSymbol possibleDerived, TypeSymbol possibleBase) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return this._conversions.HasIdentityOrImplicitReferenceConversion(possibleDerived, possibleBase, ref discardedUseSiteInfo); } private Tests MakeTestsAndBindingsForDeclarationPattern( BoundDagTemp input, BoundDeclarationPattern declaration, out BoundDagTemp output, ArrayBuilder<BoundPatternBinding> bindings) { TypeSymbol? type = declaration.DeclaredType?.Type; var tests = ArrayBuilder<Tests>.GetInstance(1); // Add a null and type test if needed. if (!declaration.IsVar) input = MakeConvertToType(input, declaration.Syntax, type!, isExplicitTest: false, tests); BoundExpression? variableAccess = declaration.VariableAccess; if (variableAccess is { }) { Debug.Assert(variableAccess.Type!.Equals(input.Type, TypeCompareKind.AllIgnoreOptions) || variableAccess.Type.IsErrorType()); bindings.Add(new BoundPatternBinding(variableAccess, input)); } else { RoslynDebug.Assert(declaration.Variable == null); } output = input; return Tests.AndSequence.Create(tests); } private Tests MakeTestsForTypePattern( BoundDagTemp input, BoundTypePattern typePattern, out BoundDagTemp output) { TypeSymbol type = typePattern.DeclaredType.Type; var tests = ArrayBuilder<Tests>.GetInstance(4); output = MakeConvertToType(input: input, syntax: typePattern.Syntax, type: type, isExplicitTest: typePattern.IsExplicitNotNullTest, tests: tests); return Tests.AndSequence.Create(tests); } private static void MakeCheckNotNull( BoundDagTemp input, SyntaxNode syntax, bool isExplicitTest, ArrayBuilder<Tests> tests) { // Add a null test if needed if (input.Type.CanContainNull()) tests.Add(new Tests.One(new BoundDagNonNullTest(syntax, isExplicitTest, input))); } /// <summary> /// Generate a not-null check and a type check. /// </summary> private BoundDagTemp MakeConvertToType( BoundDagTemp input, SyntaxNode syntax, TypeSymbol type, bool isExplicitTest, ArrayBuilder<Tests> tests) { MakeCheckNotNull(input, syntax, isExplicitTest, tests); if (!input.Type.Equals(type, TypeCompareKind.AllIgnoreOptions)) { TypeSymbol inputType = input.Type.StrippedType(); // since a null check has already been done var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(_diagnostics, _compilation.Assembly); Conversion conversion = _conversions.ClassifyBuiltInConversion(inputType, type, ref useSiteInfo); _diagnostics.Add(syntax, useSiteInfo); if (input.Type.IsDynamic() ? type.SpecialType == SpecialType.System_Object : conversion.IsImplicit) { // type test not needed, only the type cast } else { // both type test and cast needed tests.Add(new Tests.One(new BoundDagTypeTest(syntax, type, input))); } var evaluation = new BoundDagTypeEvaluation(syntax, type, input); input = new BoundDagTemp(syntax, type, evaluation); tests.Add(new Tests.One(evaluation)); } return input; } private Tests MakeTestsForConstantPattern( BoundDagTemp input, BoundConstantPattern constant, out BoundDagTemp output) { if (constant.ConstantValue == ConstantValue.Null) { output = input; return new Tests.One(new BoundDagExplicitNullTest(constant.Syntax, input)); } else { var tests = ArrayBuilder<Tests>.GetInstance(2); var convertedInput = MakeConvertToType(input, constant.Syntax, constant.Value.Type!, isExplicitTest: false, tests); output = convertedInput; tests.Add(new Tests.One(new BoundDagValueTest(constant.Syntax, constant.ConstantValue, convertedInput))); return Tests.AndSequence.Create(tests); } } private Tests MakeTestsAndBindingsForRecursivePattern( BoundDagTemp input, BoundRecursivePattern recursive, out BoundDagTemp output, ArrayBuilder<BoundPatternBinding> bindings) { RoslynDebug.Assert(input.Type.IsErrorType() || recursive.HasErrors || recursive.InputType.IsErrorType() || input.Type.Equals(recursive.InputType, TypeCompareKind.AllIgnoreOptions)); var inputType = recursive.DeclaredType?.Type ?? input.Type.StrippedType(); var tests = ArrayBuilder<Tests>.GetInstance(5); output = input = MakeConvertToType(input, recursive.Syntax, inputType, isExplicitTest: recursive.IsExplicitNotNullTest, tests); if (!recursive.Deconstruction.IsDefault) { // we have a "deconstruction" form, which is either an invocation of a Deconstruct method, or a disassembly of a tuple if (recursive.DeconstructMethod != null) { MethodSymbol method = recursive.DeconstructMethod; var evaluation = new BoundDagDeconstructEvaluation(recursive.Syntax, method, OriginalInput(input, method)); tests.Add(new Tests.One(evaluation)); int extensionExtra = method.IsStatic ? 1 : 0; int count = Math.Min(method.ParameterCount - extensionExtra, recursive.Deconstruction.Length); for (int i = 0; i < count; i++) { BoundPattern pattern = recursive.Deconstruction[i].Pattern; SyntaxNode syntax = pattern.Syntax; var element = new BoundDagTemp(syntax, method.Parameters[i + extensionExtra].Type, evaluation, i); tests.Add(MakeTestsAndBindings(element, pattern, bindings)); } } else if (Binder.IsZeroElementTupleType(inputType)) { // Work around https://github.com/dotnet/roslyn/issues/20648: The compiler's internal APIs such as `declType.IsTupleType` // do not correctly treat the non-generic struct `System.ValueTuple` as a tuple type. We explicitly perform the tests // required to identify it. When that bug is fixed we should be able to remove this if statement. // nothing to do, as there are no tests for the zero elements of this tuple } else if (inputType.IsTupleType) { ImmutableArray<FieldSymbol> elements = inputType.TupleElements; ImmutableArray<TypeWithAnnotations> elementTypes = inputType.TupleElementTypesWithAnnotations; int count = Math.Min(elementTypes.Length, recursive.Deconstruction.Length); for (int i = 0; i < count; i++) { BoundPattern pattern = recursive.Deconstruction[i].Pattern; SyntaxNode syntax = pattern.Syntax; FieldSymbol field = elements[i]; var evaluation = new BoundDagFieldEvaluation(syntax, field, OriginalInput(input, field)); // fetch the ItemN field tests.Add(new Tests.One(evaluation)); var element = new BoundDagTemp(syntax, field.Type, evaluation); tests.Add(MakeTestsAndBindings(element, pattern, bindings)); } } else { // This occurs in error cases. RoslynDebug.Assert(recursive.HasAnyErrors); // To prevent this pattern from subsuming other patterns and triggering a cascaded diagnostic, we add a test that will fail. tests.Add(new Tests.One(new BoundDagTypeTest(recursive.Syntax, ErrorType(), input, hasErrors: true))); } } if (!recursive.Properties.IsDefault) { // we have a "property" form foreach (var subpattern in recursive.Properties) { BoundPattern pattern = subpattern.Pattern; BoundDagTemp currentInput = input; if (!tryMakeSubpatternMemberTests(subpattern.Member, ref currentInput)) { Debug.Assert(recursive.HasAnyErrors); tests.Add(new Tests.One(new BoundDagTypeTest(recursive.Syntax, ErrorType(), input, hasErrors: true))); } tests.Add(MakeTestsAndBindings(currentInput, pattern, bindings)); } } if (recursive.VariableAccess != null) { // we have a "variable" declaration bindings.Add(new BoundPatternBinding(recursive.VariableAccess, input)); } return Tests.AndSequence.Create(tests); bool tryMakeSubpatternMemberTests([NotNullWhen(true)] BoundPropertySubpatternMember? member, ref BoundDagTemp input) { if (member is null) return false; if (tryMakeSubpatternMemberTests(member.Receiver, ref input)) { // If this is not the first member, add null test, unwrap nullables, and continue. input = MakeConvertToType(input, member.Syntax, member.Receiver.Type.StrippedType(), isExplicitTest: false, tests); } BoundDagEvaluation evaluation; switch (member.Symbol) { case PropertySymbol property: evaluation = new BoundDagPropertyEvaluation(member.Syntax, property, OriginalInput(input, property)); break; case FieldSymbol field: evaluation = new BoundDagFieldEvaluation(member.Syntax, field, OriginalInput(input, field)); break; default: return false; } tests.Add(new Tests.One(evaluation)); input = new BoundDagTemp(member.Syntax, member.Type, evaluation); return true; } } private Tests MakeTestsAndBindingsForNegatedPattern(BoundDagTemp input, BoundNegatedPattern neg, ArrayBuilder<BoundPatternBinding> bindings) { var tests = MakeTestsAndBindings(input, neg.Negated, bindings); return Tests.Not.Create(tests); } private Tests MakeTestsAndBindingsForBinaryPattern( BoundDagTemp input, BoundBinaryPattern bin, out BoundDagTemp output, ArrayBuilder<BoundPatternBinding> bindings) { var builder = ArrayBuilder<Tests>.GetInstance(2); if (bin.Disjunction) { builder.Add(MakeTestsAndBindings(input, bin.Left, bindings)); builder.Add(MakeTestsAndBindings(input, bin.Right, bindings)); var result = Tests.OrSequence.Create(builder); if (bin.InputType.Equals(bin.NarrowedType)) { output = input; return result; } else { builder = ArrayBuilder<Tests>.GetInstance(2); builder.Add(result); output = MakeConvertToType(input: input, syntax: bin.Syntax, type: bin.NarrowedType, isExplicitTest: false, tests: builder); return Tests.AndSequence.Create(builder); } } else { builder.Add(MakeTestsAndBindings(input, bin.Left, out var leftOutput, bindings)); builder.Add(MakeTestsAndBindings(leftOutput, bin.Right, out var rightOutput, bindings)); output = rightOutput; Debug.Assert(bin.HasErrors || output.Type.Equals(bin.NarrowedType, TypeCompareKind.AllIgnoreOptions)); return Tests.AndSequence.Create(builder); } } private Tests MakeTestsAndBindingsForRelationalPattern( BoundDagTemp input, BoundRelationalPattern rel, out BoundDagTemp output) { // check if the test is always true or always false var tests = ArrayBuilder<Tests>.GetInstance(2); output = MakeConvertToType(input, rel.Syntax, rel.Value.Type!, isExplicitTest: false, tests); var fac = ValueSetFactory.ForType(input.Type); var values = fac?.Related(rel.Relation.Operator(), rel.ConstantValue); if (values?.IsEmpty == true) { tests.Add(Tests.False.Instance); } else if (values?.Complement().IsEmpty != true) { tests.Add(new Tests.One(new BoundDagRelationalTest(rel.Syntax, rel.Relation, rel.ConstantValue, output, rel.HasErrors))); } return Tests.AndSequence.Create(tests); } private TypeSymbol ErrorType(string name = "") { return new ExtendedErrorTypeSymbol(this._compilation, name, arity: 0, errorInfo: null, unreported: false); } /// <summary> /// Compute and translate the decision dag, given a description of its initial state and a default /// decision when no decision appears to match. This implementation is nonrecursive to avoid /// overflowing the compiler's evaluation stack when compiling a large switch statement. /// </summary> private BoundDecisionDag MakeBoundDecisionDag(SyntaxNode syntax, ImmutableArray<StateForCase> cases) { // Build the state machine underlying the decision dag DecisionDag decisionDag = MakeDecisionDag(cases); // Note: It is useful for debugging the dag state table construction to set a breakpoint // here and view `decisionDag.Dump()`. ; // Compute the bound decision dag corresponding to each node of decisionDag, and store // it in node.Dag. var defaultDecision = new BoundLeafDecisionDagNode(syntax, _defaultLabel); ComputeBoundDecisionDagNodes(decisionDag, defaultDecision); var rootDecisionDagNode = decisionDag.RootNode.Dag; RoslynDebug.Assert(rootDecisionDagNode != null); var boundDecisionDag = new BoundDecisionDag(rootDecisionDagNode.Syntax, rootDecisionDagNode); #if DEBUG // Note that this uses the custom equality in `BoundDagEvaluation` // to make "equivalent" evaluation nodes share the same ID. var nextTempNumber = 0; var tempIdentifierMap = PooledDictionary<BoundDagEvaluation, int>.GetInstance(); var sortedBoundDagNodes = boundDecisionDag.TopologicallySortedNodes; for (int i = 0; i < sortedBoundDagNodes.Length; i++) { var node = sortedBoundDagNodes[i]; node.Id = i; switch (node) { case BoundEvaluationDecisionDagNode { Evaluation: { Id: -1 } evaluation }: evaluation.Id = tempIdentifier(evaluation); // Note that "equivalent" evaluations may be different object instances. // Therefore we have to dig into the Input.Source of evaluations and tests to set their IDs. if (evaluation.Input.Source is { Id: -1 } source) { source.Id = tempIdentifier(source); } break; case BoundTestDecisionDagNode { Test: var test }: if (test.Input.Source is { Id: -1 } testSource) { testSource.Id = tempIdentifier(testSource); } break; } } tempIdentifierMap.Free(); int tempIdentifier(BoundDagEvaluation e) { return tempIdentifierMap.TryGetValue(e, out int value) ? value : tempIdentifierMap[e] = ++nextTempNumber; } #endif return boundDecisionDag; } /// <summary> /// Make a <see cref="DecisionDag"/> (state machine) starting with the given set of cases in the root node, /// and return the node for the root. /// </summary> private DecisionDag MakeDecisionDag(ImmutableArray<StateForCase> casesForRootNode) { // A work list of DagStates whose successors need to be computed var workList = ArrayBuilder<DagState>.GetInstance(); // A mapping used to make each DagState unique (i.e. to de-dup identical states). var uniqueState = new Dictionary<DagState, DagState>(DagStateEquivalence.Instance); // We "intern" the states, so that we only have a single object representing one // semantic state. Because the decision automaton may contain states that have more than one // predecessor, we want to represent each such state as a reference-unique object // so that it is processed only once. This object identity uniqueness will be important later when we // start mutating the DagState nodes to compute successors and BoundDecisionDagNodes // for each one. That is why we have to use an equivalence relation in the dictionary `uniqueState`. DagState uniqifyState(ImmutableArray<StateForCase> cases, ImmutableDictionary<BoundDagTemp, IValueSet> remainingValues) { var state = new DagState(cases, remainingValues); if (uniqueState.TryGetValue(state, out DagState? existingState)) { // We found an existing state that matches. Update its set of possible remaining values // of each temp by taking the union of the sets on each incoming edge. var newRemainingValues = ImmutableDictionary.CreateBuilder<BoundDagTemp, IValueSet>(); foreach (var (dagTemp, valuesForTemp) in remainingValues) { // If one incoming edge does not have a set of possible values for the temp, // that means the temp can take on any value of its type. if (existingState.RemainingValues.TryGetValue(dagTemp, out var existingValuesForTemp)) { var newExistingValuesForTemp = existingValuesForTemp.Union(valuesForTemp); newRemainingValues.Add(dagTemp, newExistingValuesForTemp); } } if (existingState.RemainingValues.Count != newRemainingValues.Count || !existingState.RemainingValues.All(kv => newRemainingValues.TryGetValue(kv.Key, out IValueSet? values) && kv.Value.Equals(values))) { existingState.UpdateRemainingValues(newRemainingValues.ToImmutable()); if (!workList.Contains(existingState)) workList.Push(existingState); } return existingState; } else { // When we add a new unique state, we add it to a work list so that we // will process it to compute its successors. uniqueState.Add(state, state); workList.Push(state); return state; } } // Simplify the initial state based on impossible or earlier matched cases var rewrittenCases = ArrayBuilder<StateForCase>.GetInstance(casesForRootNode.Length); foreach (var state in casesForRootNode) { if (state.IsImpossible) continue; rewrittenCases.Add(state); if (state.IsFullyMatched) break; } var initialState = uniqifyState(rewrittenCases.ToImmutableAndFree(), ImmutableDictionary<BoundDagTemp, IValueSet>.Empty); // Go through the worklist of DagState nodes for which we have not yet computed // successor states. while (workList.Count != 0) { DagState state = workList.Pop(); RoslynDebug.Assert(state.SelectedTest == null); RoslynDebug.Assert(state.TrueBranch == null); RoslynDebug.Assert(state.FalseBranch == null); if (state.Cases.IsDefaultOrEmpty) { // If this state has no more cases that could possibly match, then // we know there is no case that will match and this node represents a "default" // decision. We do not need to compute a successor, as it is a leaf node continue; } StateForCase first = state.Cases[0]; Debug.Assert(!first.IsImpossible); if (first.PatternIsSatisfied) { if (first.IsFullyMatched) { // The first of the remaining cases has fully matched, as there are no more tests to do. // The language semantics of the switch statement and switch expression require that we // execute the first matching case. There is no when clause to evaluate here, // so this is a leaf node and required no further processing. } else { // There is a when clause to evaluate. // In case the when clause fails, we prepare for the remaining cases. var stateWhenFails = state.Cases.RemoveAt(0); state.FalseBranch = uniqifyState(stateWhenFails, state.RemainingValues); } } else { // Select the next test to do at this state, and compute successor states switch (state.SelectedTest = state.ComputeSelectedTest()) { case BoundDagEvaluation e: state.TrueBranch = uniqifyState(RemoveEvaluation(state.Cases, e), state.RemainingValues); // An evaluation is considered to always succeed, so there is no false branch break; case BoundDagTest d: bool foundExplicitNullTest = false; SplitCases( state.Cases, state.RemainingValues, d, out ImmutableArray<StateForCase> whenTrueDecisions, out ImmutableArray<StateForCase> whenFalseDecisions, out ImmutableDictionary<BoundDagTemp, IValueSet> whenTrueValues, out ImmutableDictionary<BoundDagTemp, IValueSet> whenFalseValues, ref foundExplicitNullTest); state.TrueBranch = uniqifyState(whenTrueDecisions, whenTrueValues); state.FalseBranch = uniqifyState(whenFalseDecisions, whenFalseValues); if (foundExplicitNullTest && d is BoundDagNonNullTest { IsExplicitTest: false } t) { // Turn an "implicit" non-null test into an explicit one state.SelectedTest = new BoundDagNonNullTest(t.Syntax, isExplicitTest: true, t.Input, t.HasErrors); } break; case var n: throw ExceptionUtilities.UnexpectedValue(n.Kind); } } } workList.Free(); return new DecisionDag(initialState); } /// <summary> /// Compute the <see cref="BoundDecisionDag"/> corresponding to each <see cref="DagState"/> of the given <see cref="DecisionDag"/> /// and store it in <see cref="DagState.Dag"/>. /// </summary> private void ComputeBoundDecisionDagNodes(DecisionDag decisionDag, BoundLeafDecisionDagNode defaultDecision) { Debug.Assert(_defaultLabel != null); Debug.Assert(defaultDecision != null); // Process the states in topological order, leaves first, and assign a BoundDecisionDag to each DagState. bool wasAcyclic = decisionDag.TryGetTopologicallySortedReachableStates(out ImmutableArray<DagState> sortedStates); if (!wasAcyclic) { // Since we intend the set of DagState nodes to be acyclic by construction, we do not expect // this to occur. Just in case it does due to bugs, we recover gracefully to avoid crashing the // compiler in production. If you find that this happens (the assert fails), please modify the // DagState construction process to avoid creating a cyclic state graph. Debug.Assert(wasAcyclic); // force failure in debug builds // If the dag contains a cycle, return a short-circuit dag instead. decisionDag.RootNode.Dag = defaultDecision; return; } // We "intern" the dag nodes, so that we only have a single object representing one // semantic node. We do this because different states may end up mapping to the same // set of successor states. In this case we merge them when producing the bound state machine. var uniqueNodes = PooledDictionary<BoundDecisionDagNode, BoundDecisionDagNode>.GetInstance(); BoundDecisionDagNode uniqifyDagNode(BoundDecisionDagNode node) => uniqueNodes.GetOrAdd(node, node); _ = uniqifyDagNode(defaultDecision); for (int i = sortedStates.Length - 1; i >= 0; i--) { var state = sortedStates[i]; if (state.Cases.IsDefaultOrEmpty) { state.Dag = defaultDecision; continue; } StateForCase first = state.Cases[0]; RoslynDebug.Assert(!(first.RemainingTests is Tests.False)); if (first.PatternIsSatisfied) { if (first.IsFullyMatched) { // there is no when clause we need to evaluate state.Dag = finalState(first.Syntax, first.CaseLabel, first.Bindings); } else { RoslynDebug.Assert(state.TrueBranch == null); RoslynDebug.Assert(state.FalseBranch is { }); // The final state here does not need bindings, as they will be performed before evaluating the when clause (see below) BoundDecisionDagNode whenTrue = finalState(first.Syntax, first.CaseLabel, default); BoundDecisionDagNode? whenFalse = state.FalseBranch.Dag; RoslynDebug.Assert(whenFalse is { }); state.Dag = uniqifyDagNode(new BoundWhenDecisionDagNode(first.Syntax, first.Bindings, first.WhenClause, whenTrue, whenFalse)); } BoundDecisionDagNode finalState(SyntaxNode syntax, LabelSymbol label, ImmutableArray<BoundPatternBinding> bindings) { BoundDecisionDagNode final = uniqifyDagNode(new BoundLeafDecisionDagNode(syntax, label)); return bindings.IsDefaultOrEmpty ? final : uniqifyDagNode(new BoundWhenDecisionDagNode(syntax, bindings, null, final, null)); } } else { switch (state.SelectedTest) { case BoundDagEvaluation e: { BoundDecisionDagNode? next = state.TrueBranch!.Dag; RoslynDebug.Assert(next is { }); RoslynDebug.Assert(state.FalseBranch == null); state.Dag = uniqifyDagNode(new BoundEvaluationDecisionDagNode(e.Syntax, e, next)); } break; case BoundDagTest d: { BoundDecisionDagNode? whenTrue = state.TrueBranch!.Dag; BoundDecisionDagNode? whenFalse = state.FalseBranch!.Dag; RoslynDebug.Assert(whenTrue is { }); RoslynDebug.Assert(whenFalse is { }); state.Dag = uniqifyDagNode(new BoundTestDecisionDagNode(d.Syntax, d, whenTrue, whenFalse)); } break; case var n: throw ExceptionUtilities.UnexpectedValue(n?.Kind); } } } uniqueNodes.Free(); } private void SplitCase( StateForCase stateForCase, BoundDagTest test, IValueSet? whenTrueValues, IValueSet? whenFalseValues, out StateForCase whenTrue, out StateForCase whenFalse, ref bool foundExplicitNullTest) { stateForCase.RemainingTests.Filter(this, test, whenTrueValues, whenFalseValues, out Tests whenTrueTests, out Tests whenFalseTests, ref foundExplicitNullTest); whenTrue = makeNext(whenTrueTests); whenFalse = makeNext(whenFalseTests); return; StateForCase makeNext(Tests remainingTests) { return remainingTests.Equals(stateForCase.RemainingTests) ? stateForCase : new StateForCase( stateForCase.Index, stateForCase.Syntax, remainingTests, stateForCase.Bindings, stateForCase.WhenClause, stateForCase.CaseLabel); } } private void SplitCases( ImmutableArray<StateForCase> statesForCases, ImmutableDictionary<BoundDagTemp, IValueSet> values, BoundDagTest test, out ImmutableArray<StateForCase> whenTrue, out ImmutableArray<StateForCase> whenFalse, out ImmutableDictionary<BoundDagTemp, IValueSet> whenTrueValues, out ImmutableDictionary<BoundDagTemp, IValueSet> whenFalseValues, ref bool foundExplicitNullTest) { var whenTrueBuilder = ArrayBuilder<StateForCase>.GetInstance(statesForCases.Length); var whenFalseBuilder = ArrayBuilder<StateForCase>.GetInstance(statesForCases.Length); bool whenTruePossible, whenFalsePossible; (whenTrueValues, whenFalseValues, whenTruePossible, whenFalsePossible) = SplitValues(values, test); // whenTruePossible means the test could possibly have succeeded. whenFalsePossible means it could possibly have failed. // Tests that are either impossible or tautological (i.e. either of these false) given // the set of values are normally removed and replaced by the known result, so we would not normally be processing // a test that always succeeds or always fails, but they can occur in erroneous programs (e.g. testing for equality // against a non-constant value). foreach (var state in statesForCases) { SplitCase( state, test, whenTrueValues.TryGetValue(test.Input, out var v1) ? v1 : null, whenFalseValues.TryGetValue(test.Input, out var v2) ? v2 : null, out var whenTrueState, out var whenFalseState, ref foundExplicitNullTest); // whenTrueState.IsImpossible occurs when Split results in a state for a given case where the case has been ruled // out (because its test has failed). If not whenTruePossible, we don't want to add anything to the state. In // either case, we do not want to add the current case to the state. if (whenTruePossible && !whenTrueState.IsImpossible && !(whenTrueBuilder.Any() && whenTrueBuilder.Last().IsFullyMatched)) whenTrueBuilder.Add(whenTrueState); // Similarly for the alternative state. if (whenFalsePossible && !whenFalseState.IsImpossible && !(whenFalseBuilder.Any() && whenFalseBuilder.Last().IsFullyMatched)) whenFalseBuilder.Add(whenFalseState); } whenTrue = whenTrueBuilder.ToImmutableAndFree(); whenFalse = whenFalseBuilder.ToImmutableAndFree(); } private static ( ImmutableDictionary<BoundDagTemp, IValueSet> whenTrueValues, ImmutableDictionary<BoundDagTemp, IValueSet> whenFalseValues, bool truePossible, bool falsePossible) SplitValues( ImmutableDictionary<BoundDagTemp, IValueSet> values, BoundDagTest test) { switch (test) { case BoundDagEvaluation _: case BoundDagExplicitNullTest _: case BoundDagNonNullTest _: case BoundDagTypeTest _: return (values, values, true, true); case BoundDagValueTest t: return resultForRelation(BinaryOperatorKind.Equal, t.Value); case BoundDagRelationalTest t: return resultForRelation(t.Relation, t.Value); default: throw ExceptionUtilities.UnexpectedValue(test); } ( ImmutableDictionary<BoundDagTemp, IValueSet> whenTrueValues, ImmutableDictionary<BoundDagTemp, IValueSet> whenFalseValues, bool truePossible, bool falsePossible) resultForRelation(BinaryOperatorKind relation, ConstantValue value) { var input = test.Input; IValueSetFactory? valueFac = ValueSetFactory.ForType(input.Type); if (valueFac == null || value.IsBad) { // If it is a type we don't track yet, assume all values are possible return (values, values, true, true); } IValueSet fromTestPassing = valueFac.Related(relation.Operator(), value); IValueSet fromTestFailing = fromTestPassing.Complement(); if (values.TryGetValue(test.Input, out IValueSet? tempValuesBeforeTest)) { fromTestPassing = fromTestPassing.Intersect(tempValuesBeforeTest); fromTestFailing = fromTestFailing.Intersect(tempValuesBeforeTest); } var whenTrueValues = values.SetItem(input, fromTestPassing); var whenFalseValues = values.SetItem(input, fromTestFailing); return (whenTrueValues, whenFalseValues, !fromTestPassing.IsEmpty, !fromTestFailing.IsEmpty); } } private static ImmutableArray<StateForCase> RemoveEvaluation(ImmutableArray<StateForCase> cases, BoundDagEvaluation e) { var builder = ArrayBuilder<StateForCase>.GetInstance(cases.Length); foreach (var stateForCase in cases) { var remainingTests = stateForCase.RemainingTests.RemoveEvaluation(e); if (remainingTests is Tests.False) { // This can occur in error cases like `e is not int x` where there is a trailing evaluation // in a failure branch. } else { builder.Add(new StateForCase( Index: stateForCase.Index, Syntax: stateForCase.Syntax, RemainingTests: remainingTests, Bindings: stateForCase.Bindings, WhenClause: stateForCase.WhenClause, CaseLabel: stateForCase.CaseLabel)); } } return builder.ToImmutableAndFree(); } /// <summary> /// Given that the test <paramref name="test"/> has occurred and produced a true/false result, /// set some flags indicating the implied status of the <paramref name="other"/> test. /// </summary> /// <param name="test"></param> /// <param name="other"></param> /// <param name="whenTrueValues">The possible values of test.Input when <paramref name="test"/> has succeeded.</param> /// <param name="whenFalseValues">The possible values of test.Input when <paramref name="test"/> has failed.</param> /// <param name="trueTestPermitsTrueOther">set if <paramref name="test"/> being true would permit <paramref name="other"/> to succeed</param> /// <param name="falseTestPermitsTrueOther">set if a false result on <paramref name="test"/> would permit <paramref name="other"/> to succeed</param> /// <param name="trueTestImpliesTrueOther">set if <paramref name="test"/> being true means <paramref name="other"/> has been proven true</param> /// <param name="falseTestImpliesTrueOther">set if <paramref name="test"/> being false means <paramref name="other"/> has been proven true</param> private void CheckConsistentDecision( BoundDagTest test, BoundDagTest other, IValueSet? whenTrueValues, IValueSet? whenFalseValues, SyntaxNode syntax, out bool trueTestPermitsTrueOther, out bool falseTestPermitsTrueOther, out bool trueTestImpliesTrueOther, out bool falseTestImpliesTrueOther, ref bool foundExplicitNullTest) { // innocent until proven guilty trueTestPermitsTrueOther = true; falseTestPermitsTrueOther = true; trueTestImpliesTrueOther = false; falseTestImpliesTrueOther = false; // if the tests are for unrelated things, there is no implication from one to the other if (!test.Input.Equals(other.Input)) return; switch (test) { case BoundDagNonNullTest _: switch (other) { case BoundDagValueTest _: // !(v != null) --> !(v == K) falseTestPermitsTrueOther = false; break; case BoundDagExplicitNullTest _: foundExplicitNullTest = true; // v != null --> !(v == null) trueTestPermitsTrueOther = false; // !(v != null) --> v == null falseTestImpliesTrueOther = true; break; case BoundDagNonNullTest n2: if (n2.IsExplicitTest) foundExplicitNullTest = true; // v != null --> v != null trueTestImpliesTrueOther = true; // !(v != null) --> !(v != null) falseTestPermitsTrueOther = false; break; default: // !(v != null) --> !(v is T) falseTestPermitsTrueOther = false; break; } break; case BoundDagTypeTest t1: switch (other) { case BoundDagNonNullTest n2: if (n2.IsExplicitTest) foundExplicitNullTest = true; // v is T --> v != null trueTestImpliesTrueOther = true; break; case BoundDagTypeTest t2: { var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(_diagnostics, _compilation.Assembly); bool? matches = ExpressionOfTypeMatchesPatternTypeForLearningFromSuccessfulTypeTest(t1.Type, t2.Type, ref useSiteInfo); if (matches == false) { // If T1 could never be T2 // v is T1 --> !(v is T2) trueTestPermitsTrueOther = false; } else if (matches == true) { // If T1: T2 // v is T1 --> v is T2 trueTestImpliesTrueOther = true; } // If every T2 is a T1, then failure of T1 implies failure of T2. matches = Binder.ExpressionOfTypeMatchesPatternType(_conversions, t2.Type, t1.Type, ref useSiteInfo, out _); _diagnostics.Add(syntax, useSiteInfo); if (matches == true) { // If T2: T1 // !(v is T1) --> !(v is T2) falseTestPermitsTrueOther = false; } } break; case BoundDagValueTest _: break; case BoundDagExplicitNullTest _: foundExplicitNullTest = true; // v is T --> !(v == null) trueTestPermitsTrueOther = false; break; } break; case BoundDagValueTest _: case BoundDagRelationalTest _: switch (other) { case BoundDagNonNullTest n2: if (n2.IsExplicitTest) foundExplicitNullTest = true; // v == K --> v != null trueTestImpliesTrueOther = true; break; case BoundDagTypeTest _: break; case BoundDagExplicitNullTest _: foundExplicitNullTest = true; // v == K --> !(v == null) trueTestPermitsTrueOther = false; break; case BoundDagRelationalTest r2: handleRelationWithValue(r2.Relation, r2.Value, out trueTestPermitsTrueOther, out falseTestPermitsTrueOther, out trueTestImpliesTrueOther, out falseTestImpliesTrueOther); break; case BoundDagValueTest v2: handleRelationWithValue(BinaryOperatorKind.Equal, v2.Value, out trueTestPermitsTrueOther, out falseTestPermitsTrueOther, out trueTestImpliesTrueOther, out falseTestImpliesTrueOther); break; void handleRelationWithValue( BinaryOperatorKind relation, ConstantValue value, out bool trueTestPermitsTrueOther, out bool falseTestPermitsTrueOther, out bool trueTestImpliesTrueOther, out bool falseTestImpliesTrueOther) { // We check test.Equals(other) to handle "bad" constant values bool sameTest = test.Equals(other); trueTestPermitsTrueOther = whenTrueValues?.Any(relation, value) ?? true; trueTestImpliesTrueOther = sameTest || trueTestPermitsTrueOther && (whenTrueValues?.All(relation, value) ?? false); falseTestPermitsTrueOther = !sameTest && (whenFalseValues?.Any(relation, value) ?? true); falseTestImpliesTrueOther = falseTestPermitsTrueOther && (whenFalseValues?.All(relation, value) ?? false); } } break; case BoundDagExplicitNullTest _: foundExplicitNullTest = true; switch (other) { case BoundDagNonNullTest n2: if (n2.IsExplicitTest) foundExplicitNullTest = true; // v == null --> !(v != null) trueTestPermitsTrueOther = false; // !(v == null) --> v != null falseTestImpliesTrueOther = true; break; case BoundDagTypeTest _: // v == null --> !(v is T) trueTestPermitsTrueOther = false; break; case BoundDagExplicitNullTest _: foundExplicitNullTest = true; // v == null --> v == null trueTestImpliesTrueOther = true; // !(v == null) --> !(v == null) falseTestPermitsTrueOther = false; break; case BoundDagValueTest _: // v == null --> !(v == K) trueTestPermitsTrueOther = false; break; } break; } } /// <summary> /// Determine what we can learn from one successful runtime type test about another planned /// runtime type test for the purpose of building the decision tree. /// We accommodate a special behavior of the runtime here, which does not match the language rules. /// A value of type `int[]` is an "instanceof" (i.e. result of the `isinst` instruction) the type /// `uint[]` and vice versa. It is similarly so for every pair of same-sized numeric types, and /// arrays of enums are considered to be their underlying type. We need the dag construction to /// recognize this runtime behavior, so we pretend that matching one of them gives no information /// on whether the other will be matched. That isn't quite correct (nothing reasonable we do /// could be), but it comes closest to preserving the existing C#7 behavior without undesirable /// side-effects, and permits the code-gen strategy to preserve the dynamic semantic equivalence /// of a switch (on the one hand) and a series of if-then-else statements (on the other). /// See, for example, https://github.com/dotnet/roslyn/issues/35661 /// </summary> private bool? ExpressionOfTypeMatchesPatternTypeForLearningFromSuccessfulTypeTest( TypeSymbol expressionType, TypeSymbol patternType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { bool? result = Binder.ExpressionOfTypeMatchesPatternType(_conversions, expressionType, patternType, ref useSiteInfo, out Conversion conversion); return (!conversion.Exists && isRuntimeSimilar(expressionType, patternType)) ? null // runtime and compile-time test behavior differ. Pretend we don't know what happens. : result; static bool isRuntimeSimilar(TypeSymbol expressionType, TypeSymbol patternType) { while (expressionType is ArrayTypeSymbol { ElementType: var e1, IsSZArray: var sz1, Rank: var r1 } && patternType is ArrayTypeSymbol { ElementType: var e2, IsSZArray: var sz2, Rank: var r2 } && sz1 == sz2 && r1 == r2) { e1 = e1.EnumUnderlyingTypeOrSelf(); e2 = e2.EnumUnderlyingTypeOrSelf(); switch (e1.SpecialType, e2.SpecialType) { // The following support CLR behavior that is required by // the CLI specification but violates the C# language behavior. // See ECMA-335's definition of *array-element-compatible-with*. case var (s1, s2) when s1 == s2: case (SpecialType.System_SByte, SpecialType.System_Byte): case (SpecialType.System_Byte, SpecialType.System_SByte): case (SpecialType.System_Int16, SpecialType.System_UInt16): case (SpecialType.System_UInt16, SpecialType.System_Int16): case (SpecialType.System_Int32, SpecialType.System_UInt32): case (SpecialType.System_UInt32, SpecialType.System_Int32): case (SpecialType.System_Int64, SpecialType.System_UInt64): case (SpecialType.System_UInt64, SpecialType.System_Int64): case (SpecialType.System_IntPtr, SpecialType.System_UIntPtr): case (SpecialType.System_UIntPtr, SpecialType.System_IntPtr): // The following support behavior of the CLR that violates the CLI // and C# specifications, but we implement them because that is the // behavior on 32-bit runtimes. case (SpecialType.System_Int32, SpecialType.System_IntPtr): case (SpecialType.System_Int32, SpecialType.System_UIntPtr): case (SpecialType.System_UInt32, SpecialType.System_IntPtr): case (SpecialType.System_UInt32, SpecialType.System_UIntPtr): case (SpecialType.System_IntPtr, SpecialType.System_Int32): case (SpecialType.System_IntPtr, SpecialType.System_UInt32): case (SpecialType.System_UIntPtr, SpecialType.System_Int32): case (SpecialType.System_UIntPtr, SpecialType.System_UInt32): // The following support behavior of the CLR that violates the CLI // and C# specifications, but we implement them because that is the // behavior on 64-bit runtimes. case (SpecialType.System_Int64, SpecialType.System_IntPtr): case (SpecialType.System_Int64, SpecialType.System_UIntPtr): case (SpecialType.System_UInt64, SpecialType.System_IntPtr): case (SpecialType.System_UInt64, SpecialType.System_UIntPtr): case (SpecialType.System_IntPtr, SpecialType.System_Int64): case (SpecialType.System_IntPtr, SpecialType.System_UInt64): case (SpecialType.System_UIntPtr, SpecialType.System_Int64): case (SpecialType.System_UIntPtr, SpecialType.System_UInt64): return true; default: (expressionType, patternType) = (e1, e2); break; } } return false; } } /// <summary> /// A representation of the entire decision dag and each of its states. /// </summary> private sealed class DecisionDag { /// <summary> /// The starting point for deciding which case matches. /// </summary> public readonly DagState RootNode; public DecisionDag(DagState rootNode) { this.RootNode = rootNode; } /// <summary> /// A successor function used to topologically sort the DagState set. /// </summary> private static ImmutableArray<DagState> Successor(DagState state) { if (state.TrueBranch != null && state.FalseBranch != null) { return ImmutableArray.Create(state.FalseBranch, state.TrueBranch); } else if (state.TrueBranch != null) { return ImmutableArray.Create(state.TrueBranch); } else if (state.FalseBranch != null) { return ImmutableArray.Create(state.FalseBranch); } else { return ImmutableArray<DagState>.Empty; } } /// <summary> /// Produce the states in topological order. /// </summary> /// <param name="result">Topologically sorted <see cref="DagState"/> nodes.</param> /// <returns>True if the graph was acyclic.</returns> public bool TryGetTopologicallySortedReachableStates(out ImmutableArray<DagState> result) { return TopologicalSort.TryIterativeSort<DagState>(SpecializedCollections.SingletonEnumerable<DagState>(this.RootNode), Successor, out result); } #if DEBUG /// <summary> /// Starting with `this` state, produce a human-readable description of the state tables. /// This is very useful for debugging and optimizing the dag state construction. /// </summary> internal string Dump() { if (!this.TryGetTopologicallySortedReachableStates(out var allStates)) { return "(the dag contains a cycle!)"; } var stateIdentifierMap = PooledDictionary<DagState, int>.GetInstance(); for (int i = 0; i < allStates.Length; i++) { stateIdentifierMap.Add(allStates[i], i); } // NOTE that this numbering for temps does not work well for the invocation of Deconstruct, which produces // multiple values. This would make them appear to be the same temp in the debug dump. int nextTempNumber = 0; PooledDictionary<BoundDagEvaluation, int> tempIdentifierMap = PooledDictionary<BoundDagEvaluation, int>.GetInstance(); int tempIdentifier(BoundDagEvaluation? e) { return (e == null) ? 0 : tempIdentifierMap.TryGetValue(e, out int value) ? value : tempIdentifierMap[e] = ++nextTempNumber; } string tempName(BoundDagTemp t) { return $"t{tempIdentifier(t.Source)}"; } var resultBuilder = PooledStringBuilder.GetInstance(); var result = resultBuilder.Builder; foreach (DagState state in allStates) { bool isFail = state.Cases.IsEmpty; bool starred = isFail || state.Cases.First().PatternIsSatisfied; result.Append($"{(starred ? "*" : "")}State " + stateIdentifierMap[state] + (isFail ? " FAIL" : "")); var remainingValues = state.RemainingValues.Select(kvp => $"{tempName(kvp.Key)}:{kvp.Value}"); result.AppendLine($"{(remainingValues.Any() ? " REMAINING " + string.Join(" ", remainingValues) : "")}"); foreach (StateForCase cd in state.Cases) { result.AppendLine($" {dumpStateForCase(cd)}"); } if (state.SelectedTest != null) { result.AppendLine($" Test: {dumpDagTest(state.SelectedTest)}"); } if (state.TrueBranch != null) { result.AppendLine($" TrueBranch: {stateIdentifierMap[state.TrueBranch]}"); } if (state.FalseBranch != null) { result.AppendLine($" FalseBranch: {stateIdentifierMap[state.FalseBranch]}"); } } stateIdentifierMap.Free(); tempIdentifierMap.Free(); return resultBuilder.ToStringAndFree(); string dumpStateForCase(StateForCase cd) { var instance = PooledStringBuilder.GetInstance(); StringBuilder builder = instance.Builder; builder.Append($"{cd.Index}. [{cd.Syntax}] {(cd.PatternIsSatisfied ? "MATCH" : cd.RemainingTests.Dump(dumpDagTest))}"); var bindings = cd.Bindings.Select(bpb => $"{(bpb.VariableAccess is BoundLocal l ? l.LocalSymbol.Name : "<var>")}={tempName(bpb.TempContainingValue)}"); if (bindings.Any()) { builder.Append(" BIND["); builder.Append(string.Join("; ", bindings)); builder.Append("]"); } if (cd.WhenClause is { }) { builder.Append($" WHEN[{cd.WhenClause.Syntax}]"); } return instance.ToStringAndFree(); } string dumpDagTest(BoundDagTest d) { switch (d) { case BoundDagTypeEvaluation a: return $"t{tempIdentifier(a)}={a.Kind}({tempName(a.Input)} as {a.Type})"; case BoundDagFieldEvaluation e: return $"t{tempIdentifier(e)}={e.Kind}({tempName(e.Input)}.{e.Field.Name})"; case BoundDagPropertyEvaluation e: return $"t{tempIdentifier(e)}={e.Kind}({tempName(e.Input)}.{e.Property.Name})"; case BoundDagEvaluation e: return $"t{tempIdentifier(e)}={e.Kind}({tempName(e.Input)})"; case BoundDagTypeTest b: return $"?{d.Kind}({tempName(d.Input)} is {b.Type})"; case BoundDagValueTest v: return $"?{d.Kind}({tempName(d.Input)} == {v.Value})"; case BoundDagRelationalTest r: var operatorName = r.Relation.Operator() switch { BinaryOperatorKind.LessThan => "<", BinaryOperatorKind.LessThanOrEqual => "<=", BinaryOperatorKind.GreaterThan => ">", BinaryOperatorKind.GreaterThanOrEqual => ">=", _ => "??" }; return $"?{d.Kind}({tempName(d.Input)} {operatorName} {r.Value})"; default: return $"?{d.Kind}({tempName(d.Input)})"; } } } #endif } /// <summary> /// The state at a given node of the decision finite state automaton. This is used during computation of the state /// machine (<see cref="BoundDecisionDag"/>), and contains a representation of the meaning of the state. Because we always make /// forward progress when a test is evaluated (the state description is monotonically smaller at each edge), the /// graph of states is acyclic, which is why we call it a dag (directed acyclic graph). /// </summary> private sealed class DagState { /// <summary> /// For each dag temp of a type for which we track such things (the integral types, floating-point types, and bool), /// the possible values it can take on when control reaches this state. /// If this dictionary is mutated after <see cref="TrueBranch"/>, <see cref="FalseBranch"/>, /// and <see cref="Dag"/> are computed (for example to merge states), they must be cleared and recomputed, /// as the set of possible values can affect successor states. /// A <see cref="BoundDagTemp"/> absent from this dictionary means that all values of the type are possible. /// </summary> public ImmutableDictionary<BoundDagTemp, IValueSet> RemainingValues { get; private set; } /// <summary> /// The set of cases that may still match, and for each of them the set of tests that remain to be tested. /// </summary> public readonly ImmutableArray<StateForCase> Cases; public DagState(ImmutableArray<StateForCase> cases, ImmutableDictionary<BoundDagTemp, IValueSet> remainingValues) { this.Cases = cases; this.RemainingValues = remainingValues; } // If not a leaf node or a when clause, the test that will be taken at this node of the // decision automaton. public BoundDagTest? SelectedTest; // We only compute the dag states for the branches after we de-dup this DagState itself. // If all that remains is the `when` clauses, SelectedDecision is left `null` (we can // build the leaf node easily during translation) and the FalseBranch field is populated // with the successor on failure of the when clause (if one exists). public DagState? TrueBranch, FalseBranch; // After the entire graph of DagState objects is complete, we translate each into its Dag node. public BoundDecisionDagNode? Dag; /// <summary> /// Decide on what test to use at this node of the decision dag. This is the principal /// heuristic we can change to adjust the quality of the generated decision automaton. /// See https://www.cs.tufts.edu/~nr/cs257/archive/norman-ramsey/match.pdf for some ideas. /// </summary> internal BoundDagTest ComputeSelectedTest() { return Cases[0].RemainingTests.ComputeSelectedTest(); } internal void UpdateRemainingValues(ImmutableDictionary<BoundDagTemp, IValueSet> newRemainingValues) { this.RemainingValues = newRemainingValues; this.SelectedTest = null; this.TrueBranch = null; this.FalseBranch = null; } } /// <summary> /// An equivalence relation between dag states used to dedup the states during dag construction. /// After dag construction is complete we treat a DagState as using object equality as equivalent /// states have been merged. /// </summary> private sealed class DagStateEquivalence : IEqualityComparer<DagState> { public static readonly DagStateEquivalence Instance = new DagStateEquivalence(); private DagStateEquivalence() { } public bool Equals(DagState? x, DagState? y) { RoslynDebug.Assert(x is { }); RoslynDebug.Assert(y is { }); return x == y || x.Cases.SequenceEqual(y.Cases, (a, b) => a.Equals(b)); } public int GetHashCode(DagState x) { return Hash.Combine(Hash.CombineValues(x.Cases), x.Cases.Length); } } /// <summary> /// As part of the description of a node of the decision automaton, we keep track of what tests /// remain to be done for each case. /// </summary> private sealed class StateForCase { /// <summary> /// A number that is distinct for each case and monotonically increasing from earlier to later cases. /// Since we always keep the cases in order, this is only used to assist with debugging (e.g. /// see DecisionDag.Dump()). /// </summary> public readonly int Index; public readonly SyntaxNode Syntax; public readonly Tests RemainingTests; public readonly ImmutableArray<BoundPatternBinding> Bindings; public readonly BoundExpression? WhenClause; public readonly LabelSymbol CaseLabel; public StateForCase( int Index, SyntaxNode Syntax, Tests RemainingTests, ImmutableArray<BoundPatternBinding> Bindings, BoundExpression? WhenClause, LabelSymbol CaseLabel) { this.Index = Index; this.Syntax = Syntax; this.RemainingTests = RemainingTests; this.Bindings = Bindings; this.WhenClause = WhenClause; this.CaseLabel = CaseLabel; } /// <summary> /// Is the pattern in a state in which it is fully matched and there is no when clause? /// </summary> public bool IsFullyMatched => RemainingTests is Tests.True && (WhenClause is null || WhenClause.ConstantValue == ConstantValue.True); /// <summary> /// Is the pattern fully matched and ready for the when clause to be evaluated (if any)? /// </summary> public bool PatternIsSatisfied => RemainingTests is Tests.True; /// <summary> /// Is the clause impossible? We do not consider a when clause with a constant false value to cause the branch to be impossible. /// Note that we do not include the possibility that a when clause is the constant false. That is treated like any other expression. /// </summary> public bool IsImpossible => RemainingTests is Tests.False; public override bool Equals(object? obj) { throw ExceptionUtilities.Unreachable; } public bool Equals(StateForCase other) { // We do not include Syntax, Bindings, WhereClause, or CaseLabel // because once the Index is the same, those must be the same too. return this == other || other != null && this.Index == other.Index && this.RemainingTests.Equals(other.RemainingTests); } public override int GetHashCode() { return Hash.Combine(RemainingTests.GetHashCode(), Index); } } /// <summary> /// A set of tests to be performed. This is a discriminated union; see the options (nested types) for more details. /// </summary> private abstract class Tests { private Tests() { } /// <summary> /// Take the set of tests and split them into two, one for when the test has succeeded, and one for when the test has failed. /// </summary> public abstract void Filter( DecisionDagBuilder builder, BoundDagTest test, IValueSet? whenTrueValues, IValueSet? whenFalseValues, out Tests whenTrue, out Tests whenFalse, ref bool foundExplicitNullTest); public virtual BoundDagTest ComputeSelectedTest() => throw ExceptionUtilities.Unreachable; public virtual Tests RemoveEvaluation(BoundDagEvaluation e) => this; public abstract string Dump(Func<BoundDagTest, string> dump); /// <summary> /// No tests to be performed; the result is true (success). /// </summary> public sealed class True : Tests { public static readonly True Instance = new True(); public override string Dump(Func<BoundDagTest, string> dump) => "TRUE"; public override void Filter( DecisionDagBuilder builder, BoundDagTest test, IValueSet? whenTrueValues, IValueSet? whenFalseValues, out Tests whenTrue, out Tests whenFalse, ref bool foundExplicitNullTest) { whenTrue = whenFalse = this; } } /// <summary> /// No tests to be performed; the result is false (failure). /// </summary> public sealed class False : Tests { public static readonly False Instance = new False(); public override string Dump(Func<BoundDagTest, string> dump) => "FALSE"; public override void Filter( DecisionDagBuilder builder, BoundDagTest test, IValueSet? whenTrueValues, IValueSet? whenFalseValues, out Tests whenTrue, out Tests whenFalse, ref bool foundExplicitNullTest) { whenTrue = whenFalse = this; } } /// <summary> /// A single test to be performed, described by a <see cref="BoundDagTest"/>. /// Note that the test might be a <see cref="BoundDagEvaluation"/>, in which case it is deemed to have /// succeeded after being evaluated. /// </summary> public sealed class One : Tests { public readonly BoundDagTest Test; public One(BoundDagTest test) => this.Test = test; public void Deconstruct(out BoundDagTest Test) => Test = this.Test; public override void Filter( DecisionDagBuilder builder, BoundDagTest test, IValueSet? whenTrueValues, IValueSet? whenFalseValues, out Tests whenTrue, out Tests whenFalse, ref bool foundExplicitNullTest) { builder.CheckConsistentDecision( test: test, other: Test, whenTrueValues: whenTrueValues, whenFalseValues: whenFalseValues, syntax: test.Syntax, trueTestPermitsTrueOther: out bool trueDecisionPermitsTrueOther, falseTestPermitsTrueOther: out bool falseDecisionPermitsTrueOther, trueTestImpliesTrueOther: out bool trueDecisionImpliesTrueOther, falseTestImpliesTrueOther: out bool falseDecisionImpliesTrueOther, foundExplicitNullTest: ref foundExplicitNullTest); whenTrue = trueDecisionImpliesTrueOther ? Tests.True.Instance : trueDecisionPermitsTrueOther ? this : (Tests)Tests.False.Instance; whenFalse = falseDecisionImpliesTrueOther ? Tests.True.Instance : falseDecisionPermitsTrueOther ? this : (Tests)Tests.False.Instance; } public override BoundDagTest ComputeSelectedTest() => this.Test; public override Tests RemoveEvaluation(BoundDagEvaluation e) => e.Equals(Test) ? Tests.True.Instance : (Tests)this; public override string Dump(Func<BoundDagTest, string> dump) => dump(this.Test); public override bool Equals(object? obj) => this == obj || obj is One other && this.Test.Equals(other.Test); public override int GetHashCode() => this.Test.GetHashCode(); } public sealed class Not : Tests { // Negation is pushed to the level of a single test by demorgan's laws public readonly Tests Negated; private Not(Tests negated) => Negated = negated; public static Tests Create(Tests negated) => negated switch { Tests.True _ => Tests.False.Instance, Tests.False _ => Tests.True.Instance, Tests.Not n => n.Negated, // double negative Tests.AndSequence a => new Not(a), Tests.OrSequence a => Tests.AndSequence.Create(NegateSequenceElements(a.RemainingTests)), // use demorgan to prefer and sequences Tests.One o => new Not(o), _ => throw ExceptionUtilities.UnexpectedValue(negated), }; private static ArrayBuilder<Tests> NegateSequenceElements(ImmutableArray<Tests> seq) { var builder = ArrayBuilder<Tests>.GetInstance(seq.Length); foreach (var t in seq) builder.Add(Not.Create(t)); return builder; } public override Tests RemoveEvaluation(BoundDagEvaluation e) => Create(Negated.RemoveEvaluation(e)); public override BoundDagTest ComputeSelectedTest() => Negated.ComputeSelectedTest(); public override string Dump(Func<BoundDagTest, string> dump) => $"Not ({Negated.Dump(dump)})"; public override void Filter( DecisionDagBuilder builder, BoundDagTest test, IValueSet? whenTrueValues, IValueSet? whenFalseValues, out Tests whenTrue, out Tests whenFalse, ref bool foundExplicitNullTest) { Negated.Filter(builder, test, whenTrueValues, whenFalseValues, out var whenTestTrue, out var whenTestFalse, ref foundExplicitNullTest); whenTrue = Not.Create(whenTestTrue); whenFalse = Not.Create(whenTestFalse); } public override bool Equals(object? obj) => this == obj || obj is Not n && Negated.Equals(n.Negated); public override int GetHashCode() => Hash.Combine(Negated.GetHashCode(), typeof(Not).GetHashCode()); } public abstract class SequenceTests : Tests { public readonly ImmutableArray<Tests> RemainingTests; protected SequenceTests(ImmutableArray<Tests> remainingTests) { Debug.Assert(remainingTests.Length > 1); this.RemainingTests = remainingTests; } public abstract Tests Update(ArrayBuilder<Tests> remainingTests); public override void Filter( DecisionDagBuilder builder, BoundDagTest test, IValueSet? whenTrueValues, IValueSet? whenFalseValues, out Tests whenTrue, out Tests whenFalse, ref bool foundExplicitNullTest) { var trueBuilder = ArrayBuilder<Tests>.GetInstance(RemainingTests.Length); var falseBuilder = ArrayBuilder<Tests>.GetInstance(RemainingTests.Length); foreach (var other in RemainingTests) { other.Filter(builder, test, whenTrueValues, whenFalseValues, out Tests oneTrue, out Tests oneFalse, ref foundExplicitNullTest); trueBuilder.Add(oneTrue); falseBuilder.Add(oneFalse); } whenTrue = Update(trueBuilder); whenFalse = Update(falseBuilder); } public override Tests RemoveEvaluation(BoundDagEvaluation e) { var builder = ArrayBuilder<Tests>.GetInstance(RemainingTests.Length); foreach (var test in RemainingTests) builder.Add(test.RemoveEvaluation(e)); return Update(builder); } public override bool Equals(object? obj) => this == obj || obj is SequenceTests other && this.GetType() == other.GetType() && RemainingTests.SequenceEqual(other.RemainingTests); public override int GetHashCode() { int length = this.RemainingTests.Length; int value = Hash.Combine(length, this.GetType().GetHashCode()); value = Hash.Combine(Hash.CombineValues(this.RemainingTests), value); return value; } } /// <summary> /// A sequence of tests that must be performed, each of which must succeed. /// The sequence is deemed to succeed if no element fails. /// </summary> public sealed class AndSequence : SequenceTests { private AndSequence(ImmutableArray<Tests> remainingTests) : base(remainingTests) { } public override Tests Update(ArrayBuilder<Tests> remainingTests) => Create(remainingTests); public static Tests Create(ArrayBuilder<Tests> remainingTests) { for (int i = remainingTests.Count - 1; i >= 0; i--) { switch (remainingTests[i]) { case True _: remainingTests.RemoveAt(i); break; case False f: remainingTests.Free(); return f; case AndSequence seq: var testsToInsert = seq.RemainingTests; remainingTests.RemoveAt(i); for (int j = 0, n = testsToInsert.Length; j < n; j++) remainingTests.Insert(i + j, testsToInsert[j]); break; } } var result = remainingTests.Count switch { 0 => True.Instance, 1 => remainingTests[0], _ => new AndSequence(remainingTests.ToImmutable()), }; remainingTests.Free(); return result; } public override BoundDagTest ComputeSelectedTest() { // Our simple heuristic is to perform the first test of the // first possible matched case, with two exceptions. if (RemainingTests[0] is One { Test: { Kind: BoundKind.DagNonNullTest } planA }) { switch (RemainingTests[1]) { // In the specific case of a null check following by a type test, we skip the // null check and perform the type test directly. That's because the type test // has the side-effect of performing the null check for us. case One { Test: { Kind: BoundKind.DagTypeTest } planB1 }: return (planA.Input == planB1.Input) ? planB1 : planA; // In the specific case of a null check following by a value test (which occurs for // pattern matching a string constant pattern), we skip the // null check and perform the value test directly. That's because the value test // has the side-effect of performing the null check for us. case One { Test: { Kind: BoundKind.DagValueTest } planB2 }: return (planA.Input == planB2.Input) ? planB2 : planA; } } return RemainingTests[0].ComputeSelectedTest(); } public override string Dump(Func<BoundDagTest, string> dump) { return $"AND({string.Join(", ", RemainingTests.Select(t => t.Dump(dump)))})"; } } /// <summary> /// A sequence of tests that must be performed, any of which must succeed. /// The sequence is deemed to succeed if some element succeeds. /// </summary> public sealed class OrSequence : SequenceTests { private OrSequence(ImmutableArray<Tests> remainingTests) : base(remainingTests) { } public override BoundDagTest ComputeSelectedTest() => this.RemainingTests[0].ComputeSelectedTest(); public override Tests Update(ArrayBuilder<Tests> remainingTests) => Create(remainingTests); public static Tests Create(ArrayBuilder<Tests> remainingTests) { for (int i = remainingTests.Count - 1; i >= 0; i--) { switch (remainingTests[i]) { case False _: remainingTests.RemoveAt(i); break; case True t: remainingTests.Free(); return t; case OrSequence seq: remainingTests.RemoveAt(i); var testsToInsert = seq.RemainingTests; for (int j = 0, n = testsToInsert.Length; j < n; j++) remainingTests.Insert(i + j, testsToInsert[j]); break; } } var result = remainingTests.Count switch { 0 => False.Instance, 1 => remainingTests[0], _ => new OrSequence(remainingTests.ToImmutable()), }; remainingTests.Free(); return result; } public override string Dump(Func<BoundDagTest, string> dump) { return $"OR({string.Join(", ", RemainingTests.Select(t => t.Dump(dump)))})"; } } } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// <para> /// A utility class for making a decision dag (directed acyclic graph) for a pattern-matching construct. /// A decision dag is represented by /// the class <see cref="BoundDecisionDag"/> and is a representation of a finite state automaton that performs a /// sequence of binary tests. Each node is represented by a <see cref="BoundDecisionDagNode"/>. There are four /// kind of nodes: <see cref="BoundTestDecisionDagNode"/> performs one of the binary tests; /// <see cref="BoundEvaluationDecisionDagNode"/> simply performs some computation and stores it in one or more /// temporary variables for use in subsequent nodes (think of it as a node with a single successor); /// <see cref="BoundWhenDecisionDagNode"/> represents the test performed by evaluating the expression of the /// when-clause of a switch case; and <see cref="BoundLeafDecisionDagNode"/> represents a leaf node when we /// have finally determined exactly which case matches. Each test processes a single input, and there are /// four kinds:<see cref="BoundDagExplicitNullTest"/> tests a value for null; <see cref="BoundDagNonNullTest"/> /// tests that a value is not null; <see cref="BoundDagTypeTest"/> checks if the value is of a given type; /// and <see cref="BoundDagValueTest"/> checks if the value is equal to a given constant. Of the evaluations, /// there are <see cref="BoundDagDeconstructEvaluation"/> which represents an invocation of a type's /// "Deconstruct" method; <see cref="BoundDagFieldEvaluation"/> reads a field; <see cref="BoundDagPropertyEvaluation"/> /// reads a property; and <see cref="BoundDagTypeEvaluation"/> converts a value from one type to another (which /// is performed only after testing that the value is of that type). /// </para> /// <para> /// In order to build this automaton, we start (in /// <see cref="MakeBoundDecisionDag(SyntaxNode, ImmutableArray{DecisionDagBuilder.StateForCase})"/> /// by computing a description of the initial state in a <see cref="DagState"/>, and then /// for each such state description we decide what the test or evaluation will be at /// that state, and compute the successor state descriptions. /// A state description represented by a <see cref="DagState"/> is a collection of partially matched /// cases represented /// by <see cref="StateForCase"/>, in which some number of the tests have already been performed /// for each case. /// When we have computed <see cref="DagState"/> descriptions for all of the states, we create a new /// <see cref="BoundDecisionDagNode"/> for each of them, containing /// the state transitions (including the test to perform at each node and the successor nodes) but /// not the state descriptions. A <see cref="BoundDecisionDag"/> containing this /// set of nodes becomes part of the bound nodes (e.g. in <see cref="BoundSwitchStatement"/> and /// <see cref="BoundUnconvertedSwitchExpression"/>) and is used for semantic analysis and lowering. /// </para> /// </summary> internal sealed class DecisionDagBuilder { private readonly CSharpCompilation _compilation; private readonly Conversions _conversions; private readonly BindingDiagnosticBag _diagnostics; private readonly LabelSymbol _defaultLabel; private DecisionDagBuilder(CSharpCompilation compilation, LabelSymbol defaultLabel, BindingDiagnosticBag diagnostics) { this._compilation = compilation; this._conversions = compilation.Conversions; _diagnostics = diagnostics; _defaultLabel = defaultLabel; } /// <summary> /// Create a decision dag for a switch statement. /// </summary> public static BoundDecisionDag CreateDecisionDagForSwitchStatement( CSharpCompilation compilation, SyntaxNode syntax, BoundExpression switchGoverningExpression, ImmutableArray<BoundSwitchSection> switchSections, LabelSymbol defaultLabel, BindingDiagnosticBag diagnostics) { var builder = new DecisionDagBuilder(compilation, defaultLabel, diagnostics); return builder.CreateDecisionDagForSwitchStatement(syntax, switchGoverningExpression, switchSections); } /// <summary> /// Create a decision dag for a switch expression. /// </summary> public static BoundDecisionDag CreateDecisionDagForSwitchExpression( CSharpCompilation compilation, SyntaxNode syntax, BoundExpression switchExpressionInput, ImmutableArray<BoundSwitchExpressionArm> switchArms, LabelSymbol defaultLabel, BindingDiagnosticBag diagnostics) { var builder = new DecisionDagBuilder(compilation, defaultLabel, diagnostics); return builder.CreateDecisionDagForSwitchExpression(syntax, switchExpressionInput, switchArms); } /// <summary> /// Translate the pattern of an is-pattern expression. /// </summary> public static BoundDecisionDag CreateDecisionDagForIsPattern( CSharpCompilation compilation, SyntaxNode syntax, BoundExpression inputExpression, BoundPattern pattern, LabelSymbol whenTrueLabel, LabelSymbol whenFalseLabel, BindingDiagnosticBag diagnostics) { var builder = new DecisionDagBuilder(compilation, defaultLabel: whenFalseLabel, diagnostics); return builder.CreateDecisionDagForIsPattern(syntax, inputExpression, pattern, whenTrueLabel); } private BoundDecisionDag CreateDecisionDagForIsPattern( SyntaxNode syntax, BoundExpression inputExpression, BoundPattern pattern, LabelSymbol whenTrueLabel) { var rootIdentifier = BoundDagTemp.ForOriginalInput(inputExpression); return MakeBoundDecisionDag(syntax, ImmutableArray.Create(MakeTestsForPattern(index: 1, pattern.Syntax, rootIdentifier, pattern, whenClause: null, whenTrueLabel))); } private BoundDecisionDag CreateDecisionDagForSwitchStatement( SyntaxNode syntax, BoundExpression switchGoverningExpression, ImmutableArray<BoundSwitchSection> switchSections) { var rootIdentifier = BoundDagTemp.ForOriginalInput(switchGoverningExpression); int i = 0; var builder = ArrayBuilder<StateForCase>.GetInstance(switchSections.Length); foreach (BoundSwitchSection section in switchSections) { foreach (BoundSwitchLabel label in section.SwitchLabels) { if (label.Syntax.Kind() != SyntaxKind.DefaultSwitchLabel) { builder.Add(MakeTestsForPattern(++i, label.Syntax, rootIdentifier, label.Pattern, label.WhenClause, label.Label)); } } } return MakeBoundDecisionDag(syntax, builder.ToImmutableAndFree()); } /// <summary> /// Used to create a decision dag for a switch expression. /// </summary> private BoundDecisionDag CreateDecisionDagForSwitchExpression( SyntaxNode syntax, BoundExpression switchExpressionInput, ImmutableArray<BoundSwitchExpressionArm> switchArms) { var rootIdentifier = BoundDagTemp.ForOriginalInput(switchExpressionInput); int i = 0; var builder = ArrayBuilder<StateForCase>.GetInstance(switchArms.Length); foreach (BoundSwitchExpressionArm arm in switchArms) builder.Add(MakeTestsForPattern(++i, arm.Syntax, rootIdentifier, arm.Pattern, arm.WhenClause, arm.Label)); return MakeBoundDecisionDag(syntax, builder.ToImmutableAndFree()); } /// <summary> /// Compute the set of remaining tests for a pattern. /// </summary> private StateForCase MakeTestsForPattern( int index, SyntaxNode syntax, BoundDagTemp input, BoundPattern pattern, BoundExpression? whenClause, LabelSymbol label) { Tests tests = MakeAndSimplifyTestsAndBindings(input, pattern, out ImmutableArray<BoundPatternBinding> bindings); return new StateForCase(index, syntax, tests, bindings, whenClause, label); } private Tests MakeAndSimplifyTestsAndBindings( BoundDagTemp input, BoundPattern pattern, out ImmutableArray<BoundPatternBinding> bindings) { var bindingsBuilder = ArrayBuilder<BoundPatternBinding>.GetInstance(); Tests tests = MakeTestsAndBindings(input, pattern, bindingsBuilder); tests = SimplifyTestsAndBindings(tests, bindingsBuilder); bindings = bindingsBuilder.ToImmutableAndFree(); return tests; } private static Tests SimplifyTestsAndBindings( Tests tests, ArrayBuilder<BoundPatternBinding> bindingsBuilder) { // Now simplify the tests and bindings. We don't need anything in tests that does not // contribute to the result. This will, for example, permit us to match `(2, 3) is (2, _)` without // fetching `Item2` from the input. var usedValues = PooledHashSet<BoundDagEvaluation>.GetInstance(); foreach (BoundPatternBinding binding in bindingsBuilder) { BoundDagTemp temp = binding.TempContainingValue; if (temp.Source is { }) { usedValues.Add(temp.Source); } } var result = scanAndSimplify(tests); usedValues.Free(); return result; Tests scanAndSimplify(Tests tests) { switch (tests) { case Tests.SequenceTests seq: var testSequence = seq.RemainingTests; var length = testSequence.Length; var newSequence = ArrayBuilder<Tests>.GetInstance(length); newSequence.AddRange(testSequence); for (int i = length - 1; i >= 0; i--) { newSequence[i] = scanAndSimplify(newSequence[i]); } return seq.Update(newSequence); case Tests.True _: case Tests.False _: return tests; case Tests.One(BoundDagEvaluation e): if (usedValues.Contains(e)) { if (e.Input.Source is { }) usedValues.Add(e.Input.Source); return tests; } else { return Tests.True.Instance; } case Tests.One(BoundDagTest d): if (d.Input.Source is { }) usedValues.Add(d.Input.Source); return tests; case Tests.Not n: return Tests.Not.Create(scanAndSimplify(n.Negated)); default: throw ExceptionUtilities.UnexpectedValue(tests); } } } private Tests MakeTestsAndBindings( BoundDagTemp input, BoundPattern pattern, ArrayBuilder<BoundPatternBinding> bindings) { return MakeTestsAndBindings(input, pattern, out _, bindings); } /// <summary> /// Make the tests and variable bindings for the given pattern with the given input. The pattern's /// "output" value is placed in <paramref name="output"/>. The output is defined as the input /// narrowed according to the pattern's *narrowed type*; see https://github.com/dotnet/csharplang/issues/2850. /// </summary> private Tests MakeTestsAndBindings( BoundDagTemp input, BoundPattern pattern, out BoundDagTemp output, ArrayBuilder<BoundPatternBinding> bindings) { Debug.Assert(pattern.HasErrors || pattern.InputType.Equals(input.Type, TypeCompareKind.AllIgnoreOptions) || pattern.InputType.IsErrorType()); switch (pattern) { case BoundDeclarationPattern declaration: return MakeTestsAndBindingsForDeclarationPattern(input, declaration, out output, bindings); case BoundConstantPattern constant: return MakeTestsForConstantPattern(input, constant, out output); case BoundDiscardPattern _: output = input; return Tests.True.Instance; case BoundRecursivePattern recursive: return MakeTestsAndBindingsForRecursivePattern(input, recursive, out output, bindings); case BoundITuplePattern iTuple: return MakeTestsAndBindingsForITuplePattern(input, iTuple, out output, bindings); case BoundTypePattern type: return MakeTestsForTypePattern(input, type, out output); case BoundRelationalPattern rel: return MakeTestsAndBindingsForRelationalPattern(input, rel, out output); case BoundNegatedPattern neg: output = input; return MakeTestsAndBindingsForNegatedPattern(input, neg, bindings); case BoundBinaryPattern bin: return MakeTestsAndBindingsForBinaryPattern(input, bin, out output, bindings); default: throw ExceptionUtilities.UnexpectedValue(pattern.Kind); } } private Tests MakeTestsAndBindingsForITuplePattern( BoundDagTemp input, BoundITuplePattern pattern, out BoundDagTemp output, ArrayBuilder<BoundPatternBinding> bindings) { var syntax = pattern.Syntax; var patternLength = pattern.Subpatterns.Length; var objectType = this._compilation.GetSpecialType(SpecialType.System_Object); var getLengthProperty = (PropertySymbol)pattern.GetLengthMethod.AssociatedSymbol; RoslynDebug.Assert(getLengthProperty.Type.SpecialType == SpecialType.System_Int32); var getItemProperty = (PropertySymbol)pattern.GetItemMethod.AssociatedSymbol; var iTupleType = getLengthProperty.ContainingType; RoslynDebug.Assert(iTupleType.Name == "ITuple"); var tests = ArrayBuilder<Tests>.GetInstance(4 + patternLength * 2); tests.Add(new Tests.One(new BoundDagTypeTest(syntax, iTupleType, input))); var valueAsITupleEvaluation = new BoundDagTypeEvaluation(syntax, iTupleType, input); tests.Add(new Tests.One(valueAsITupleEvaluation)); var valueAsITuple = new BoundDagTemp(syntax, iTupleType, valueAsITupleEvaluation); output = valueAsITuple; var lengthEvaluation = new BoundDagPropertyEvaluation(syntax, getLengthProperty, OriginalInput(valueAsITuple, getLengthProperty)); tests.Add(new Tests.One(lengthEvaluation)); var lengthTemp = new BoundDagTemp(syntax, this._compilation.GetSpecialType(SpecialType.System_Int32), lengthEvaluation); tests.Add(new Tests.One(new BoundDagValueTest(syntax, ConstantValue.Create(patternLength), lengthTemp))); var getItemPropertyInput = OriginalInput(valueAsITuple, getItemProperty); for (int i = 0; i < patternLength; i++) { var indexEvaluation = new BoundDagIndexEvaluation(syntax, getItemProperty, i, getItemPropertyInput); tests.Add(new Tests.One(indexEvaluation)); var indexTemp = new BoundDagTemp(syntax, objectType, indexEvaluation); tests.Add(MakeTestsAndBindings(indexTemp, pattern.Subpatterns[i].Pattern, bindings)); } return Tests.AndSequence.Create(tests); } /// <summary> /// Get the earliest input of which the symbol is a member. /// A BoundDagTypeEvaluation doesn't change the underlying object being pointed to. /// So two evaluations act on the same input so long as they have the same original input. /// We use this method to compute the original input for an evaluation. /// </summary> private BoundDagTemp OriginalInput(BoundDagTemp input, Symbol symbol) { while (input.Source is BoundDagTypeEvaluation source && IsDerivedType(source.Input.Type, symbol.ContainingType)) { input = source.Input; } return input; } bool IsDerivedType(TypeSymbol possibleDerived, TypeSymbol possibleBase) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return this._conversions.HasIdentityOrImplicitReferenceConversion(possibleDerived, possibleBase, ref discardedUseSiteInfo); } private Tests MakeTestsAndBindingsForDeclarationPattern( BoundDagTemp input, BoundDeclarationPattern declaration, out BoundDagTemp output, ArrayBuilder<BoundPatternBinding> bindings) { TypeSymbol? type = declaration.DeclaredType?.Type; var tests = ArrayBuilder<Tests>.GetInstance(1); // Add a null and type test if needed. if (!declaration.IsVar) input = MakeConvertToType(input, declaration.Syntax, type!, isExplicitTest: false, tests); BoundExpression? variableAccess = declaration.VariableAccess; if (variableAccess is { }) { Debug.Assert(variableAccess.Type!.Equals(input.Type, TypeCompareKind.AllIgnoreOptions) || variableAccess.Type.IsErrorType()); bindings.Add(new BoundPatternBinding(variableAccess, input)); } else { RoslynDebug.Assert(declaration.Variable == null); } output = input; return Tests.AndSequence.Create(tests); } private Tests MakeTestsForTypePattern( BoundDagTemp input, BoundTypePattern typePattern, out BoundDagTemp output) { TypeSymbol type = typePattern.DeclaredType.Type; var tests = ArrayBuilder<Tests>.GetInstance(4); output = MakeConvertToType(input: input, syntax: typePattern.Syntax, type: type, isExplicitTest: typePattern.IsExplicitNotNullTest, tests: tests); return Tests.AndSequence.Create(tests); } private static void MakeCheckNotNull( BoundDagTemp input, SyntaxNode syntax, bool isExplicitTest, ArrayBuilder<Tests> tests) { // Add a null test if needed if (input.Type.CanContainNull()) tests.Add(new Tests.One(new BoundDagNonNullTest(syntax, isExplicitTest, input))); } /// <summary> /// Generate a not-null check and a type check. /// </summary> private BoundDagTemp MakeConvertToType( BoundDagTemp input, SyntaxNode syntax, TypeSymbol type, bool isExplicitTest, ArrayBuilder<Tests> tests) { MakeCheckNotNull(input, syntax, isExplicitTest, tests); if (!input.Type.Equals(type, TypeCompareKind.AllIgnoreOptions)) { TypeSymbol inputType = input.Type.StrippedType(); // since a null check has already been done var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(_diagnostics, _compilation.Assembly); Conversion conversion = _conversions.ClassifyBuiltInConversion(inputType, type, ref useSiteInfo); _diagnostics.Add(syntax, useSiteInfo); if (input.Type.IsDynamic() ? type.SpecialType == SpecialType.System_Object : conversion.IsImplicit) { // type test not needed, only the type cast } else { // both type test and cast needed tests.Add(new Tests.One(new BoundDagTypeTest(syntax, type, input))); } var evaluation = new BoundDagTypeEvaluation(syntax, type, input); input = new BoundDagTemp(syntax, type, evaluation); tests.Add(new Tests.One(evaluation)); } return input; } private Tests MakeTestsForConstantPattern( BoundDagTemp input, BoundConstantPattern constant, out BoundDagTemp output) { if (constant.ConstantValue == ConstantValue.Null) { output = input; return new Tests.One(new BoundDagExplicitNullTest(constant.Syntax, input)); } else { var tests = ArrayBuilder<Tests>.GetInstance(2); var convertedInput = MakeConvertToType(input, constant.Syntax, constant.Value.Type!, isExplicitTest: false, tests); output = convertedInput; tests.Add(new Tests.One(new BoundDagValueTest(constant.Syntax, constant.ConstantValue, convertedInput))); return Tests.AndSequence.Create(tests); } } private Tests MakeTestsAndBindingsForRecursivePattern( BoundDagTemp input, BoundRecursivePattern recursive, out BoundDagTemp output, ArrayBuilder<BoundPatternBinding> bindings) { RoslynDebug.Assert(input.Type.IsErrorType() || recursive.HasErrors || recursive.InputType.IsErrorType() || input.Type.Equals(recursive.InputType, TypeCompareKind.AllIgnoreOptions)); var inputType = recursive.DeclaredType?.Type ?? input.Type.StrippedType(); var tests = ArrayBuilder<Tests>.GetInstance(5); output = input = MakeConvertToType(input, recursive.Syntax, inputType, isExplicitTest: recursive.IsExplicitNotNullTest, tests); if (!recursive.Deconstruction.IsDefault) { // we have a "deconstruction" form, which is either an invocation of a Deconstruct method, or a disassembly of a tuple if (recursive.DeconstructMethod != null) { MethodSymbol method = recursive.DeconstructMethod; var evaluation = new BoundDagDeconstructEvaluation(recursive.Syntax, method, OriginalInput(input, method)); tests.Add(new Tests.One(evaluation)); int extensionExtra = method.IsStatic ? 1 : 0; int count = Math.Min(method.ParameterCount - extensionExtra, recursive.Deconstruction.Length); for (int i = 0; i < count; i++) { BoundPattern pattern = recursive.Deconstruction[i].Pattern; SyntaxNode syntax = pattern.Syntax; var element = new BoundDagTemp(syntax, method.Parameters[i + extensionExtra].Type, evaluation, i); tests.Add(MakeTestsAndBindings(element, pattern, bindings)); } } else if (Binder.IsZeroElementTupleType(inputType)) { // Work around https://github.com/dotnet/roslyn/issues/20648: The compiler's internal APIs such as `declType.IsTupleType` // do not correctly treat the non-generic struct `System.ValueTuple` as a tuple type. We explicitly perform the tests // required to identify it. When that bug is fixed we should be able to remove this if statement. // nothing to do, as there are no tests for the zero elements of this tuple } else if (inputType.IsTupleType) { ImmutableArray<FieldSymbol> elements = inputType.TupleElements; ImmutableArray<TypeWithAnnotations> elementTypes = inputType.TupleElementTypesWithAnnotations; int count = Math.Min(elementTypes.Length, recursive.Deconstruction.Length); for (int i = 0; i < count; i++) { BoundPattern pattern = recursive.Deconstruction[i].Pattern; SyntaxNode syntax = pattern.Syntax; FieldSymbol field = elements[i]; var evaluation = new BoundDagFieldEvaluation(syntax, field, OriginalInput(input, field)); // fetch the ItemN field tests.Add(new Tests.One(evaluation)); var element = new BoundDagTemp(syntax, field.Type, evaluation); tests.Add(MakeTestsAndBindings(element, pattern, bindings)); } } else { // This occurs in error cases. RoslynDebug.Assert(recursive.HasAnyErrors); // To prevent this pattern from subsuming other patterns and triggering a cascaded diagnostic, we add a test that will fail. tests.Add(new Tests.One(new BoundDagTypeTest(recursive.Syntax, ErrorType(), input, hasErrors: true))); } } if (!recursive.Properties.IsDefault) { // we have a "property" form foreach (var subpattern in recursive.Properties) { BoundPattern pattern = subpattern.Pattern; BoundDagTemp currentInput = input; if (!tryMakeSubpatternMemberTests(subpattern.Member, ref currentInput)) { Debug.Assert(recursive.HasAnyErrors); tests.Add(new Tests.One(new BoundDagTypeTest(recursive.Syntax, ErrorType(), input, hasErrors: true))); } else { tests.Add(MakeTestsAndBindings(currentInput, pattern, bindings)); } } } if (recursive.VariableAccess != null) { // we have a "variable" declaration bindings.Add(new BoundPatternBinding(recursive.VariableAccess, input)); } return Tests.AndSequence.Create(tests); bool tryMakeSubpatternMemberTests([NotNullWhen(true)] BoundPropertySubpatternMember? member, ref BoundDagTemp input) { if (member is null) return false; if (tryMakeSubpatternMemberTests(member.Receiver, ref input)) { // If this is not the first member, add null test, unwrap nullables, and continue. input = MakeConvertToType(input, member.Syntax, member.Receiver.Type.StrippedType(), isExplicitTest: false, tests); } BoundDagEvaluation evaluation; switch (member.Symbol) { case PropertySymbol property: evaluation = new BoundDagPropertyEvaluation(member.Syntax, property, OriginalInput(input, property)); break; case FieldSymbol field: evaluation = new BoundDagFieldEvaluation(member.Syntax, field, OriginalInput(input, field)); break; default: return false; } tests.Add(new Tests.One(evaluation)); input = new BoundDagTemp(member.Syntax, member.Type, evaluation); return true; } } private Tests MakeTestsAndBindingsForNegatedPattern(BoundDagTemp input, BoundNegatedPattern neg, ArrayBuilder<BoundPatternBinding> bindings) { var tests = MakeTestsAndBindings(input, neg.Negated, bindings); return Tests.Not.Create(tests); } private Tests MakeTestsAndBindingsForBinaryPattern( BoundDagTemp input, BoundBinaryPattern bin, out BoundDagTemp output, ArrayBuilder<BoundPatternBinding> bindings) { var builder = ArrayBuilder<Tests>.GetInstance(2); if (bin.Disjunction) { builder.Add(MakeTestsAndBindings(input, bin.Left, bindings)); builder.Add(MakeTestsAndBindings(input, bin.Right, bindings)); var result = Tests.OrSequence.Create(builder); if (bin.InputType.Equals(bin.NarrowedType)) { output = input; return result; } else { builder = ArrayBuilder<Tests>.GetInstance(2); builder.Add(result); output = MakeConvertToType(input: input, syntax: bin.Syntax, type: bin.NarrowedType, isExplicitTest: false, tests: builder); return Tests.AndSequence.Create(builder); } } else { builder.Add(MakeTestsAndBindings(input, bin.Left, out var leftOutput, bindings)); builder.Add(MakeTestsAndBindings(leftOutput, bin.Right, out var rightOutput, bindings)); output = rightOutput; Debug.Assert(bin.HasErrors || output.Type.Equals(bin.NarrowedType, TypeCompareKind.AllIgnoreOptions)); return Tests.AndSequence.Create(builder); } } private Tests MakeTestsAndBindingsForRelationalPattern( BoundDagTemp input, BoundRelationalPattern rel, out BoundDagTemp output) { // check if the test is always true or always false var tests = ArrayBuilder<Tests>.GetInstance(2); output = MakeConvertToType(input, rel.Syntax, rel.Value.Type!, isExplicitTest: false, tests); var fac = ValueSetFactory.ForType(input.Type); var values = fac?.Related(rel.Relation.Operator(), rel.ConstantValue); if (values?.IsEmpty == true) { tests.Add(Tests.False.Instance); } else if (values?.Complement().IsEmpty != true) { tests.Add(new Tests.One(new BoundDagRelationalTest(rel.Syntax, rel.Relation, rel.ConstantValue, output, rel.HasErrors))); } return Tests.AndSequence.Create(tests); } private TypeSymbol ErrorType(string name = "") { return new ExtendedErrorTypeSymbol(this._compilation, name, arity: 0, errorInfo: null, unreported: false); } /// <summary> /// Compute and translate the decision dag, given a description of its initial state and a default /// decision when no decision appears to match. This implementation is nonrecursive to avoid /// overflowing the compiler's evaluation stack when compiling a large switch statement. /// </summary> private BoundDecisionDag MakeBoundDecisionDag(SyntaxNode syntax, ImmutableArray<StateForCase> cases) { // Build the state machine underlying the decision dag DecisionDag decisionDag = MakeDecisionDag(cases); // Note: It is useful for debugging the dag state table construction to set a breakpoint // here and view `decisionDag.Dump()`. ; // Compute the bound decision dag corresponding to each node of decisionDag, and store // it in node.Dag. var defaultDecision = new BoundLeafDecisionDagNode(syntax, _defaultLabel); ComputeBoundDecisionDagNodes(decisionDag, defaultDecision); var rootDecisionDagNode = decisionDag.RootNode.Dag; RoslynDebug.Assert(rootDecisionDagNode != null); var boundDecisionDag = new BoundDecisionDag(rootDecisionDagNode.Syntax, rootDecisionDagNode); #if DEBUG // Note that this uses the custom equality in `BoundDagEvaluation` // to make "equivalent" evaluation nodes share the same ID. var nextTempNumber = 0; var tempIdentifierMap = PooledDictionary<BoundDagEvaluation, int>.GetInstance(); var sortedBoundDagNodes = boundDecisionDag.TopologicallySortedNodes; for (int i = 0; i < sortedBoundDagNodes.Length; i++) { var node = sortedBoundDagNodes[i]; node.Id = i; switch (node) { case BoundEvaluationDecisionDagNode { Evaluation: { Id: -1 } evaluation }: evaluation.Id = tempIdentifier(evaluation); // Note that "equivalent" evaluations may be different object instances. // Therefore we have to dig into the Input.Source of evaluations and tests to set their IDs. if (evaluation.Input.Source is { Id: -1 } source) { source.Id = tempIdentifier(source); } break; case BoundTestDecisionDagNode { Test: var test }: if (test.Input.Source is { Id: -1 } testSource) { testSource.Id = tempIdentifier(testSource); } break; } } tempIdentifierMap.Free(); int tempIdentifier(BoundDagEvaluation e) { return tempIdentifierMap.TryGetValue(e, out int value) ? value : tempIdentifierMap[e] = ++nextTempNumber; } #endif return boundDecisionDag; } /// <summary> /// Make a <see cref="DecisionDag"/> (state machine) starting with the given set of cases in the root node, /// and return the node for the root. /// </summary> private DecisionDag MakeDecisionDag(ImmutableArray<StateForCase> casesForRootNode) { // A work list of DagStates whose successors need to be computed var workList = ArrayBuilder<DagState>.GetInstance(); // A mapping used to make each DagState unique (i.e. to de-dup identical states). var uniqueState = new Dictionary<DagState, DagState>(DagStateEquivalence.Instance); // We "intern" the states, so that we only have a single object representing one // semantic state. Because the decision automaton may contain states that have more than one // predecessor, we want to represent each such state as a reference-unique object // so that it is processed only once. This object identity uniqueness will be important later when we // start mutating the DagState nodes to compute successors and BoundDecisionDagNodes // for each one. That is why we have to use an equivalence relation in the dictionary `uniqueState`. DagState uniqifyState(ImmutableArray<StateForCase> cases, ImmutableDictionary<BoundDagTemp, IValueSet> remainingValues) { var state = new DagState(cases, remainingValues); if (uniqueState.TryGetValue(state, out DagState? existingState)) { // We found an existing state that matches. Update its set of possible remaining values // of each temp by taking the union of the sets on each incoming edge. var newRemainingValues = ImmutableDictionary.CreateBuilder<BoundDagTemp, IValueSet>(); foreach (var (dagTemp, valuesForTemp) in remainingValues) { // If one incoming edge does not have a set of possible values for the temp, // that means the temp can take on any value of its type. if (existingState.RemainingValues.TryGetValue(dagTemp, out var existingValuesForTemp)) { var newExistingValuesForTemp = existingValuesForTemp.Union(valuesForTemp); newRemainingValues.Add(dagTemp, newExistingValuesForTemp); } } if (existingState.RemainingValues.Count != newRemainingValues.Count || !existingState.RemainingValues.All(kv => newRemainingValues.TryGetValue(kv.Key, out IValueSet? values) && kv.Value.Equals(values))) { existingState.UpdateRemainingValues(newRemainingValues.ToImmutable()); if (!workList.Contains(existingState)) workList.Push(existingState); } return existingState; } else { // When we add a new unique state, we add it to a work list so that we // will process it to compute its successors. uniqueState.Add(state, state); workList.Push(state); return state; } } // Simplify the initial state based on impossible or earlier matched cases var rewrittenCases = ArrayBuilder<StateForCase>.GetInstance(casesForRootNode.Length); foreach (var state in casesForRootNode) { if (state.IsImpossible) continue; rewrittenCases.Add(state); if (state.IsFullyMatched) break; } var initialState = uniqifyState(rewrittenCases.ToImmutableAndFree(), ImmutableDictionary<BoundDagTemp, IValueSet>.Empty); // Go through the worklist of DagState nodes for which we have not yet computed // successor states. while (workList.Count != 0) { DagState state = workList.Pop(); RoslynDebug.Assert(state.SelectedTest == null); RoslynDebug.Assert(state.TrueBranch == null); RoslynDebug.Assert(state.FalseBranch == null); if (state.Cases.IsDefaultOrEmpty) { // If this state has no more cases that could possibly match, then // we know there is no case that will match and this node represents a "default" // decision. We do not need to compute a successor, as it is a leaf node continue; } StateForCase first = state.Cases[0]; Debug.Assert(!first.IsImpossible); if (first.PatternIsSatisfied) { if (first.IsFullyMatched) { // The first of the remaining cases has fully matched, as there are no more tests to do. // The language semantics of the switch statement and switch expression require that we // execute the first matching case. There is no when clause to evaluate here, // so this is a leaf node and required no further processing. } else { // There is a when clause to evaluate. // In case the when clause fails, we prepare for the remaining cases. var stateWhenFails = state.Cases.RemoveAt(0); state.FalseBranch = uniqifyState(stateWhenFails, state.RemainingValues); } } else { // Select the next test to do at this state, and compute successor states switch (state.SelectedTest = state.ComputeSelectedTest()) { case BoundDagEvaluation e: state.TrueBranch = uniqifyState(RemoveEvaluation(state.Cases, e), state.RemainingValues); // An evaluation is considered to always succeed, so there is no false branch break; case BoundDagTest d: bool foundExplicitNullTest = false; SplitCases( state.Cases, state.RemainingValues, d, out ImmutableArray<StateForCase> whenTrueDecisions, out ImmutableArray<StateForCase> whenFalseDecisions, out ImmutableDictionary<BoundDagTemp, IValueSet> whenTrueValues, out ImmutableDictionary<BoundDagTemp, IValueSet> whenFalseValues, ref foundExplicitNullTest); state.TrueBranch = uniqifyState(whenTrueDecisions, whenTrueValues); state.FalseBranch = uniqifyState(whenFalseDecisions, whenFalseValues); if (foundExplicitNullTest && d is BoundDagNonNullTest { IsExplicitTest: false } t) { // Turn an "implicit" non-null test into an explicit one state.SelectedTest = new BoundDagNonNullTest(t.Syntax, isExplicitTest: true, t.Input, t.HasErrors); } break; case var n: throw ExceptionUtilities.UnexpectedValue(n.Kind); } } } workList.Free(); return new DecisionDag(initialState); } /// <summary> /// Compute the <see cref="BoundDecisionDag"/> corresponding to each <see cref="DagState"/> of the given <see cref="DecisionDag"/> /// and store it in <see cref="DagState.Dag"/>. /// </summary> private void ComputeBoundDecisionDagNodes(DecisionDag decisionDag, BoundLeafDecisionDagNode defaultDecision) { Debug.Assert(_defaultLabel != null); Debug.Assert(defaultDecision != null); // Process the states in topological order, leaves first, and assign a BoundDecisionDag to each DagState. bool wasAcyclic = decisionDag.TryGetTopologicallySortedReachableStates(out ImmutableArray<DagState> sortedStates); if (!wasAcyclic) { // Since we intend the set of DagState nodes to be acyclic by construction, we do not expect // this to occur. Just in case it does due to bugs, we recover gracefully to avoid crashing the // compiler in production. If you find that this happens (the assert fails), please modify the // DagState construction process to avoid creating a cyclic state graph. Debug.Assert(wasAcyclic); // force failure in debug builds // If the dag contains a cycle, return a short-circuit dag instead. decisionDag.RootNode.Dag = defaultDecision; return; } // We "intern" the dag nodes, so that we only have a single object representing one // semantic node. We do this because different states may end up mapping to the same // set of successor states. In this case we merge them when producing the bound state machine. var uniqueNodes = PooledDictionary<BoundDecisionDagNode, BoundDecisionDagNode>.GetInstance(); BoundDecisionDagNode uniqifyDagNode(BoundDecisionDagNode node) => uniqueNodes.GetOrAdd(node, node); _ = uniqifyDagNode(defaultDecision); for (int i = sortedStates.Length - 1; i >= 0; i--) { var state = sortedStates[i]; if (state.Cases.IsDefaultOrEmpty) { state.Dag = defaultDecision; continue; } StateForCase first = state.Cases[0]; RoslynDebug.Assert(!(first.RemainingTests is Tests.False)); if (first.PatternIsSatisfied) { if (first.IsFullyMatched) { // there is no when clause we need to evaluate state.Dag = finalState(first.Syntax, first.CaseLabel, first.Bindings); } else { RoslynDebug.Assert(state.TrueBranch == null); RoslynDebug.Assert(state.FalseBranch is { }); // The final state here does not need bindings, as they will be performed before evaluating the when clause (see below) BoundDecisionDagNode whenTrue = finalState(first.Syntax, first.CaseLabel, default); BoundDecisionDagNode? whenFalse = state.FalseBranch.Dag; RoslynDebug.Assert(whenFalse is { }); state.Dag = uniqifyDagNode(new BoundWhenDecisionDagNode(first.Syntax, first.Bindings, first.WhenClause, whenTrue, whenFalse)); } BoundDecisionDagNode finalState(SyntaxNode syntax, LabelSymbol label, ImmutableArray<BoundPatternBinding> bindings) { BoundDecisionDagNode final = uniqifyDagNode(new BoundLeafDecisionDagNode(syntax, label)); return bindings.IsDefaultOrEmpty ? final : uniqifyDagNode(new BoundWhenDecisionDagNode(syntax, bindings, null, final, null)); } } else { switch (state.SelectedTest) { case BoundDagEvaluation e: { BoundDecisionDagNode? next = state.TrueBranch!.Dag; RoslynDebug.Assert(next is { }); RoslynDebug.Assert(state.FalseBranch == null); state.Dag = uniqifyDagNode(new BoundEvaluationDecisionDagNode(e.Syntax, e, next)); } break; case BoundDagTest d: { BoundDecisionDagNode? whenTrue = state.TrueBranch!.Dag; BoundDecisionDagNode? whenFalse = state.FalseBranch!.Dag; RoslynDebug.Assert(whenTrue is { }); RoslynDebug.Assert(whenFalse is { }); state.Dag = uniqifyDagNode(new BoundTestDecisionDagNode(d.Syntax, d, whenTrue, whenFalse)); } break; case var n: throw ExceptionUtilities.UnexpectedValue(n?.Kind); } } } uniqueNodes.Free(); } private void SplitCase( StateForCase stateForCase, BoundDagTest test, IValueSet? whenTrueValues, IValueSet? whenFalseValues, out StateForCase whenTrue, out StateForCase whenFalse, ref bool foundExplicitNullTest) { stateForCase.RemainingTests.Filter(this, test, whenTrueValues, whenFalseValues, out Tests whenTrueTests, out Tests whenFalseTests, ref foundExplicitNullTest); whenTrue = makeNext(whenTrueTests); whenFalse = makeNext(whenFalseTests); return; StateForCase makeNext(Tests remainingTests) { return remainingTests.Equals(stateForCase.RemainingTests) ? stateForCase : new StateForCase( stateForCase.Index, stateForCase.Syntax, remainingTests, stateForCase.Bindings, stateForCase.WhenClause, stateForCase.CaseLabel); } } private void SplitCases( ImmutableArray<StateForCase> statesForCases, ImmutableDictionary<BoundDagTemp, IValueSet> values, BoundDagTest test, out ImmutableArray<StateForCase> whenTrue, out ImmutableArray<StateForCase> whenFalse, out ImmutableDictionary<BoundDagTemp, IValueSet> whenTrueValues, out ImmutableDictionary<BoundDagTemp, IValueSet> whenFalseValues, ref bool foundExplicitNullTest) { var whenTrueBuilder = ArrayBuilder<StateForCase>.GetInstance(statesForCases.Length); var whenFalseBuilder = ArrayBuilder<StateForCase>.GetInstance(statesForCases.Length); bool whenTruePossible, whenFalsePossible; (whenTrueValues, whenFalseValues, whenTruePossible, whenFalsePossible) = SplitValues(values, test); // whenTruePossible means the test could possibly have succeeded. whenFalsePossible means it could possibly have failed. // Tests that are either impossible or tautological (i.e. either of these false) given // the set of values are normally removed and replaced by the known result, so we would not normally be processing // a test that always succeeds or always fails, but they can occur in erroneous programs (e.g. testing for equality // against a non-constant value). foreach (var state in statesForCases) { SplitCase( state, test, whenTrueValues.TryGetValue(test.Input, out var v1) ? v1 : null, whenFalseValues.TryGetValue(test.Input, out var v2) ? v2 : null, out var whenTrueState, out var whenFalseState, ref foundExplicitNullTest); // whenTrueState.IsImpossible occurs when Split results in a state for a given case where the case has been ruled // out (because its test has failed). If not whenTruePossible, we don't want to add anything to the state. In // either case, we do not want to add the current case to the state. if (whenTruePossible && !whenTrueState.IsImpossible && !(whenTrueBuilder.Any() && whenTrueBuilder.Last().IsFullyMatched)) whenTrueBuilder.Add(whenTrueState); // Similarly for the alternative state. if (whenFalsePossible && !whenFalseState.IsImpossible && !(whenFalseBuilder.Any() && whenFalseBuilder.Last().IsFullyMatched)) whenFalseBuilder.Add(whenFalseState); } whenTrue = whenTrueBuilder.ToImmutableAndFree(); whenFalse = whenFalseBuilder.ToImmutableAndFree(); } private static ( ImmutableDictionary<BoundDagTemp, IValueSet> whenTrueValues, ImmutableDictionary<BoundDagTemp, IValueSet> whenFalseValues, bool truePossible, bool falsePossible) SplitValues( ImmutableDictionary<BoundDagTemp, IValueSet> values, BoundDagTest test) { switch (test) { case BoundDagEvaluation _: case BoundDagExplicitNullTest _: case BoundDagNonNullTest _: case BoundDagTypeTest _: return (values, values, true, true); case BoundDagValueTest t: return resultForRelation(BinaryOperatorKind.Equal, t.Value); case BoundDagRelationalTest t: return resultForRelation(t.Relation, t.Value); default: throw ExceptionUtilities.UnexpectedValue(test); } ( ImmutableDictionary<BoundDagTemp, IValueSet> whenTrueValues, ImmutableDictionary<BoundDagTemp, IValueSet> whenFalseValues, bool truePossible, bool falsePossible) resultForRelation(BinaryOperatorKind relation, ConstantValue value) { var input = test.Input; IValueSetFactory? valueFac = ValueSetFactory.ForType(input.Type); if (valueFac == null || value.IsBad) { // If it is a type we don't track yet, assume all values are possible return (values, values, true, true); } IValueSet fromTestPassing = valueFac.Related(relation.Operator(), value); IValueSet fromTestFailing = fromTestPassing.Complement(); if (values.TryGetValue(test.Input, out IValueSet? tempValuesBeforeTest)) { fromTestPassing = fromTestPassing.Intersect(tempValuesBeforeTest); fromTestFailing = fromTestFailing.Intersect(tempValuesBeforeTest); } var whenTrueValues = values.SetItem(input, fromTestPassing); var whenFalseValues = values.SetItem(input, fromTestFailing); return (whenTrueValues, whenFalseValues, !fromTestPassing.IsEmpty, !fromTestFailing.IsEmpty); } } private static ImmutableArray<StateForCase> RemoveEvaluation(ImmutableArray<StateForCase> cases, BoundDagEvaluation e) { var builder = ArrayBuilder<StateForCase>.GetInstance(cases.Length); foreach (var stateForCase in cases) { var remainingTests = stateForCase.RemainingTests.RemoveEvaluation(e); if (remainingTests is Tests.False) { // This can occur in error cases like `e is not int x` where there is a trailing evaluation // in a failure branch. } else { builder.Add(new StateForCase( Index: stateForCase.Index, Syntax: stateForCase.Syntax, RemainingTests: remainingTests, Bindings: stateForCase.Bindings, WhenClause: stateForCase.WhenClause, CaseLabel: stateForCase.CaseLabel)); } } return builder.ToImmutableAndFree(); } /// <summary> /// Given that the test <paramref name="test"/> has occurred and produced a true/false result, /// set some flags indicating the implied status of the <paramref name="other"/> test. /// </summary> /// <param name="test"></param> /// <param name="other"></param> /// <param name="whenTrueValues">The possible values of test.Input when <paramref name="test"/> has succeeded.</param> /// <param name="whenFalseValues">The possible values of test.Input when <paramref name="test"/> has failed.</param> /// <param name="trueTestPermitsTrueOther">set if <paramref name="test"/> being true would permit <paramref name="other"/> to succeed</param> /// <param name="falseTestPermitsTrueOther">set if a false result on <paramref name="test"/> would permit <paramref name="other"/> to succeed</param> /// <param name="trueTestImpliesTrueOther">set if <paramref name="test"/> being true means <paramref name="other"/> has been proven true</param> /// <param name="falseTestImpliesTrueOther">set if <paramref name="test"/> being false means <paramref name="other"/> has been proven true</param> private void CheckConsistentDecision( BoundDagTest test, BoundDagTest other, IValueSet? whenTrueValues, IValueSet? whenFalseValues, SyntaxNode syntax, out bool trueTestPermitsTrueOther, out bool falseTestPermitsTrueOther, out bool trueTestImpliesTrueOther, out bool falseTestImpliesTrueOther, ref bool foundExplicitNullTest) { // innocent until proven guilty trueTestPermitsTrueOther = true; falseTestPermitsTrueOther = true; trueTestImpliesTrueOther = false; falseTestImpliesTrueOther = false; // if the tests are for unrelated things, there is no implication from one to the other if (!test.Input.Equals(other.Input)) return; switch (test) { case BoundDagNonNullTest _: switch (other) { case BoundDagValueTest _: // !(v != null) --> !(v == K) falseTestPermitsTrueOther = false; break; case BoundDagExplicitNullTest _: foundExplicitNullTest = true; // v != null --> !(v == null) trueTestPermitsTrueOther = false; // !(v != null) --> v == null falseTestImpliesTrueOther = true; break; case BoundDagNonNullTest n2: if (n2.IsExplicitTest) foundExplicitNullTest = true; // v != null --> v != null trueTestImpliesTrueOther = true; // !(v != null) --> !(v != null) falseTestPermitsTrueOther = false; break; default: // !(v != null) --> !(v is T) falseTestPermitsTrueOther = false; break; } break; case BoundDagTypeTest t1: switch (other) { case BoundDagNonNullTest n2: if (n2.IsExplicitTest) foundExplicitNullTest = true; // v is T --> v != null trueTestImpliesTrueOther = true; break; case BoundDagTypeTest t2: { var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(_diagnostics, _compilation.Assembly); bool? matches = ExpressionOfTypeMatchesPatternTypeForLearningFromSuccessfulTypeTest(t1.Type, t2.Type, ref useSiteInfo); if (matches == false) { // If T1 could never be T2 // v is T1 --> !(v is T2) trueTestPermitsTrueOther = false; } else if (matches == true) { // If T1: T2 // v is T1 --> v is T2 trueTestImpliesTrueOther = true; } // If every T2 is a T1, then failure of T1 implies failure of T2. matches = Binder.ExpressionOfTypeMatchesPatternType(_conversions, t2.Type, t1.Type, ref useSiteInfo, out _); _diagnostics.Add(syntax, useSiteInfo); if (matches == true) { // If T2: T1 // !(v is T1) --> !(v is T2) falseTestPermitsTrueOther = false; } } break; case BoundDagValueTest _: break; case BoundDagExplicitNullTest _: foundExplicitNullTest = true; // v is T --> !(v == null) trueTestPermitsTrueOther = false; break; } break; case BoundDagValueTest _: case BoundDagRelationalTest _: switch (other) { case BoundDagNonNullTest n2: if (n2.IsExplicitTest) foundExplicitNullTest = true; // v == K --> v != null trueTestImpliesTrueOther = true; break; case BoundDagTypeTest _: break; case BoundDagExplicitNullTest _: foundExplicitNullTest = true; // v == K --> !(v == null) trueTestPermitsTrueOther = false; break; case BoundDagRelationalTest r2: handleRelationWithValue(r2.Relation, r2.Value, out trueTestPermitsTrueOther, out falseTestPermitsTrueOther, out trueTestImpliesTrueOther, out falseTestImpliesTrueOther); break; case BoundDagValueTest v2: handleRelationWithValue(BinaryOperatorKind.Equal, v2.Value, out trueTestPermitsTrueOther, out falseTestPermitsTrueOther, out trueTestImpliesTrueOther, out falseTestImpliesTrueOther); break; void handleRelationWithValue( BinaryOperatorKind relation, ConstantValue value, out bool trueTestPermitsTrueOther, out bool falseTestPermitsTrueOther, out bool trueTestImpliesTrueOther, out bool falseTestImpliesTrueOther) { // We check test.Equals(other) to handle "bad" constant values bool sameTest = test.Equals(other); trueTestPermitsTrueOther = whenTrueValues?.Any(relation, value) ?? true; trueTestImpliesTrueOther = sameTest || trueTestPermitsTrueOther && (whenTrueValues?.All(relation, value) ?? false); falseTestPermitsTrueOther = !sameTest && (whenFalseValues?.Any(relation, value) ?? true); falseTestImpliesTrueOther = falseTestPermitsTrueOther && (whenFalseValues?.All(relation, value) ?? false); } } break; case BoundDagExplicitNullTest _: foundExplicitNullTest = true; switch (other) { case BoundDagNonNullTest n2: if (n2.IsExplicitTest) foundExplicitNullTest = true; // v == null --> !(v != null) trueTestPermitsTrueOther = false; // !(v == null) --> v != null falseTestImpliesTrueOther = true; break; case BoundDagTypeTest _: // v == null --> !(v is T) trueTestPermitsTrueOther = false; break; case BoundDagExplicitNullTest _: foundExplicitNullTest = true; // v == null --> v == null trueTestImpliesTrueOther = true; // !(v == null) --> !(v == null) falseTestPermitsTrueOther = false; break; case BoundDagValueTest _: // v == null --> !(v == K) trueTestPermitsTrueOther = false; break; } break; } } /// <summary> /// Determine what we can learn from one successful runtime type test about another planned /// runtime type test for the purpose of building the decision tree. /// We accommodate a special behavior of the runtime here, which does not match the language rules. /// A value of type `int[]` is an "instanceof" (i.e. result of the `isinst` instruction) the type /// `uint[]` and vice versa. It is similarly so for every pair of same-sized numeric types, and /// arrays of enums are considered to be their underlying type. We need the dag construction to /// recognize this runtime behavior, so we pretend that matching one of them gives no information /// on whether the other will be matched. That isn't quite correct (nothing reasonable we do /// could be), but it comes closest to preserving the existing C#7 behavior without undesirable /// side-effects, and permits the code-gen strategy to preserve the dynamic semantic equivalence /// of a switch (on the one hand) and a series of if-then-else statements (on the other). /// See, for example, https://github.com/dotnet/roslyn/issues/35661 /// </summary> private bool? ExpressionOfTypeMatchesPatternTypeForLearningFromSuccessfulTypeTest( TypeSymbol expressionType, TypeSymbol patternType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { bool? result = Binder.ExpressionOfTypeMatchesPatternType(_conversions, expressionType, patternType, ref useSiteInfo, out Conversion conversion); return (!conversion.Exists && isRuntimeSimilar(expressionType, patternType)) ? null // runtime and compile-time test behavior differ. Pretend we don't know what happens. : result; static bool isRuntimeSimilar(TypeSymbol expressionType, TypeSymbol patternType) { while (expressionType is ArrayTypeSymbol { ElementType: var e1, IsSZArray: var sz1, Rank: var r1 } && patternType is ArrayTypeSymbol { ElementType: var e2, IsSZArray: var sz2, Rank: var r2 } && sz1 == sz2 && r1 == r2) { e1 = e1.EnumUnderlyingTypeOrSelf(); e2 = e2.EnumUnderlyingTypeOrSelf(); switch (e1.SpecialType, e2.SpecialType) { // The following support CLR behavior that is required by // the CLI specification but violates the C# language behavior. // See ECMA-335's definition of *array-element-compatible-with*. case var (s1, s2) when s1 == s2: case (SpecialType.System_SByte, SpecialType.System_Byte): case (SpecialType.System_Byte, SpecialType.System_SByte): case (SpecialType.System_Int16, SpecialType.System_UInt16): case (SpecialType.System_UInt16, SpecialType.System_Int16): case (SpecialType.System_Int32, SpecialType.System_UInt32): case (SpecialType.System_UInt32, SpecialType.System_Int32): case (SpecialType.System_Int64, SpecialType.System_UInt64): case (SpecialType.System_UInt64, SpecialType.System_Int64): case (SpecialType.System_IntPtr, SpecialType.System_UIntPtr): case (SpecialType.System_UIntPtr, SpecialType.System_IntPtr): // The following support behavior of the CLR that violates the CLI // and C# specifications, but we implement them because that is the // behavior on 32-bit runtimes. case (SpecialType.System_Int32, SpecialType.System_IntPtr): case (SpecialType.System_Int32, SpecialType.System_UIntPtr): case (SpecialType.System_UInt32, SpecialType.System_IntPtr): case (SpecialType.System_UInt32, SpecialType.System_UIntPtr): case (SpecialType.System_IntPtr, SpecialType.System_Int32): case (SpecialType.System_IntPtr, SpecialType.System_UInt32): case (SpecialType.System_UIntPtr, SpecialType.System_Int32): case (SpecialType.System_UIntPtr, SpecialType.System_UInt32): // The following support behavior of the CLR that violates the CLI // and C# specifications, but we implement them because that is the // behavior on 64-bit runtimes. case (SpecialType.System_Int64, SpecialType.System_IntPtr): case (SpecialType.System_Int64, SpecialType.System_UIntPtr): case (SpecialType.System_UInt64, SpecialType.System_IntPtr): case (SpecialType.System_UInt64, SpecialType.System_UIntPtr): case (SpecialType.System_IntPtr, SpecialType.System_Int64): case (SpecialType.System_IntPtr, SpecialType.System_UInt64): case (SpecialType.System_UIntPtr, SpecialType.System_Int64): case (SpecialType.System_UIntPtr, SpecialType.System_UInt64): return true; default: (expressionType, patternType) = (e1, e2); break; } } return false; } } /// <summary> /// A representation of the entire decision dag and each of its states. /// </summary> private sealed class DecisionDag { /// <summary> /// The starting point for deciding which case matches. /// </summary> public readonly DagState RootNode; public DecisionDag(DagState rootNode) { this.RootNode = rootNode; } /// <summary> /// A successor function used to topologically sort the DagState set. /// </summary> private static ImmutableArray<DagState> Successor(DagState state) { if (state.TrueBranch != null && state.FalseBranch != null) { return ImmutableArray.Create(state.FalseBranch, state.TrueBranch); } else if (state.TrueBranch != null) { return ImmutableArray.Create(state.TrueBranch); } else if (state.FalseBranch != null) { return ImmutableArray.Create(state.FalseBranch); } else { return ImmutableArray<DagState>.Empty; } } /// <summary> /// Produce the states in topological order. /// </summary> /// <param name="result">Topologically sorted <see cref="DagState"/> nodes.</param> /// <returns>True if the graph was acyclic.</returns> public bool TryGetTopologicallySortedReachableStates(out ImmutableArray<DagState> result) { return TopologicalSort.TryIterativeSort<DagState>(SpecializedCollections.SingletonEnumerable<DagState>(this.RootNode), Successor, out result); } #if DEBUG /// <summary> /// Starting with `this` state, produce a human-readable description of the state tables. /// This is very useful for debugging and optimizing the dag state construction. /// </summary> internal string Dump() { if (!this.TryGetTopologicallySortedReachableStates(out var allStates)) { return "(the dag contains a cycle!)"; } var stateIdentifierMap = PooledDictionary<DagState, int>.GetInstance(); for (int i = 0; i < allStates.Length; i++) { stateIdentifierMap.Add(allStates[i], i); } // NOTE that this numbering for temps does not work well for the invocation of Deconstruct, which produces // multiple values. This would make them appear to be the same temp in the debug dump. int nextTempNumber = 0; PooledDictionary<BoundDagEvaluation, int> tempIdentifierMap = PooledDictionary<BoundDagEvaluation, int>.GetInstance(); int tempIdentifier(BoundDagEvaluation? e) { return (e == null) ? 0 : tempIdentifierMap.TryGetValue(e, out int value) ? value : tempIdentifierMap[e] = ++nextTempNumber; } string tempName(BoundDagTemp t) { return $"t{tempIdentifier(t.Source)}"; } var resultBuilder = PooledStringBuilder.GetInstance(); var result = resultBuilder.Builder; foreach (DagState state in allStates) { bool isFail = state.Cases.IsEmpty; bool starred = isFail || state.Cases.First().PatternIsSatisfied; result.Append($"{(starred ? "*" : "")}State " + stateIdentifierMap[state] + (isFail ? " FAIL" : "")); var remainingValues = state.RemainingValues.Select(kvp => $"{tempName(kvp.Key)}:{kvp.Value}"); result.AppendLine($"{(remainingValues.Any() ? " REMAINING " + string.Join(" ", remainingValues) : "")}"); foreach (StateForCase cd in state.Cases) { result.AppendLine($" {dumpStateForCase(cd)}"); } if (state.SelectedTest != null) { result.AppendLine($" Test: {dumpDagTest(state.SelectedTest)}"); } if (state.TrueBranch != null) { result.AppendLine($" TrueBranch: {stateIdentifierMap[state.TrueBranch]}"); } if (state.FalseBranch != null) { result.AppendLine($" FalseBranch: {stateIdentifierMap[state.FalseBranch]}"); } } stateIdentifierMap.Free(); tempIdentifierMap.Free(); return resultBuilder.ToStringAndFree(); string dumpStateForCase(StateForCase cd) { var instance = PooledStringBuilder.GetInstance(); StringBuilder builder = instance.Builder; builder.Append($"{cd.Index}. [{cd.Syntax}] {(cd.PatternIsSatisfied ? "MATCH" : cd.RemainingTests.Dump(dumpDagTest))}"); var bindings = cd.Bindings.Select(bpb => $"{(bpb.VariableAccess is BoundLocal l ? l.LocalSymbol.Name : "<var>")}={tempName(bpb.TempContainingValue)}"); if (bindings.Any()) { builder.Append(" BIND["); builder.Append(string.Join("; ", bindings)); builder.Append("]"); } if (cd.WhenClause is { }) { builder.Append($" WHEN[{cd.WhenClause.Syntax}]"); } return instance.ToStringAndFree(); } string dumpDagTest(BoundDagTest d) { switch (d) { case BoundDagTypeEvaluation a: return $"t{tempIdentifier(a)}={a.Kind}({tempName(a.Input)} as {a.Type})"; case BoundDagFieldEvaluation e: return $"t{tempIdentifier(e)}={e.Kind}({tempName(e.Input)}.{e.Field.Name})"; case BoundDagPropertyEvaluation e: return $"t{tempIdentifier(e)}={e.Kind}({tempName(e.Input)}.{e.Property.Name})"; case BoundDagEvaluation e: return $"t{tempIdentifier(e)}={e.Kind}({tempName(e.Input)})"; case BoundDagTypeTest b: return $"?{d.Kind}({tempName(d.Input)} is {b.Type})"; case BoundDagValueTest v: return $"?{d.Kind}({tempName(d.Input)} == {v.Value})"; case BoundDagRelationalTest r: var operatorName = r.Relation.Operator() switch { BinaryOperatorKind.LessThan => "<", BinaryOperatorKind.LessThanOrEqual => "<=", BinaryOperatorKind.GreaterThan => ">", BinaryOperatorKind.GreaterThanOrEqual => ">=", _ => "??" }; return $"?{d.Kind}({tempName(d.Input)} {operatorName} {r.Value})"; default: return $"?{d.Kind}({tempName(d.Input)})"; } } } #endif } /// <summary> /// The state at a given node of the decision finite state automaton. This is used during computation of the state /// machine (<see cref="BoundDecisionDag"/>), and contains a representation of the meaning of the state. Because we always make /// forward progress when a test is evaluated (the state description is monotonically smaller at each edge), the /// graph of states is acyclic, which is why we call it a dag (directed acyclic graph). /// </summary> private sealed class DagState { /// <summary> /// For each dag temp of a type for which we track such things (the integral types, floating-point types, and bool), /// the possible values it can take on when control reaches this state. /// If this dictionary is mutated after <see cref="TrueBranch"/>, <see cref="FalseBranch"/>, /// and <see cref="Dag"/> are computed (for example to merge states), they must be cleared and recomputed, /// as the set of possible values can affect successor states. /// A <see cref="BoundDagTemp"/> absent from this dictionary means that all values of the type are possible. /// </summary> public ImmutableDictionary<BoundDagTemp, IValueSet> RemainingValues { get; private set; } /// <summary> /// The set of cases that may still match, and for each of them the set of tests that remain to be tested. /// </summary> public readonly ImmutableArray<StateForCase> Cases; public DagState(ImmutableArray<StateForCase> cases, ImmutableDictionary<BoundDagTemp, IValueSet> remainingValues) { this.Cases = cases; this.RemainingValues = remainingValues; } // If not a leaf node or a when clause, the test that will be taken at this node of the // decision automaton. public BoundDagTest? SelectedTest; // We only compute the dag states for the branches after we de-dup this DagState itself. // If all that remains is the `when` clauses, SelectedDecision is left `null` (we can // build the leaf node easily during translation) and the FalseBranch field is populated // with the successor on failure of the when clause (if one exists). public DagState? TrueBranch, FalseBranch; // After the entire graph of DagState objects is complete, we translate each into its Dag node. public BoundDecisionDagNode? Dag; /// <summary> /// Decide on what test to use at this node of the decision dag. This is the principal /// heuristic we can change to adjust the quality of the generated decision automaton. /// See https://www.cs.tufts.edu/~nr/cs257/archive/norman-ramsey/match.pdf for some ideas. /// </summary> internal BoundDagTest ComputeSelectedTest() { return Cases[0].RemainingTests.ComputeSelectedTest(); } internal void UpdateRemainingValues(ImmutableDictionary<BoundDagTemp, IValueSet> newRemainingValues) { this.RemainingValues = newRemainingValues; this.SelectedTest = null; this.TrueBranch = null; this.FalseBranch = null; } } /// <summary> /// An equivalence relation between dag states used to dedup the states during dag construction. /// After dag construction is complete we treat a DagState as using object equality as equivalent /// states have been merged. /// </summary> private sealed class DagStateEquivalence : IEqualityComparer<DagState> { public static readonly DagStateEquivalence Instance = new DagStateEquivalence(); private DagStateEquivalence() { } public bool Equals(DagState? x, DagState? y) { RoslynDebug.Assert(x is { }); RoslynDebug.Assert(y is { }); return x == y || x.Cases.SequenceEqual(y.Cases, (a, b) => a.Equals(b)); } public int GetHashCode(DagState x) { return Hash.Combine(Hash.CombineValues(x.Cases), x.Cases.Length); } } /// <summary> /// As part of the description of a node of the decision automaton, we keep track of what tests /// remain to be done for each case. /// </summary> private sealed class StateForCase { /// <summary> /// A number that is distinct for each case and monotonically increasing from earlier to later cases. /// Since we always keep the cases in order, this is only used to assist with debugging (e.g. /// see DecisionDag.Dump()). /// </summary> public readonly int Index; public readonly SyntaxNode Syntax; public readonly Tests RemainingTests; public readonly ImmutableArray<BoundPatternBinding> Bindings; public readonly BoundExpression? WhenClause; public readonly LabelSymbol CaseLabel; public StateForCase( int Index, SyntaxNode Syntax, Tests RemainingTests, ImmutableArray<BoundPatternBinding> Bindings, BoundExpression? WhenClause, LabelSymbol CaseLabel) { this.Index = Index; this.Syntax = Syntax; this.RemainingTests = RemainingTests; this.Bindings = Bindings; this.WhenClause = WhenClause; this.CaseLabel = CaseLabel; } /// <summary> /// Is the pattern in a state in which it is fully matched and there is no when clause? /// </summary> public bool IsFullyMatched => RemainingTests is Tests.True && (WhenClause is null || WhenClause.ConstantValue == ConstantValue.True); /// <summary> /// Is the pattern fully matched and ready for the when clause to be evaluated (if any)? /// </summary> public bool PatternIsSatisfied => RemainingTests is Tests.True; /// <summary> /// Is the clause impossible? We do not consider a when clause with a constant false value to cause the branch to be impossible. /// Note that we do not include the possibility that a when clause is the constant false. That is treated like any other expression. /// </summary> public bool IsImpossible => RemainingTests is Tests.False; public override bool Equals(object? obj) { throw ExceptionUtilities.Unreachable; } public bool Equals(StateForCase other) { // We do not include Syntax, Bindings, WhereClause, or CaseLabel // because once the Index is the same, those must be the same too. return this == other || other != null && this.Index == other.Index && this.RemainingTests.Equals(other.RemainingTests); } public override int GetHashCode() { return Hash.Combine(RemainingTests.GetHashCode(), Index); } } /// <summary> /// A set of tests to be performed. This is a discriminated union; see the options (nested types) for more details. /// </summary> private abstract class Tests { private Tests() { } /// <summary> /// Take the set of tests and split them into two, one for when the test has succeeded, and one for when the test has failed. /// </summary> public abstract void Filter( DecisionDagBuilder builder, BoundDagTest test, IValueSet? whenTrueValues, IValueSet? whenFalseValues, out Tests whenTrue, out Tests whenFalse, ref bool foundExplicitNullTest); public virtual BoundDagTest ComputeSelectedTest() => throw ExceptionUtilities.Unreachable; public virtual Tests RemoveEvaluation(BoundDagEvaluation e) => this; public abstract string Dump(Func<BoundDagTest, string> dump); /// <summary> /// No tests to be performed; the result is true (success). /// </summary> public sealed class True : Tests { public static readonly True Instance = new True(); public override string Dump(Func<BoundDagTest, string> dump) => "TRUE"; public override void Filter( DecisionDagBuilder builder, BoundDagTest test, IValueSet? whenTrueValues, IValueSet? whenFalseValues, out Tests whenTrue, out Tests whenFalse, ref bool foundExplicitNullTest) { whenTrue = whenFalse = this; } } /// <summary> /// No tests to be performed; the result is false (failure). /// </summary> public sealed class False : Tests { public static readonly False Instance = new False(); public override string Dump(Func<BoundDagTest, string> dump) => "FALSE"; public override void Filter( DecisionDagBuilder builder, BoundDagTest test, IValueSet? whenTrueValues, IValueSet? whenFalseValues, out Tests whenTrue, out Tests whenFalse, ref bool foundExplicitNullTest) { whenTrue = whenFalse = this; } } /// <summary> /// A single test to be performed, described by a <see cref="BoundDagTest"/>. /// Note that the test might be a <see cref="BoundDagEvaluation"/>, in which case it is deemed to have /// succeeded after being evaluated. /// </summary> public sealed class One : Tests { public readonly BoundDagTest Test; public One(BoundDagTest test) => this.Test = test; public void Deconstruct(out BoundDagTest Test) => Test = this.Test; public override void Filter( DecisionDagBuilder builder, BoundDagTest test, IValueSet? whenTrueValues, IValueSet? whenFalseValues, out Tests whenTrue, out Tests whenFalse, ref bool foundExplicitNullTest) { builder.CheckConsistentDecision( test: test, other: Test, whenTrueValues: whenTrueValues, whenFalseValues: whenFalseValues, syntax: test.Syntax, trueTestPermitsTrueOther: out bool trueDecisionPermitsTrueOther, falseTestPermitsTrueOther: out bool falseDecisionPermitsTrueOther, trueTestImpliesTrueOther: out bool trueDecisionImpliesTrueOther, falseTestImpliesTrueOther: out bool falseDecisionImpliesTrueOther, foundExplicitNullTest: ref foundExplicitNullTest); whenTrue = trueDecisionImpliesTrueOther ? Tests.True.Instance : trueDecisionPermitsTrueOther ? this : (Tests)Tests.False.Instance; whenFalse = falseDecisionImpliesTrueOther ? Tests.True.Instance : falseDecisionPermitsTrueOther ? this : (Tests)Tests.False.Instance; } public override BoundDagTest ComputeSelectedTest() => this.Test; public override Tests RemoveEvaluation(BoundDagEvaluation e) => e.Equals(Test) ? Tests.True.Instance : (Tests)this; public override string Dump(Func<BoundDagTest, string> dump) => dump(this.Test); public override bool Equals(object? obj) => this == obj || obj is One other && this.Test.Equals(other.Test); public override int GetHashCode() => this.Test.GetHashCode(); } public sealed class Not : Tests { // Negation is pushed to the level of a single test by demorgan's laws public readonly Tests Negated; private Not(Tests negated) => Negated = negated; public static Tests Create(Tests negated) => negated switch { Tests.True _ => Tests.False.Instance, Tests.False _ => Tests.True.Instance, Tests.Not n => n.Negated, // double negative Tests.AndSequence a => new Not(a), Tests.OrSequence a => Tests.AndSequence.Create(NegateSequenceElements(a.RemainingTests)), // use demorgan to prefer and sequences Tests.One o => new Not(o), _ => throw ExceptionUtilities.UnexpectedValue(negated), }; private static ArrayBuilder<Tests> NegateSequenceElements(ImmutableArray<Tests> seq) { var builder = ArrayBuilder<Tests>.GetInstance(seq.Length); foreach (var t in seq) builder.Add(Not.Create(t)); return builder; } public override Tests RemoveEvaluation(BoundDagEvaluation e) => Create(Negated.RemoveEvaluation(e)); public override BoundDagTest ComputeSelectedTest() => Negated.ComputeSelectedTest(); public override string Dump(Func<BoundDagTest, string> dump) => $"Not ({Negated.Dump(dump)})"; public override void Filter( DecisionDagBuilder builder, BoundDagTest test, IValueSet? whenTrueValues, IValueSet? whenFalseValues, out Tests whenTrue, out Tests whenFalse, ref bool foundExplicitNullTest) { Negated.Filter(builder, test, whenTrueValues, whenFalseValues, out var whenTestTrue, out var whenTestFalse, ref foundExplicitNullTest); whenTrue = Not.Create(whenTestTrue); whenFalse = Not.Create(whenTestFalse); } public override bool Equals(object? obj) => this == obj || obj is Not n && Negated.Equals(n.Negated); public override int GetHashCode() => Hash.Combine(Negated.GetHashCode(), typeof(Not).GetHashCode()); } public abstract class SequenceTests : Tests { public readonly ImmutableArray<Tests> RemainingTests; protected SequenceTests(ImmutableArray<Tests> remainingTests) { Debug.Assert(remainingTests.Length > 1); this.RemainingTests = remainingTests; } public abstract Tests Update(ArrayBuilder<Tests> remainingTests); public override void Filter( DecisionDagBuilder builder, BoundDagTest test, IValueSet? whenTrueValues, IValueSet? whenFalseValues, out Tests whenTrue, out Tests whenFalse, ref bool foundExplicitNullTest) { var trueBuilder = ArrayBuilder<Tests>.GetInstance(RemainingTests.Length); var falseBuilder = ArrayBuilder<Tests>.GetInstance(RemainingTests.Length); foreach (var other in RemainingTests) { other.Filter(builder, test, whenTrueValues, whenFalseValues, out Tests oneTrue, out Tests oneFalse, ref foundExplicitNullTest); trueBuilder.Add(oneTrue); falseBuilder.Add(oneFalse); } whenTrue = Update(trueBuilder); whenFalse = Update(falseBuilder); } public override Tests RemoveEvaluation(BoundDagEvaluation e) { var builder = ArrayBuilder<Tests>.GetInstance(RemainingTests.Length); foreach (var test in RemainingTests) builder.Add(test.RemoveEvaluation(e)); return Update(builder); } public override bool Equals(object? obj) => this == obj || obj is SequenceTests other && this.GetType() == other.GetType() && RemainingTests.SequenceEqual(other.RemainingTests); public override int GetHashCode() { int length = this.RemainingTests.Length; int value = Hash.Combine(length, this.GetType().GetHashCode()); value = Hash.Combine(Hash.CombineValues(this.RemainingTests), value); return value; } } /// <summary> /// A sequence of tests that must be performed, each of which must succeed. /// The sequence is deemed to succeed if no element fails. /// </summary> public sealed class AndSequence : SequenceTests { private AndSequence(ImmutableArray<Tests> remainingTests) : base(remainingTests) { } public override Tests Update(ArrayBuilder<Tests> remainingTests) => Create(remainingTests); public static Tests Create(ArrayBuilder<Tests> remainingTests) { for (int i = remainingTests.Count - 1; i >= 0; i--) { switch (remainingTests[i]) { case True _: remainingTests.RemoveAt(i); break; case False f: remainingTests.Free(); return f; case AndSequence seq: var testsToInsert = seq.RemainingTests; remainingTests.RemoveAt(i); for (int j = 0, n = testsToInsert.Length; j < n; j++) remainingTests.Insert(i + j, testsToInsert[j]); break; } } var result = remainingTests.Count switch { 0 => True.Instance, 1 => remainingTests[0], _ => new AndSequence(remainingTests.ToImmutable()), }; remainingTests.Free(); return result; } public override BoundDagTest ComputeSelectedTest() { // Our simple heuristic is to perform the first test of the // first possible matched case, with two exceptions. if (RemainingTests[0] is One { Test: { Kind: BoundKind.DagNonNullTest } planA }) { switch (RemainingTests[1]) { // In the specific case of a null check following by a type test, we skip the // null check and perform the type test directly. That's because the type test // has the side-effect of performing the null check for us. case One { Test: { Kind: BoundKind.DagTypeTest } planB1 }: return (planA.Input == planB1.Input) ? planB1 : planA; // In the specific case of a null check following by a value test (which occurs for // pattern matching a string constant pattern), we skip the // null check and perform the value test directly. That's because the value test // has the side-effect of performing the null check for us. case One { Test: { Kind: BoundKind.DagValueTest } planB2 }: return (planA.Input == planB2.Input) ? planB2 : planA; } } return RemainingTests[0].ComputeSelectedTest(); } public override string Dump(Func<BoundDagTest, string> dump) { return $"AND({string.Join(", ", RemainingTests.Select(t => t.Dump(dump)))})"; } } /// <summary> /// A sequence of tests that must be performed, any of which must succeed. /// The sequence is deemed to succeed if some element succeeds. /// </summary> public sealed class OrSequence : SequenceTests { private OrSequence(ImmutableArray<Tests> remainingTests) : base(remainingTests) { } public override BoundDagTest ComputeSelectedTest() => this.RemainingTests[0].ComputeSelectedTest(); public override Tests Update(ArrayBuilder<Tests> remainingTests) => Create(remainingTests); public static Tests Create(ArrayBuilder<Tests> remainingTests) { for (int i = remainingTests.Count - 1; i >= 0; i--) { switch (remainingTests[i]) { case False _: remainingTests.RemoveAt(i); break; case True t: remainingTests.Free(); return t; case OrSequence seq: remainingTests.RemoveAt(i); var testsToInsert = seq.RemainingTests; for (int j = 0, n = testsToInsert.Length; j < n; j++) remainingTests.Insert(i + j, testsToInsert[j]); break; } } var result = remainingTests.Count switch { 0 => False.Instance, 1 => remainingTests[0], _ => new OrSequence(remainingTests.ToImmutable()), }; remainingTests.Free(); return result; } public override string Dump(Func<BoundDagTest, string> dump) { return $"OR({string.Join(", ", RemainingTests.Select(t => t.Dump(dump)))})"; } } } } }
1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/Semantics/PatternMatchingTests5.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.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class PatternMatchingTests5 : PatternMatchingTestBase { [Fact] public void ExtendedPropertyPatterns_01() { var program = @" using System; class C { public C Prop1 { get; set; } public C Prop2 { get; set; } public C Prop3 { get; set; } static bool Test1(C o) => o is { Prop1.Prop2.Prop3: null }; static bool Test2(S o) => o is { Prop1.Prop2.Prop3: null }; static bool Test3(S? o) => o is { Prop1.Prop2.Prop3: null }; static bool Test4(S0 o) => o is { Prop1.Prop2.Prop3: 420 }; public static void Main() { Console.WriteLine(Test1(new() { Prop1 = new() { Prop2 = new() { Prop3 = null }}})); Console.WriteLine(Test2(new() { Prop1 = new() { Prop2 = new() { Prop3 = null }}})); Console.WriteLine(Test3(new() { Prop1 = new() { Prop2 = new() { Prop3 = null }}})); Console.WriteLine(Test1(new() { Prop1 = new() { Prop2 = null }})); Console.WriteLine(Test2(new() { Prop1 = new() { Prop2 = null }})); Console.WriteLine(Test3(new() { Prop1 = new() { Prop2 = null }})); Console.WriteLine(Test1(new() { Prop1 = null })); Console.WriteLine(Test2(new() { Prop1 = null })); Console.WriteLine(Test3(new() { Prop1 = null })); Console.WriteLine(Test1(default)); Console.WriteLine(Test2(default)); Console.WriteLine(Test3(default)); Console.WriteLine(Test4(new() { Prop1 = new() { Prop2 = new() { Prop3 = 421 }}})); Console.WriteLine(Test4(new() { Prop1 = new() { Prop2 = new() { Prop3 = 420 }}})); } } struct S { public A? Prop1; } struct A { public B? Prop2; } struct B { public int? Prop3; } struct S0 { public A0 Prop1; } struct A0 { public B0 Prop2; } struct B0 { public int Prop3; } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var expectedOutput = @" True True True False False False False False False False False False False True "; var verifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); verifier.VerifyIL("C.Test1", @" { // Code size 35 (0x23) .maxstack 2 .locals init (C V_0, C V_1) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0021 IL_0003: ldarg.0 IL_0004: callvirt ""C C.Prop1.get"" IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: brfalse.s IL_0021 IL_000d: ldloc.0 IL_000e: callvirt ""C C.Prop2.get"" IL_0013: stloc.1 IL_0014: ldloc.1 IL_0015: brfalse.s IL_0021 IL_0017: ldloc.1 IL_0018: callvirt ""C C.Prop3.get"" IL_001d: ldnull IL_001e: ceq IL_0020: ret IL_0021: ldc.i4.0 IL_0022: ret }"); verifier.VerifyIL("C.Test2", @" { // Code size 64 (0x40) .maxstack 2 .locals init (A? V_0, B? V_1, int? V_2) IL_0000: ldarg.0 IL_0001: ldfld ""A? S.Prop1"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: call ""bool A?.HasValue.get"" IL_000e: brfalse.s IL_003e IL_0010: ldloca.s V_0 IL_0012: call ""A A?.GetValueOrDefault()"" IL_0017: ldfld ""B? A.Prop2"" IL_001c: stloc.1 IL_001d: ldloca.s V_1 IL_001f: call ""bool B?.HasValue.get"" IL_0024: brfalse.s IL_003e IL_0026: ldloca.s V_1 IL_0028: call ""B B?.GetValueOrDefault()"" IL_002d: ldfld ""int? B.Prop3"" IL_0032: stloc.2 IL_0033: ldloca.s V_2 IL_0035: call ""bool int?.HasValue.get"" IL_003a: ldc.i4.0 IL_003b: ceq IL_003d: ret IL_003e: ldc.i4.0 IL_003f: ret }"); verifier.VerifyIL("C.Test4", @" { // Code size 24 (0x18) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""A0 S0.Prop1"" IL_0006: ldfld ""B0 A0.Prop2"" IL_000b: ldfld ""int B0.Prop3"" IL_0010: ldc.i4 0x1a4 IL_0015: ceq IL_0017: ret }"); } [Fact] public void ExtendedPropertyPatterns_02() { var program = @" class C { public C Prop1 { get; set; } public C Prop2 { get; set; } public static void Main() { _ = new C() is { Prop1: null } and { Prop1.Prop2: null }; _ = new C() is { Prop1: null, Prop1.Prop2: null }; } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (9,13): error CS8518: An expression of type 'C' can never match the provided pattern. // _ = new C() is { Prop1: null } and { Prop1.Prop2: null }; Diagnostic(ErrorCode.ERR_IsPatternImpossible, "new C() is { Prop1: null } and { Prop1.Prop2: null }").WithArguments("C").WithLocation(9, 13), // (10,13): error CS8518: An expression of type 'C' can never match the provided pattern. // _ = new C() is { Prop1: null, Prop1.Prop2: null }; Diagnostic(ErrorCode.ERR_IsPatternImpossible, "new C() is { Prop1: null, Prop1.Prop2: null }").WithArguments("C").WithLocation(10, 13) ); } [Fact] public void ExtendedPropertyPatterns_03() { var program = @" using System; class C { C _prop1; C _prop2; C Prop1 { get { Console.WriteLine(nameof(Prop1)); return _prop1; } set => _prop1 = value; } C Prop2 { get { Console.WriteLine(nameof(Prop2)); return _prop2; } set => _prop2 = value; } public static void Main() { Test(null); Test(new()); Test(new() { Prop1 = new() }); Test(new() { Prop1 = new() { Prop2 = new() } }); } static void Test(C o) { Console.WriteLine(nameof(Test)); var result = o switch { {Prop1: null} => 1, {Prop1.Prop2: null} => 2, _ => -1, }; Console.WriteLine(result); } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var expectedOutput = @" Test -1 Test Prop1 1 Test Prop1 Prop2 2 Test Prop1 Prop2 -1"; var verifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); verifier.VerifyIL("C.Test", @" { // Code size 50 (0x32) .maxstack 1 .locals init (int V_0, C V_1) IL_0000: ldstr ""Test"" IL_0005: call ""void System.Console.WriteLine(string)"" IL_000a: ldarg.0 IL_000b: brfalse.s IL_0029 IL_000d: ldarg.0 IL_000e: callvirt ""C C.Prop1.get"" IL_0013: stloc.1 IL_0014: ldloc.1 IL_0015: brfalse.s IL_0021 IL_0017: ldloc.1 IL_0018: callvirt ""C C.Prop2.get"" IL_001d: brfalse.s IL_0025 IL_001f: br.s IL_0029 IL_0021: ldc.i4.1 IL_0022: stloc.0 IL_0023: br.s IL_002b IL_0025: ldc.i4.2 IL_0026: stloc.0 IL_0027: br.s IL_002b IL_0029: ldc.i4.m1 IL_002a: stloc.0 IL_002b: ldloc.0 IL_002c: call ""void System.Console.WriteLine(int)"" IL_0031: ret }"); } [Fact] public void ExtendedPropertyPatterns_04() { var program = @" class C { public static void Main() { _ = new C() is { Prop1<int>.Prop2: {} }; _ = new C() is { Prop1->Prop2: {} }; _ = new C() is { Prop1!.Prop2: {} }; _ = new C() is { Prop1?.Prop2: {} }; _ = new C() is { Prop1[0]: {} }; _ = new C() is { 1: {} }; } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (6,26): error CS8918: Identifier or a simple member access expected. // _ = new C() is { Prop1<int>.Prop2: {} }; Diagnostic(ErrorCode.ERR_InvalidNameInSubpattern, "Prop1<int>").WithLocation(6, 26), // (7,26): error CS8918: Identifier or a simple member access expected. // _ = new C() is { Prop1->Prop2: {} }; Diagnostic(ErrorCode.ERR_InvalidNameInSubpattern, "Prop1->Prop2").WithLocation(7, 26), // (8,26): error CS8918: Identifier or a simple member access expected. // _ = new C() is { Prop1!.Prop2: {} }; Diagnostic(ErrorCode.ERR_InvalidNameInSubpattern, "Prop1!").WithLocation(8, 26), // (9,26): error CS8918: Identifier or a simple member access expected. // _ = new C() is { Prop1?.Prop2: {} }; Diagnostic(ErrorCode.ERR_InvalidNameInSubpattern, "Prop1?.Prop2").WithLocation(9, 26), // (10,26): error CS8503: A property subpattern requires a reference to the property or field to be matched, e.g. '{ Name: Prop1[0] }' // _ = new C() is { Prop1[0]: {} }; Diagnostic(ErrorCode.ERR_PropertyPatternNameMissing, "Prop1[0]").WithArguments("Prop1[0]").WithLocation(10, 26), // (10,26): error CS0246: The type or namespace name 'Prop1' could not be found (are you missing a using directive or an assembly reference?) // _ = new C() is { Prop1[0]: {} }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Prop1").WithArguments("Prop1").WithLocation(10, 26), // (10,31): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // _ = new C() is { Prop1[0]: {} }; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[0]").WithLocation(10, 31), // (10,34): error CS1003: Syntax error, ',' expected // _ = new C() is { Prop1[0]: {} }; Diagnostic(ErrorCode.ERR_SyntaxError, ":").WithArguments(",", ":").WithLocation(10, 34), // (10,36): error CS1003: Syntax error, ',' expected // _ = new C() is { Prop1[0]: {} }; Diagnostic(ErrorCode.ERR_SyntaxError, "{").WithArguments(",", "{").WithLocation(10, 36), // (11,26): error CS8918: Identifier or a simple member access expected. // _ = new C() is { 1: {} }; Diagnostic(ErrorCode.ERR_InvalidNameInSubpattern, "1").WithLocation(11, 26)); } [Fact, WorkItem(52956, "https://github.com/dotnet/roslyn/issues/52956")] public void ExtendedPropertyPatterns_05() { var program = @" class C { C Field1, Field2, Field3, Field4; public void M() { _ = this is { Field1.Field2.Field3: {} }; _ = this is { Field4: {} }; } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (4,7): warning CS0649: Field 'C.Field1' is never assigned to, and will always have its default value null // C Field1, Field2, Field3, Field4; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field1").WithArguments("C.Field1", "null").WithLocation(4, 7), // (4,15): warning CS0649: Field 'C.Field2' is never assigned to, and will always have its default value null // C Field1, Field2, Field3, Field4; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field2").WithArguments("C.Field2", "null").WithLocation(4, 15), // (4,23): warning CS0649: Field 'C.Field3' is never assigned to, and will always have its default value null // C Field1, Field2, Field3, Field4; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field3").WithArguments("C.Field3", "null").WithLocation(4, 23), // (4,31): warning CS0649: Field 'C.Field4' is never assigned to, and will always have its default value null // C Field1, Field2, Field3, Field4; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field4").WithArguments("C.Field4", "null").WithLocation(4, 31) ); } [Fact, WorkItem(52956, "https://github.com/dotnet/roslyn/issues/52956")] public void ExtendedPropertyPatterns_05_NestedRecursivePattern() { var program = @" class C { C Field1, Field2, Field3, Field4; public void M() { _ = this is { Field1: { Field2.Field3.Field4: not null } }; } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (4,7): warning CS0649: Field 'C.Field1' is never assigned to, and will always have its default value null // C Field1, Field2, Field3, Field4; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field1").WithArguments("C.Field1", "null").WithLocation(4, 7), // (4,15): warning CS0649: Field 'C.Field2' is never assigned to, and will always have its default value null // C Field1, Field2, Field3, Field4; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field2").WithArguments("C.Field2", "null").WithLocation(4, 15), // (4,23): warning CS0649: Field 'C.Field3' is never assigned to, and will always have its default value null // C Field1, Field2, Field3, Field4; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field3").WithArguments("C.Field3", "null").WithLocation(4, 23), // (4,31): warning CS0649: Field 'C.Field4' is never assigned to, and will always have its default value null // C Field1, Field2, Field3, Field4; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field4").WithArguments("C.Field4", "null").WithLocation(4, 31) ); } [Fact, WorkItem(52956, "https://github.com/dotnet/roslyn/issues/52956")] public void ExtendedPropertyPatterns_05_Properties() { var program = @" class C { C Prop1 { get; set; } C Prop2 { get; set; } C Prop3 { get; set; } C Prop4 { get; set; } public void M() { _ = this is { Prop1.Prop2.Prop3: {} }; _ = this is { Prop4: {} }; } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics(); } [Fact] public void ExtendedPropertyPatterns_IOperation_Properties() { var src = @" class Program { static void M(A a) /*<bind>*/{ _ = a is { Prop1.Prop2.Prop3: null }; }/*</bind>*/ } class A { public B Prop1 => null; } class B { public C Prop2 => null; } class C { public object Prop3 => null; } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var isPattern = tree.GetRoot().DescendantNodes().OfType<IsPatternExpressionSyntax>().Single(); VerifyOperationTree(comp, model.GetOperation(isPattern), @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'a is { Prop ... op3: null }') Value: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: A) (Syntax: 'a') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null) (Syntax: '{ Prop1.Pro ... op3: null }') (InputType: A, NarrowedType: A, DeclaredSymbol: null, MatchedType: A, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Prop1') Member: IPropertyReferenceOperation: B A.Prop1 { get; } (OperationKind.PropertyReference, Type: B) (Syntax: 'Prop1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Prop1') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'Prop1') (InputType: B, NarrowedType: B, DeclaredSymbol: null, MatchedType: B, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Prop1.Prop2') Member: IPropertyReferenceOperation: C B.Prop2 { get; } (OperationKind.PropertyReference, Type: C) (Syntax: 'Prop1.Prop2') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Prop1.Prop2') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'Prop1.Prop2') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Prop1.Prop2.Prop3') Member: IPropertyReferenceOperation: System.Object C.Prop3 { get; } (OperationKind.PropertyReference, Type: System.Object) (Syntax: 'Prop1.Prop2.Prop3') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'Prop1.Prop2.Prop3') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: System.Object, NarrowedType: System.Object) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '_ = a is { ... p3: null };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: '_ = a is { ... op3: null }') Left: IDiscardOperation (Symbol: System.Boolean _) (OperationKind.Discard, Type: System.Boolean) (Syntax: '_') Right: IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'a is { Prop ... op3: null }') Value: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: A) (Syntax: 'a') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null) (Syntax: '{ Prop1.Pro ... op3: null }') (InputType: A, NarrowedType: A, DeclaredSymbol: null, MatchedType: A, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Prop1') Member: IPropertyReferenceOperation: B A.Prop1 { get; } (OperationKind.PropertyReference, Type: B) (Syntax: 'Prop1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Prop1') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'Prop1') (InputType: B, NarrowedType: B, DeclaredSymbol: null, MatchedType: B, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Prop1.Prop2') Member: IPropertyReferenceOperation: C B.Prop2 { get; } (OperationKind.PropertyReference, Type: C) (Syntax: 'Prop1.Prop2') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Prop1.Prop2') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'Prop1.Prop2') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Prop1.Prop2.Prop3') Member: IPropertyReferenceOperation: System.Object C.Prop3 { get; } (OperationKind.PropertyReference, Type: System.Object) (Syntax: 'Prop1.Prop2.Prop3') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'Prop1.Prop2.Prop3') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: System.Object, NarrowedType: System.Object) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, DiagnosticDescription.None, parseOptions: TestOptions.Regular10); } [Fact] public void ExtendedPropertyPatterns_IOperation_FieldsInStructs() { var src = @" class Program { static void M(A a) /*<bind>*/{ _ = a is { Field1.Field2.Field3: null, Field4: null }; }/*</bind>*/ } struct A { public B? Field1; public B? Field4; } struct B { public C? Field2; } struct C { public object Field3; } "; var expectedDiagnostics = new[] { // (9,22): warning CS0649: Field 'A.Field1' is never assigned to, and will always have its default value // struct A { public B? Field1; public B? Field4; } Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field1").WithArguments("A.Field1", "").WithLocation(9, 22), // (9,40): warning CS0649: Field 'A.Field4' is never assigned to, and will always have its default value // struct A { public B? Field1; public B? Field4; } Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field4").WithArguments("A.Field4", "").WithLocation(9, 40), // (10,22): warning CS0649: Field 'B.Field2' is never assigned to, and will always have its default value // struct B { public C? Field2; } Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field2").WithArguments("B.Field2", "").WithLocation(10, 22), // (11,26): warning CS0649: Field 'C.Field3' is never assigned to, and will always have its default value null // struct C { public object Field3; } Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field3").WithArguments("C.Field3", "null").WithLocation(11, 26) }; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); comp.VerifyDiagnostics(expectedDiagnostics); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var isPattern = tree.GetRoot().DescendantNodes().OfType<IsPatternExpressionSyntax>().Single(); VerifyOperationTree(comp, model.GetOperation(isPattern), @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'a is { Fiel ... ld4: null }') Value: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: A) (Syntax: 'a') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null) (Syntax: '{ Field1.Fi ... ld4: null }') (InputType: A, NarrowedType: A, DeclaredSymbol: null, MatchedType: A, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (2): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Field1') Member: IFieldReferenceOperation: B? A.Field1 (OperationKind.FieldReference, Type: B?) (Syntax: 'Field1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Field1') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'Field1') (InputType: B, NarrowedType: B, DeclaredSymbol: null, MatchedType: B, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Field1.Field2') Member: IFieldReferenceOperation: C? B.Field2 (OperationKind.FieldReference, Type: C?) (Syntax: 'Field1.Field2') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Field1.Field2') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'Field1.Field2') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Field1.Field2.Field3') Member: IFieldReferenceOperation: System.Object C.Field3 (OperationKind.FieldReference, Type: System.Object) (Syntax: 'Field1.Field2.Field3') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'Field1.Field2.Field3') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: System.Object, NarrowedType: System.Object) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null) (Syntax: 'Field4: null') Member: IFieldReferenceOperation: B? A.Field4 (OperationKind.FieldReference, Type: B?) (Syntax: 'Field4') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Field4') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: B?, NarrowedType: B?) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: B?, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '_ = a is { ... d4: null };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: '_ = a is { ... ld4: null }') Left: IDiscardOperation (Symbol: System.Boolean _) (OperationKind.Discard, Type: System.Boolean) (Syntax: '_') Right: IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'a is { Fiel ... ld4: null }') Value: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: A) (Syntax: 'a') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null) (Syntax: '{ Field1.Fi ... ld4: null }') (InputType: A, NarrowedType: A, DeclaredSymbol: null, MatchedType: A, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (2): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Field1') Member: IFieldReferenceOperation: B? A.Field1 (OperationKind.FieldReference, Type: B?) (Syntax: 'Field1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Field1') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'Field1') (InputType: B, NarrowedType: B, DeclaredSymbol: null, MatchedType: B, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Field1.Field2') Member: IFieldReferenceOperation: C? B.Field2 (OperationKind.FieldReference, Type: C?) (Syntax: 'Field1.Field2') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Field1.Field2') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'Field1.Field2') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Field1.Field2.Field3') Member: IFieldReferenceOperation: System.Object C.Field3 (OperationKind.FieldReference, Type: System.Object) (Syntax: 'Field1.Field2.Field3') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'Field1.Field2.Field3') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: System.Object, NarrowedType: System.Object) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null) (Syntax: 'Field4: null') Member: IFieldReferenceOperation: B? A.Field4 (OperationKind.FieldReference, Type: B?) (Syntax: 'Field4') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Field4') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: B?, NarrowedType: B?) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: B?, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NullLiteral) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.Regular10); } [Fact] public void ExtendedPropertyPatterns_Explainer() { var src = @" class Program { void M(A a) { _ = a switch // 1 { { BProp.BoolProp: true } => 1 }; _ = a switch // 2 { { BProp.IntProp: <= 0 } => 1 }; } } class A { public B BProp => null; } class B { public bool BoolProp => true; public int IntProp => 0; } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); comp.VerifyDiagnostics( // (6,15): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '{ BProp: { BoolProp: false } }' is not covered. // _ = a switch // 1 Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("{ BProp: { BoolProp: false } }").WithLocation(6, 15), // (11,15): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '{ BProp: { IntProp: 1 } }' is not covered. // _ = a switch // 2 Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("{ BProp: { IntProp: 1 } }").WithLocation(11, 15) ); } [Fact, WorkItem(52956, "https://github.com/dotnet/roslyn/issues/52956")] public void ExtendedPropertyPatterns_BadMemberAccess() { var program = @" class C { C Field1, Field2, Field3; public static void Main() { _ = new C() is { Field1?.Field2: {} }; // 1 _ = new C() is { Field1!.Field2: {} }; // 2 _ = new C() is { Missing: null }; // 3 _ = new C() is { Field3.Missing: {} }; // 4 _ = new C() is { Missing1.Missing2: {} }; // 5 } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (4,7): warning CS0169: The field 'C.Field1' is never used // C Field1, Field2, Field3; Diagnostic(ErrorCode.WRN_UnreferencedField, "Field1").WithArguments("C.Field1").WithLocation(4, 7), // (4,15): warning CS0169: The field 'C.Field2' is never used // C Field1, Field2, Field3; Diagnostic(ErrorCode.WRN_UnreferencedField, "Field2").WithArguments("C.Field2").WithLocation(4, 15), // (4,23): warning CS0649: Field 'C.Field3' is never assigned to, and will always have its default value null // C Field1, Field2, Field3; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field3").WithArguments("C.Field3", "null").WithLocation(4, 23), // (7,26): error CS8918: Identifier or a simple member access expected. // _ = new C() is { Field1?.Field2: {} }; // 1 Diagnostic(ErrorCode.ERR_InvalidNameInSubpattern, "Field1?.Field2").WithLocation(7, 26), // (8,26): error CS8918: Identifier or a simple member access expected. // _ = new C() is { Field1!.Field2: {} }; // 2 Diagnostic(ErrorCode.ERR_InvalidNameInSubpattern, "Field1!").WithLocation(8, 26), // (9,26): error CS0117: 'C' does not contain a definition for 'Missing' // _ = new C() is { Missing: null }; // 3 Diagnostic(ErrorCode.ERR_NoSuchMember, "Missing").WithArguments("C", "Missing").WithLocation(9, 26), // (10,33): error CS0117: 'C' does not contain a definition for 'Missing' // _ = new C() is { Field3.Missing: {} }; // 4 Diagnostic(ErrorCode.ERR_NoSuchMember, "Missing").WithArguments("C", "Missing").WithLocation(10, 33), // (11,26): error CS0117: 'C' does not contain a definition for 'Missing1' // _ = new C() is { Missing1.Missing2: {} }; // 5 Diagnostic(ErrorCode.ERR_NoSuchMember, "Missing1").WithArguments("C", "Missing1").WithLocation(11, 26) ); } [Fact] public void ExtendedPropertyPatterns_IOperationOnMissing() { var program = @" class C { public void M() { _ = this is { Missing: null }; } } "; var comp = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); comp.VerifyEmitDiagnostics( // (6,23): error CS0117: 'C' does not contain a definition for 'Missing' // _ = this is { Missing: null }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Missing").WithArguments("C", "Missing").WithLocation(6, 23) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var isPattern = tree.GetRoot().DescendantNodes().OfType<IsPatternExpressionSyntax>().Single(); VerifyOperationTree(comp, model.GetOperation(isPattern), @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'this is { M ... ing: null }') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid) (Syntax: '{ Missing: null }') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid) (Syntax: 'Missing: null') Member: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'Missing') Children(0) Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: ?, NarrowedType: ?) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') "); } [Fact] public void ExtendedPropertyPatterns_IOperationOnNestedMissing() { var program = @" class C { int Property { get; set; } public void M() { _ = this is { Property.Missing: null }; } } "; var comp = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); comp.VerifyEmitDiagnostics( // (7,32): error CS0117: 'int' does not contain a definition for 'Missing' // _ = this is { Property.Missing: null }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Missing").WithArguments("int", "Missing").WithLocation(7, 32) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var isPattern = tree.GetRoot().DescendantNodes().OfType<IsPatternExpressionSyntax>().Single(); VerifyOperationTree(comp, model.GetOperation(isPattern), @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'this is { P ... ing: null }') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid) (Syntax: '{ Property. ... ing: null }') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Property') Member: IPropertyReferenceOperation: System.Int32 C.Property { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'Property') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'Property') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'Property') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: null, MatchedType: System.Int32, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'Property.Missing') Member: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'Property.Missing') Children(0) Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: ?, NarrowedType: ?) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') "); } [Fact] public void ExtendedPropertyPatterns_IOperationOnTwoMissing() { var program = @" class C { public void M() { _ = this is { Missing1.Missing2: null }; } } "; var comp = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); comp.VerifyEmitDiagnostics( // (6,23): error CS0117: 'C' does not contain a definition for 'Missing1' // _ = this is { Missing1.Missing2: null }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Missing1").WithArguments("C", "Missing1").WithLocation(6, 23) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var isPattern = tree.GetRoot().DescendantNodes().OfType<IsPatternExpressionSyntax>().Single(); VerifyOperationTree(comp, model.GetOperation(isPattern), @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'this is { M ... ng2: null }') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid) (Syntax: '{ Missing1. ... ng2: null }') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'Missing1') Member: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'Missing1') Children(0) Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'Missing1') (InputType: ?, NarrowedType: ?, DeclaredSymbol: null, MatchedType: ?, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'Missing1.Missing2') Member: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'Missing1.Missing2') Children(0) Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: ?, NarrowedType: ?) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') "); } [Fact, WorkItem(53484, "https://github.com/dotnet/roslyn/issues/53484")] public void ExtendedPropertyPatterns_SuppressionOnPattern() { var program = @" #nullable enable public class ContainerType { public class Type { public void M() { const Type c = null!; if (this is c!) {} if (this is (c!)) {} if (this is Type!) {} // 1 if (this is ContainerType!.Type) {} // 2 if (this is ContainerType.Type!) {} // 3 } } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (12,25): error CS8598: The suppression operator is not allowed in this context // if (this is Type!) {} // 1 Diagnostic(ErrorCode.ERR_IllegalSuppression, "Type!").WithLocation(12, 25), // (13,25): error CS8598: The suppression operator is not allowed in this context // if (this is ContainerType!.Type) {} // 2 Diagnostic(ErrorCode.ERR_IllegalSuppression, "ContainerType").WithLocation(13, 25), // (14,25): error CS8598: The suppression operator is not allowed in this context // if (this is ContainerType.Type!) {} // 3 Diagnostic(ErrorCode.ERR_IllegalSuppression, "ContainerType.Type!").WithLocation(14, 25) ); } [Fact, WorkItem(53484, "https://github.com/dotnet/roslyn/issues/53484")] public void ExtendedPropertyPatterns_PointerAccessInPattern() { var program = @" public class Type { public unsafe void M(S* s) { if (0 is s->X) {} } } public struct S { public int X; } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns, options: TestOptions.UnsafeDebugDll); compilation.VerifyEmitDiagnostics( // (6,18): error CS0150: A constant value is expected // if (0 is s->X) {} Diagnostic(ErrorCode.ERR_ConstantExpected, "s->X").WithLocation(6, 18) ); } [Fact] public void ExtendedPropertyPatterns_SymbolInfo_01() { var source = @" using System; class Program { public static void Main() { P p = new P(); Console.WriteLine(p is { X.Y: {}, Y.X: {} }); } } class P { public P X { get; } public P Y; } "; var compilation = CreatePatternCompilation(source); compilation.VerifyEmitDiagnostics( // (14,14): warning CS0649: Field 'P.Y' is never assigned to, and will always have its default value null // public P Y; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Y").WithArguments("P.Y", "null").WithLocation(14, 14) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var subpatterns = tree.GetRoot().DescendantNodes().OfType<SubpatternSyntax>().ToArray(); Assert.Equal(2, subpatterns.Length); AssertEmpty(model.GetSymbolInfo(subpatterns[0])); AssertEmpty(model.GetSymbolInfo(subpatterns[0].ExpressionColon)); var xy = subpatterns[0].ExpressionColon.Expression; var xySymbol = model.GetSymbolInfo(xy); Assert.Equal(CandidateReason.None, xySymbol.CandidateReason); Assert.Equal("P P.Y", xySymbol.Symbol.ToTestDisplayString()); var x = ((MemberAccessExpressionSyntax)subpatterns[0].ExpressionColon.Expression).Expression; var xSymbol = model.GetSymbolInfo(x); Assert.Equal(CandidateReason.None, xSymbol.CandidateReason); Assert.Equal("P P.X { get; }", xSymbol.Symbol.ToTestDisplayString()); var yName = ((MemberAccessExpressionSyntax)subpatterns[0].ExpressionColon.Expression).Name; var yNameSymbol = model.GetSymbolInfo(yName); Assert.Equal(CandidateReason.None, yNameSymbol.CandidateReason); Assert.Equal("P P.Y", yNameSymbol.Symbol.ToTestDisplayString()); AssertEmpty(model.GetSymbolInfo(subpatterns[1])); AssertEmpty(model.GetSymbolInfo(subpatterns[1].ExpressionColon)); var yx = subpatterns[1].ExpressionColon.Expression; var yxSymbol = model.GetSymbolInfo(yx); Assert.NotEqual(default, yxSymbol); Assert.Equal(CandidateReason.None, yxSymbol.CandidateReason); Assert.Equal("P P.X { get; }", yxSymbol.Symbol.ToTestDisplayString()); var y = ((MemberAccessExpressionSyntax)subpatterns[1].ExpressionColon.Expression).Expression; var ySymbol = model.GetSymbolInfo(y); Assert.Equal(CandidateReason.None, ySymbol.CandidateReason); Assert.Equal("P P.Y", ySymbol.Symbol.ToTestDisplayString()); var xName = ((MemberAccessExpressionSyntax)subpatterns[1].ExpressionColon.Expression).Name; var xNameSymbol = model.GetSymbolInfo(xName); Assert.Equal(CandidateReason.None, xNameSymbol.CandidateReason); Assert.Equal("P P.X { get; }", xNameSymbol.Symbol.ToTestDisplayString()); } [Fact] public void ExtendedPropertyPatterns_SymbolInfo_02() { var source = @" using System; class Program { public static void Main() { P p = null; Console.WriteLine(p is { X.Y: {}, Y.X: {}, }); } } interface I1 { P X { get; } P Y { get; } } interface I2 { P X { get; } P Y { get; } } interface P : I1, I2 { // X and Y inherited ambiguously } "; var compilation = CreatePatternCompilation(source); compilation.VerifyEmitDiagnostics( // (8,34): error CS0229: Ambiguity between 'I1.X' and 'I2.X' // Console.WriteLine(p is { X.Y: {}, Y.X: {}, }); Diagnostic(ErrorCode.ERR_AmbigMember, "X").WithArguments("I1.X", "I2.X").WithLocation(8, 34), // (8,43): error CS0229: Ambiguity between 'I1.Y' and 'I2.Y' // Console.WriteLine(p is { X.Y: {}, Y.X: {}, }); Diagnostic(ErrorCode.ERR_AmbigMember, "Y").WithArguments("I1.Y", "I2.Y").WithLocation(8, 43) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var subpatterns = tree.GetRoot().DescendantNodes().OfType<SubpatternSyntax>().ToArray(); Assert.Equal(2, subpatterns.Length); AssertEmpty(model.GetSymbolInfo(subpatterns[0])); AssertEmpty(model.GetSymbolInfo(subpatterns[0].ExpressionColon)); var x = ((MemberAccessExpressionSyntax)subpatterns[0].ExpressionColon.Expression).Expression; var xSymbol = model.GetSymbolInfo(x); Assert.Equal(CandidateReason.Ambiguous, xSymbol.CandidateReason); Assert.Null(xSymbol.Symbol); Assert.Equal(2, xSymbol.CandidateSymbols.Length); Assert.Equal("P I1.X { get; }", xSymbol.CandidateSymbols[0].ToTestDisplayString()); Assert.Equal("P I2.X { get; }", xSymbol.CandidateSymbols[1].ToTestDisplayString()); AssertEmpty(model.GetSymbolInfo(subpatterns[1])); AssertEmpty(model.GetSymbolInfo(subpatterns[1].ExpressionColon)); var y = ((MemberAccessExpressionSyntax)subpatterns[1].ExpressionColon.Expression).Expression; var ySymbol = model.GetSymbolInfo(y); Assert.Equal(CandidateReason.Ambiguous, ySymbol.CandidateReason); Assert.Null(ySymbol.Symbol); Assert.Equal(2, ySymbol.CandidateSymbols.Length); Assert.Equal("P I1.Y { get; }", ySymbol.CandidateSymbols[0].ToTestDisplayString()); Assert.Equal("P I2.Y { get; }", ySymbol.CandidateSymbols[1].ToTestDisplayString()); } [Fact] public void ExtendedPropertyPatterns_SymbolInfo_03() { var source = @" using System; class Program { public static void Main() { P p = null; Console.WriteLine(p is { X.Y: {}, Y.X: {}, }); } } class P { } "; var compilation = CreatePatternCompilation(source); compilation.VerifyEmitDiagnostics( // (8,34): error CS0117: 'P' does not contain a definition for 'X' // Console.WriteLine(p is { X: 3, Y: 4 }); Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("P", "X").WithLocation(8, 34) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var subpatterns = tree.GetRoot().DescendantNodes().OfType<SubpatternSyntax>().ToArray(); Assert.Equal(2, subpatterns.Length); AssertEmpty(model.GetSymbolInfo(subpatterns[0])); AssertEmpty(model.GetSymbolInfo(subpatterns[0].ExpressionColon)); var x = subpatterns[0].ExpressionColon.Expression; var xSymbol = model.GetSymbolInfo(x); Assert.Equal(CandidateReason.None, xSymbol.CandidateReason); Assert.Null(xSymbol.Symbol); Assert.Empty(xSymbol.CandidateSymbols); AssertEmpty(model.GetSymbolInfo(subpatterns[1])); AssertEmpty(model.GetSymbolInfo(subpatterns[1].ExpressionColon)); var y = subpatterns[1].ExpressionColon.Expression; var ySymbol = model.GetSymbolInfo(y); Assert.Equal(CandidateReason.None, ySymbol.CandidateReason); Assert.Null(ySymbol.Symbol); Assert.Empty(ySymbol.CandidateSymbols); } [Fact] public void ExtendedPropertyPatterns_SymbolInfo_04() { var source = @" using System; class Program { public static void Main() { Console.WriteLine(new C() is { X.Y: {} }); Console.WriteLine(new S() is { Y.X: {} }); } } class C { public S? X { get; } } struct S { public C Y; } "; var compilation = CreatePatternCompilation(source); compilation.VerifyEmitDiagnostics( // (17,14): warning CS0649: Field 'S.Y' is never assigned to, and will always have its default value null // public C Y; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Y").WithArguments("S.Y", "null").WithLocation(17, 14) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var subpatterns = tree.GetRoot().DescendantNodes().OfType<SubpatternSyntax>().ToArray(); Assert.Equal(2, subpatterns.Length); AssertEmpty(model.GetSymbolInfo(subpatterns[0])); AssertEmpty(model.GetSymbolInfo(subpatterns[0].ExpressionColon)); var xy = subpatterns[0].ExpressionColon.Expression; var xySymbol = model.GetSymbolInfo(xy); Assert.Equal(CandidateReason.None, xySymbol.CandidateReason); Assert.Equal("C S.Y", xySymbol.Symbol.ToTestDisplayString()); var xyType = model.GetTypeInfo(xy); Assert.Equal("C", xyType.Type.ToTestDisplayString()); Assert.Equal("C", xyType.ConvertedType.ToTestDisplayString()); var x = ((MemberAccessExpressionSyntax)subpatterns[0].ExpressionColon.Expression).Expression; var xSymbol = model.GetSymbolInfo(x); Assert.Equal(CandidateReason.None, xSymbol.CandidateReason); Assert.Equal("S? C.X { get; }", xSymbol.Symbol.ToTestDisplayString()); var xType = model.GetTypeInfo(x); Assert.Equal("S?", xType.Type.ToTestDisplayString()); Assert.Equal("S?", xType.ConvertedType.ToTestDisplayString()); var yName = ((MemberAccessExpressionSyntax)subpatterns[0].ExpressionColon.Expression).Name; var yNameSymbol = model.GetSymbolInfo(yName); Assert.Equal(CandidateReason.None, yNameSymbol.CandidateReason); Assert.Equal("C S.Y", yNameSymbol.Symbol.ToTestDisplayString()); var yNameType = model.GetTypeInfo(yName); Assert.Equal("C", yNameType.Type.ToTestDisplayString()); Assert.Equal("C", yNameType.ConvertedType.ToTestDisplayString()); AssertEmpty(model.GetSymbolInfo(subpatterns[1])); AssertEmpty(model.GetSymbolInfo(subpatterns[1].ExpressionColon)); var yx = subpatterns[1].ExpressionColon.Expression; var yxSymbol = model.GetSymbolInfo(yx); Assert.NotEqual(default, yxSymbol); Assert.Equal(CandidateReason.None, yxSymbol.CandidateReason); Assert.Equal("S? C.X { get; }", yxSymbol.Symbol.ToTestDisplayString()); var yxType = model.GetTypeInfo(yx); Assert.Equal("S?", yxType.Type.ToTestDisplayString()); Assert.Equal("S?", yxType.ConvertedType.ToTestDisplayString()); var y = ((MemberAccessExpressionSyntax)subpatterns[1].ExpressionColon.Expression).Expression; var ySymbol = model.GetSymbolInfo(y); Assert.Equal(CandidateReason.None, ySymbol.CandidateReason); Assert.Equal("C S.Y", ySymbol.Symbol.ToTestDisplayString()); var yType = model.GetTypeInfo(y); Assert.Equal("C", yType.Type.ToTestDisplayString()); Assert.Equal("C", yType.ConvertedType.ToTestDisplayString()); var xName = ((MemberAccessExpressionSyntax)subpatterns[1].ExpressionColon.Expression).Name; var xNameSymbol = model.GetSymbolInfo(xName); Assert.Equal(CandidateReason.None, xNameSymbol.CandidateReason); Assert.Equal("S? C.X { get; }", xNameSymbol.Symbol.ToTestDisplayString()); var xNameType = model.GetTypeInfo(xName); Assert.Equal("S?", xNameType.Type.ToTestDisplayString()); Assert.Equal("S?", xNameType.ConvertedType.ToTestDisplayString()); var verifier = CompileAndVerify(compilation); verifier.VerifyIL("Program.Main", @" { // Code size 92 (0x5c) .maxstack 2 .locals init (C V_0, S? V_1, S V_2) IL_0000: nop IL_0001: newobj ""C..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_002b IL_000a: ldloc.0 IL_000b: callvirt ""S? C.X.get"" IL_0010: stloc.1 IL_0011: ldloca.s V_1 IL_0013: call ""bool S?.HasValue.get"" IL_0018: brfalse.s IL_002b IL_001a: ldloca.s V_1 IL_001c: call ""S S?.GetValueOrDefault()"" IL_0021: ldfld ""C S.Y"" IL_0026: ldnull IL_0027: cgt.un IL_0029: br.s IL_002c IL_002b: ldc.i4.0 IL_002c: call ""void System.Console.WriteLine(bool)"" IL_0031: nop IL_0032: ldloca.s V_2 IL_0034: initobj ""S"" IL_003a: ldloc.2 IL_003b: ldfld ""C S.Y"" IL_0040: stloc.0 IL_0041: ldloc.0 IL_0042: brfalse.s IL_0054 IL_0044: ldloc.0 IL_0045: callvirt ""S? C.X.get"" IL_004a: stloc.1 IL_004b: ldloca.s V_1 IL_004d: call ""bool S?.HasValue.get"" IL_0052: br.s IL_0055 IL_0054: ldc.i4.0 IL_0055: call ""void System.Console.WriteLine(bool)"" IL_005a: nop IL_005b: ret } "); } [Fact] public void ExtendedPropertyPatterns_Nullability_Properties() { var program = @" #nullable enable class C { C? Prop { get; } public void M() { if (this is { Prop.Prop: null }) { this.Prop.ToString(); this.Prop.Prop.ToString(); // 1 } if (this is { Prop.Prop: {} }) { this.Prop.ToString(); this.Prop.Prop.ToString(); } if (this is { Prop: null } && this is { Prop.Prop: null }) { this.Prop.ToString(); this.Prop.Prop.ToString(); // 2 } if (this is { Prop: null } || this is { Prop.Prop: null }) { this.Prop.ToString(); // 3 this.Prop.Prop.ToString(); // 4 } } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // this.Prop.Prop.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "this.Prop.Prop").WithLocation(9, 13), // (20,13): warning CS8602: Dereference of a possibly null reference. // this.Prop.Prop.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "this.Prop.Prop").WithLocation(20, 13), // (25,13): warning CS8602: Dereference of a possibly null reference. // this.Prop.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "this.Prop").WithLocation(25, 13), // (26,13): warning CS8602: Dereference of a possibly null reference. // this.Prop.Prop.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "this.Prop.Prop").WithLocation(26, 13)); } [Fact] public void ExtendedPropertyPatterns_Nullability_AnnotatedFields() { var program = @" #nullable enable class C { public void M(C1 c1) { if (c1 is { Prop1.Prop2: null }) { c1.Prop1.ToString(); c1.Prop1.Prop2.ToString(); // 1 } if (c1 is { Prop1.Prop2: {} }) { c1.Prop1.ToString(); c1.Prop1.Prop2.ToString(); } if (c1 is { Prop1: null } && c1 is { Prop1.Prop2: null }) { c1.Prop1.ToString(); c1.Prop1.Prop2.ToString(); // 2 } if (c1 is { Prop1: null } || c1 is { Prop1.Prop2: null }) { c1.Prop1.ToString(); // 3 c1.Prop1.Prop2.ToString(); // 4 } } } class C1 { public C2? Prop1 = null; } class C2 { public object? Prop2 = null; } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // c1.Prop1.Prop2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.Prop1.Prop2").WithLocation(8, 13), // (19,13): warning CS8602: Dereference of a possibly null reference. // c1.Prop1.Prop2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.Prop1.Prop2").WithLocation(19, 13), // (24,13): warning CS8602: Dereference of a possibly null reference. // c1.Prop1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.Prop1").WithLocation(24, 13), // (25,13): warning CS8602: Dereference of a possibly null reference. // c1.Prop1.Prop2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.Prop1.Prop2").WithLocation(25, 13) ); } [Fact] public void ExtendedPropertyPatterns_Nullability_UnannotatedFields() { var program = @" #nullable enable class C { public void M1(C1 c1) { if (c1 is { Prop1.Prop2: null }) { c1.Prop1.ToString(); c1.Prop1.Prop2.ToString(); // 1 } else { c1.Prop1.ToString(); c1.Prop1.Prop2.ToString(); } } public void M2(C1 c1) { if (c1 is { Prop1.Prop2: {} }) { c1.Prop1.ToString(); c1.Prop1.Prop2.ToString(); } } public void M3(C1 c1) { if (c1 is { Prop1: null } && c1 is { Prop1.Prop2: null }) { c1.Prop1.ToString(); c1.Prop1.Prop2.ToString(); // 2 } else { c1.Prop1.ToString(); // 3 c1.Prop1.Prop2.ToString(); } } public void M4(C1 c1) { if (c1 is { Prop1: null } || c1 is { Prop1.Prop2: null }) { c1.Prop1.ToString(); // 4 c1.Prop1.Prop2.ToString(); // 5 } else { c1.Prop1.ToString(); c1.Prop1.Prop2.ToString(); } } } class C1 { public C2 Prop1 = null!; } class C2 { public object Prop2 = null!; } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // c1.Prop1.Prop2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.Prop1.Prop2").WithLocation(10, 13), // (34,13): warning CS8602: Dereference of a possibly null reference. // c1.Prop1.Prop2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.Prop1.Prop2").WithLocation(34, 13), // (38,13): warning CS8602: Dereference of a possibly null reference. // c1.Prop1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.Prop1").WithLocation(38, 13), // (48,13): warning CS8602: Dereference of a possibly null reference. // c1.Prop1.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.Prop1").WithLocation(48, 13), // (49,13): warning CS8602: Dereference of a possibly null reference. // c1.Prop1.Prop2.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.Prop1.Prop2").WithLocation(49, 13) ); } [Fact] public void ExtendedPropertyPatterns_ExpressionColonInPositionalPattern() { var source = @" class C { C Property { get; set; } void M() { _ = this is (Property.Property: null, Property: null); } public void Deconstruct(out C c1, out C c2) => throw null; } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular9); compilation.VerifyEmitDiagnostics( // (8,22): error CS8773: Feature 'extended property patterns' is not available in C# 9.0. Please use language version 10.0 or greater. // _ = this is (Property.Property: null, Property: null); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "Property.Property").WithArguments("extended property patterns", "10.0").WithLocation(8, 22), // (8,22): error CS1001: Identifier expected // _ = this is (Property.Property: null, Property: null); Diagnostic(ErrorCode.ERR_IdentifierExpected, "Property.Property").WithLocation(8, 22), // (8,47): error CS8517: The name 'Property' does not match the corresponding 'Deconstruct' parameter 'c2'. // _ = this is (Property.Property: null, Property: null); Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "Property").WithArguments("Property", "c2").WithLocation(8, 47) ); } [Fact] public void ExtendedPropertyPatterns_ExpressionColonInITuplePattern() { var source = @" class C { void M() { System.Runtime.CompilerServices.ITuple t = null; var r = t is (X.Y: 3, Y.Z: 4); } } namespace System.Runtime.CompilerServices { public interface ITuple { int Length { get; } object this[int index] { get; } } } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (7,23): error CS1001: Identifier expected // var r = t is (X.Y: 3, Y.Z: 4); Diagnostic(ErrorCode.ERR_IdentifierExpected, "X.Y").WithLocation(7, 23), // (7,31): error CS1001: Identifier expected // var r = t is (X.Y: 3, Y.Z: 4); Diagnostic(ErrorCode.ERR_IdentifierExpected, "Y.Z").WithLocation(7, 31) ); } [Fact] public void ExtendedPropertyPatterns_ExpressionColonInValueTuplePattern() { var source = @" class C { void M() { _ = (1, 2) is (X.Y: 3, Y.Z: 4); } } namespace System.Runtime.CompilerServices { public interface ITuple { int Length { get; } object this[int index] { get; } } } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (6,24): error CS1001: Identifier expected // _ = (1, 2) is (X.Y: 3, Y.Z: 4); Diagnostic(ErrorCode.ERR_IdentifierExpected, "X.Y").WithLocation(6, 24), // (6,32): error CS1001: Identifier expected // _ = (1, 2) is (X.Y: 3, Y.Z: 4); Diagnostic(ErrorCode.ERR_IdentifierExpected, "Y.Z").WithLocation(6, 32) ); } [Fact] public void ExtendedPropertyPatterns_ObsoleteProperty() { var program = @" using System; class C { public void M1(C1 c1) { _ = c1 is { Prop1.Prop2: null }; } } class C1 { [ObsoleteAttribute(""error Prop1"", true)] public C2 Prop1 { get; set; } } class C2 { [ObsoleteAttribute(""error Prop2"", true)] public object Prop2 { get; set; } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (7,21): error CS0619: 'C1.Prop1' is obsolete: 'error Prop1' // _ = c1 is { Prop1.Prop2: null }; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "Prop1").WithArguments("C1.Prop1", "error Prop1").WithLocation(7, 21), // (7,27): error CS0619: 'C2.Prop2' is obsolete: 'error Prop2' // _ = c1 is { Prop1.Prop2: null }; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "Prop2").WithArguments("C2.Prop2", "error Prop2").WithLocation(7, 27) ); } [Fact] public void ExtendedPropertyPatterns_ObsoleteAccessor() { var program = @" using System; class C { public void M1(C1 c1) { _ = c1 is { Prop1.Prop2: null }; } } class C1 { public C2 Prop1 { [ObsoleteAttribute(""error Prop1"", true)] get; set; } } class C2 { public object Prop2 { get; [ObsoleteAttribute(""error Prop2"", true)] set; } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (7,21): error CS0619: 'C1.Prop1.get' is obsolete: 'error Prop1' // _ = c1 is { Prop1.Prop2: null }; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "Prop1.Prop2").WithArguments("C1.Prop1.get", "error Prop1").WithLocation(7, 21) ); } [Fact] public void ExtendedPropertyPatterns_InaccessibleProperty() { var program = @" using System; class C { public void M1(C1 c1) { _ = c1 is { Prop1.Prop2: null }; } } class C1 { private C2 Prop1 { get; set; } } class C2 { private object Prop2 { get; set; } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (7,21): error CS0122: 'C1.Prop1' is inaccessible due to its protection level // _ = c1 is { Prop1.Prop2: null }; Diagnostic(ErrorCode.ERR_BadAccess, "Prop1").WithArguments("C1.Prop1").WithLocation(7, 21) ); } [Fact] public void ExtendedPropertyPatterns_ExpressionTree() { var program = @" using System; using System.Collections.Generic; using System.Linq.Expressions; class C { public void M1(C1 c1) { Expression<Func<C1, bool>> f = (c1) => c1 is { Prop1.Prop2: null }; } } class C1 { public C2 Prop1 { get; set; } } class C2 { public object Prop2 { get; set; } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (9,48): error CS8122: An expression tree may not contain an 'is' pattern-matching operator. // Expression<Func<C1, bool>> f = (c1) => c1 is { Prop1.Prop2: null }; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsIsMatch, "c1 is { Prop1.Prop2: null }").WithLocation(9, 48) ); } [Fact] public void ExtendedPropertyPatterns_EvaluationOrder() { var program = @" if (new C() is { Prop1.True: true, Prop1.Prop2: not null }) { System.Console.WriteLine(""matched1""); } if (new C() is { Prop1.Prop2: not null, Prop1.True: true }) { System.Console.WriteLine(""matched2""); } if (new C() is { Prop1.Prop2: not null, Prop2.True: true }) { System.Console.WriteLine(""matched3""); } if (new C() is { Prop1.Prop2.Prop3.True: true }) { System.Console.WriteLine(""matched3""); } if (new C() is { Prop1: { Prop2.Prop3.True: true } }) { System.Console.WriteLine(""matched4""); } if (new C() is { Prop1.True: false, Prop1.Prop2: not null }) { throw null; } class C { public C Prop1 { get { System.Console.Write(""Prop1 ""); return this; } } public C Prop2 { get { System.Console.Write(""Prop2 ""); return this; } } public C Prop3 { get { System.Console.Write(""Prop3 ""); return this; } } public bool True { get { System.Console.Write(""True ""); return true; } } } "; CompileAndVerify(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns, expectedOutput: @" Prop1 True Prop2 matched1 Prop1 Prop2 True matched2 Prop1 Prop2 Prop2 True matched3 Prop1 Prop2 Prop3 True matched3 Prop1 Prop2 Prop3 True matched4 Prop1 True"); } [Fact] public void ExtendedPropertyPatterns_StaticMembers() { var program = @" _ = new C() is { Static: null }; // 1 _ = new C() is { Instance.Static: null }; // 2 _ = new C() is { Static.Instance: null }; // 3 class C { public C Instance { get; set; } public static C Static { get; set; } } "; var comp = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); comp.VerifyEmitDiagnostics( // (2,18): error CS0176: Member 'C.Static' cannot be accessed with an instance reference; qualify it with a type name instead // _ = new C() is { Static: null }; // 1 Diagnostic(ErrorCode.ERR_ObjectProhibited, "Static").WithArguments("C.Static").WithLocation(2, 18), // (3,27): error CS0176: Member 'C.Static' cannot be accessed with an instance reference; qualify it with a type name instead // _ = new C() is { Instance.Static: null }; // 2 Diagnostic(ErrorCode.ERR_ObjectProhibited, "Static").WithArguments("C.Static").WithLocation(3, 27), // (4,18): error CS0176: Member 'C.Static' cannot be accessed with an instance reference; qualify it with a type name instead // _ = new C() is { Static.Instance: null }; // 3 Diagnostic(ErrorCode.ERR_ObjectProhibited, "Static").WithArguments("C.Static").WithLocation(4, 18) ); } [Fact] public void ExtendedPropertyPatterns_Exhaustiveness() { var program = @" _ = new C() switch // 1 { { Prop.True: true } => 0 }; _ = new C() switch { { Prop.True: true } => 0, { Prop.True: false } => 0 }; #nullable enable _ = new C() switch // 2 { { Prop.Prop: null } => 0 }; class C { public C Prop { get => throw null!; } public bool True { get => throw null!; } } "; var comp = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); comp.VerifyEmitDiagnostics( // (2,13): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '{ Prop: { True: false } }' is not covered. // _ = new C() switch // 1 Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("{ Prop: { True: false } }").WithLocation(2, 13), // (14,13): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '{ Prop: { Prop: not null } }' is not covered. // _ = new C() switch // 2 Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("{ Prop: { Prop: not null } }").WithLocation(14, 13) ); } public class FlowAnalysisTests : FlowTestBase { [Fact] public void RegionInIsPattern01() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void M(object o) { _ = o switch { string { Length: 0 } s => /*<bind>*/s.ToString()/*</bind>*/, _ = throw null }; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("o, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.UnsafeAddressTaken)); } } } }
// Licensed to the .NET Foundation under one or more 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.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class PatternMatchingTests5 : PatternMatchingTestBase { [Fact] public void ExtendedPropertyPatterns_01() { var program = @" using System; class C { public C Prop1 { get; set; } public C Prop2 { get; set; } public C Prop3 { get; set; } static bool Test1(C o) => o is { Prop1.Prop2.Prop3: null }; static bool Test2(S o) => o is { Prop1.Prop2.Prop3: null }; static bool Test3(S? o) => o is { Prop1.Prop2.Prop3: null }; static bool Test4(S0 o) => o is { Prop1.Prop2.Prop3: 420 }; public static void Main() { Console.WriteLine(Test1(new() { Prop1 = new() { Prop2 = new() { Prop3 = null }}})); Console.WriteLine(Test2(new() { Prop1 = new() { Prop2 = new() { Prop3 = null }}})); Console.WriteLine(Test3(new() { Prop1 = new() { Prop2 = new() { Prop3 = null }}})); Console.WriteLine(Test1(new() { Prop1 = new() { Prop2 = null }})); Console.WriteLine(Test2(new() { Prop1 = new() { Prop2 = null }})); Console.WriteLine(Test3(new() { Prop1 = new() { Prop2 = null }})); Console.WriteLine(Test1(new() { Prop1 = null })); Console.WriteLine(Test2(new() { Prop1 = null })); Console.WriteLine(Test3(new() { Prop1 = null })); Console.WriteLine(Test1(default)); Console.WriteLine(Test2(default)); Console.WriteLine(Test3(default)); Console.WriteLine(Test4(new() { Prop1 = new() { Prop2 = new() { Prop3 = 421 }}})); Console.WriteLine(Test4(new() { Prop1 = new() { Prop2 = new() { Prop3 = 420 }}})); } } struct S { public A? Prop1; } struct A { public B? Prop2; } struct B { public int? Prop3; } struct S0 { public A0 Prop1; } struct A0 { public B0 Prop2; } struct B0 { public int Prop3; } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var expectedOutput = @" True True True False False False False False False False False False False True "; var verifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); verifier.VerifyIL("C.Test1", @" { // Code size 35 (0x23) .maxstack 2 .locals init (C V_0, C V_1) IL_0000: ldarg.0 IL_0001: brfalse.s IL_0021 IL_0003: ldarg.0 IL_0004: callvirt ""C C.Prop1.get"" IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: brfalse.s IL_0021 IL_000d: ldloc.0 IL_000e: callvirt ""C C.Prop2.get"" IL_0013: stloc.1 IL_0014: ldloc.1 IL_0015: brfalse.s IL_0021 IL_0017: ldloc.1 IL_0018: callvirt ""C C.Prop3.get"" IL_001d: ldnull IL_001e: ceq IL_0020: ret IL_0021: ldc.i4.0 IL_0022: ret }"); verifier.VerifyIL("C.Test2", @" { // Code size 64 (0x40) .maxstack 2 .locals init (A? V_0, B? V_1, int? V_2) IL_0000: ldarg.0 IL_0001: ldfld ""A? S.Prop1"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: call ""bool A?.HasValue.get"" IL_000e: brfalse.s IL_003e IL_0010: ldloca.s V_0 IL_0012: call ""A A?.GetValueOrDefault()"" IL_0017: ldfld ""B? A.Prop2"" IL_001c: stloc.1 IL_001d: ldloca.s V_1 IL_001f: call ""bool B?.HasValue.get"" IL_0024: brfalse.s IL_003e IL_0026: ldloca.s V_1 IL_0028: call ""B B?.GetValueOrDefault()"" IL_002d: ldfld ""int? B.Prop3"" IL_0032: stloc.2 IL_0033: ldloca.s V_2 IL_0035: call ""bool int?.HasValue.get"" IL_003a: ldc.i4.0 IL_003b: ceq IL_003d: ret IL_003e: ldc.i4.0 IL_003f: ret }"); verifier.VerifyIL("C.Test4", @" { // Code size 24 (0x18) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""A0 S0.Prop1"" IL_0006: ldfld ""B0 A0.Prop2"" IL_000b: ldfld ""int B0.Prop3"" IL_0010: ldc.i4 0x1a4 IL_0015: ceq IL_0017: ret }"); } [Fact] public void ExtendedPropertyPatterns_02() { var program = @" class C { public C Prop1 { get; set; } public C Prop2 { get; set; } public static void Main() { _ = new C() is { Prop1: null } and { Prop1.Prop2: null }; _ = new C() is { Prop1: null, Prop1.Prop2: null }; } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (9,13): error CS8518: An expression of type 'C' can never match the provided pattern. // _ = new C() is { Prop1: null } and { Prop1.Prop2: null }; Diagnostic(ErrorCode.ERR_IsPatternImpossible, "new C() is { Prop1: null } and { Prop1.Prop2: null }").WithArguments("C").WithLocation(9, 13), // (10,13): error CS8518: An expression of type 'C' can never match the provided pattern. // _ = new C() is { Prop1: null, Prop1.Prop2: null }; Diagnostic(ErrorCode.ERR_IsPatternImpossible, "new C() is { Prop1: null, Prop1.Prop2: null }").WithArguments("C").WithLocation(10, 13) ); } [Fact] public void ExtendedPropertyPatterns_03() { var program = @" using System; class C { C _prop1; C _prop2; C Prop1 { get { Console.WriteLine(nameof(Prop1)); return _prop1; } set => _prop1 = value; } C Prop2 { get { Console.WriteLine(nameof(Prop2)); return _prop2; } set => _prop2 = value; } public static void Main() { Test(null); Test(new()); Test(new() { Prop1 = new() }); Test(new() { Prop1 = new() { Prop2 = new() } }); } static void Test(C o) { Console.WriteLine(nameof(Test)); var result = o switch { {Prop1: null} => 1, {Prop1.Prop2: null} => 2, _ => -1, }; Console.WriteLine(result); } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var expectedOutput = @" Test -1 Test Prop1 1 Test Prop1 Prop2 2 Test Prop1 Prop2 -1"; var verifier = CompileAndVerify(compilation, expectedOutput: expectedOutput); verifier.VerifyIL("C.Test", @" { // Code size 50 (0x32) .maxstack 1 .locals init (int V_0, C V_1) IL_0000: ldstr ""Test"" IL_0005: call ""void System.Console.WriteLine(string)"" IL_000a: ldarg.0 IL_000b: brfalse.s IL_0029 IL_000d: ldarg.0 IL_000e: callvirt ""C C.Prop1.get"" IL_0013: stloc.1 IL_0014: ldloc.1 IL_0015: brfalse.s IL_0021 IL_0017: ldloc.1 IL_0018: callvirt ""C C.Prop2.get"" IL_001d: brfalse.s IL_0025 IL_001f: br.s IL_0029 IL_0021: ldc.i4.1 IL_0022: stloc.0 IL_0023: br.s IL_002b IL_0025: ldc.i4.2 IL_0026: stloc.0 IL_0027: br.s IL_002b IL_0029: ldc.i4.m1 IL_002a: stloc.0 IL_002b: ldloc.0 IL_002c: call ""void System.Console.WriteLine(int)"" IL_0031: ret }"); } [Fact] public void ExtendedPropertyPatterns_04() { var program = @" class C { public static void Main() { _ = new C() is { Prop1<int>.Prop2: {} }; _ = new C() is { Prop1->Prop2: {} }; _ = new C() is { Prop1!.Prop2: {} }; _ = new C() is { Prop1?.Prop2: {} }; _ = new C() is { Prop1[0]: {} }; _ = new C() is { 1: {} }; } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (6,26): error CS8918: Identifier or a simple member access expected. // _ = new C() is { Prop1<int>.Prop2: {} }; Diagnostic(ErrorCode.ERR_InvalidNameInSubpattern, "Prop1<int>").WithLocation(6, 26), // (7,26): error CS8918: Identifier or a simple member access expected. // _ = new C() is { Prop1->Prop2: {} }; Diagnostic(ErrorCode.ERR_InvalidNameInSubpattern, "Prop1->Prop2").WithLocation(7, 26), // (8,26): error CS8918: Identifier or a simple member access expected. // _ = new C() is { Prop1!.Prop2: {} }; Diagnostic(ErrorCode.ERR_InvalidNameInSubpattern, "Prop1!").WithLocation(8, 26), // (9,26): error CS8918: Identifier or a simple member access expected. // _ = new C() is { Prop1?.Prop2: {} }; Diagnostic(ErrorCode.ERR_InvalidNameInSubpattern, "Prop1?.Prop2").WithLocation(9, 26), // (10,26): error CS8503: A property subpattern requires a reference to the property or field to be matched, e.g. '{ Name: Prop1[0] }' // _ = new C() is { Prop1[0]: {} }; Diagnostic(ErrorCode.ERR_PropertyPatternNameMissing, "Prop1[0]").WithArguments("Prop1[0]").WithLocation(10, 26), // (10,26): error CS0246: The type or namespace name 'Prop1' could not be found (are you missing a using directive or an assembly reference?) // _ = new C() is { Prop1[0]: {} }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Prop1").WithArguments("Prop1").WithLocation(10, 26), // (10,31): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // _ = new C() is { Prop1[0]: {} }; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[0]").WithLocation(10, 31), // (10,34): error CS1003: Syntax error, ',' expected // _ = new C() is { Prop1[0]: {} }; Diagnostic(ErrorCode.ERR_SyntaxError, ":").WithArguments(",", ":").WithLocation(10, 34), // (10,36): error CS1003: Syntax error, ',' expected // _ = new C() is { Prop1[0]: {} }; Diagnostic(ErrorCode.ERR_SyntaxError, "{").WithArguments(",", "{").WithLocation(10, 36), // (11,26): error CS8918: Identifier or a simple member access expected. // _ = new C() is { 1: {} }; Diagnostic(ErrorCode.ERR_InvalidNameInSubpattern, "1").WithLocation(11, 26)); } [Fact, WorkItem(52956, "https://github.com/dotnet/roslyn/issues/52956")] public void ExtendedPropertyPatterns_05() { var program = @" class C { C Field1, Field2, Field3, Field4; public void M() { _ = this is { Field1.Field2.Field3: {} }; _ = this is { Field4: {} }; } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (4,7): warning CS0649: Field 'C.Field1' is never assigned to, and will always have its default value null // C Field1, Field2, Field3, Field4; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field1").WithArguments("C.Field1", "null").WithLocation(4, 7), // (4,15): warning CS0649: Field 'C.Field2' is never assigned to, and will always have its default value null // C Field1, Field2, Field3, Field4; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field2").WithArguments("C.Field2", "null").WithLocation(4, 15), // (4,23): warning CS0649: Field 'C.Field3' is never assigned to, and will always have its default value null // C Field1, Field2, Field3, Field4; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field3").WithArguments("C.Field3", "null").WithLocation(4, 23), // (4,31): warning CS0649: Field 'C.Field4' is never assigned to, and will always have its default value null // C Field1, Field2, Field3, Field4; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field4").WithArguments("C.Field4", "null").WithLocation(4, 31) ); } [Fact, WorkItem(52956, "https://github.com/dotnet/roslyn/issues/52956")] public void ExtendedPropertyPatterns_05_NestedRecursivePattern() { var program = @" class C { C Field1, Field2, Field3, Field4; public void M() { _ = this is { Field1: { Field2.Field3.Field4: not null } }; } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (4,7): warning CS0649: Field 'C.Field1' is never assigned to, and will always have its default value null // C Field1, Field2, Field3, Field4; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field1").WithArguments("C.Field1", "null").WithLocation(4, 7), // (4,15): warning CS0649: Field 'C.Field2' is never assigned to, and will always have its default value null // C Field1, Field2, Field3, Field4; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field2").WithArguments("C.Field2", "null").WithLocation(4, 15), // (4,23): warning CS0649: Field 'C.Field3' is never assigned to, and will always have its default value null // C Field1, Field2, Field3, Field4; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field3").WithArguments("C.Field3", "null").WithLocation(4, 23), // (4,31): warning CS0649: Field 'C.Field4' is never assigned to, and will always have its default value null // C Field1, Field2, Field3, Field4; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field4").WithArguments("C.Field4", "null").WithLocation(4, 31) ); } [Fact, WorkItem(52956, "https://github.com/dotnet/roslyn/issues/52956")] public void ExtendedPropertyPatterns_05_Properties() { var program = @" class C { C Prop1 { get; set; } C Prop2 { get; set; } C Prop3 { get; set; } C Prop4 { get; set; } public void M() { _ = this is { Prop1.Prop2.Prop3: {} }; _ = this is { Prop4: {} }; } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics(); } [Fact] public void ExtendedPropertyPatterns_IOperation_Properties() { var src = @" class Program { static void M(A a) /*<bind>*/{ _ = a is { Prop1.Prop2.Prop3: null }; }/*</bind>*/ } class A { public B Prop1 => null; } class B { public C Prop2 => null; } class C { public object Prop3 => null; } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var isPattern = tree.GetRoot().DescendantNodes().OfType<IsPatternExpressionSyntax>().Single(); VerifyOperationTree(comp, model.GetOperation(isPattern), @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'a is { Prop ... op3: null }') Value: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: A) (Syntax: 'a') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null) (Syntax: '{ Prop1.Pro ... op3: null }') (InputType: A, NarrowedType: A, DeclaredSymbol: null, MatchedType: A, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Prop1') Member: IPropertyReferenceOperation: B A.Prop1 { get; } (OperationKind.PropertyReference, Type: B) (Syntax: 'Prop1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Prop1') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'Prop1') (InputType: B, NarrowedType: B, DeclaredSymbol: null, MatchedType: B, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Prop1.Prop2') Member: IPropertyReferenceOperation: C B.Prop2 { get; } (OperationKind.PropertyReference, Type: C) (Syntax: 'Prop1.Prop2') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Prop1.Prop2') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'Prop1.Prop2') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Prop1.Prop2.Prop3') Member: IPropertyReferenceOperation: System.Object C.Prop3 { get; } (OperationKind.PropertyReference, Type: System.Object) (Syntax: 'Prop1.Prop2.Prop3') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'Prop1.Prop2.Prop3') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: System.Object, NarrowedType: System.Object) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '_ = a is { ... p3: null };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: '_ = a is { ... op3: null }') Left: IDiscardOperation (Symbol: System.Boolean _) (OperationKind.Discard, Type: System.Boolean) (Syntax: '_') Right: IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'a is { Prop ... op3: null }') Value: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: A) (Syntax: 'a') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null) (Syntax: '{ Prop1.Pro ... op3: null }') (InputType: A, NarrowedType: A, DeclaredSymbol: null, MatchedType: A, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Prop1') Member: IPropertyReferenceOperation: B A.Prop1 { get; } (OperationKind.PropertyReference, Type: B) (Syntax: 'Prop1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Prop1') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'Prop1') (InputType: B, NarrowedType: B, DeclaredSymbol: null, MatchedType: B, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Prop1.Prop2') Member: IPropertyReferenceOperation: C B.Prop2 { get; } (OperationKind.PropertyReference, Type: C) (Syntax: 'Prop1.Prop2') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Prop1.Prop2') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'Prop1.Prop2') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Prop1.Prop2.Prop3') Member: IPropertyReferenceOperation: System.Object C.Prop3 { get; } (OperationKind.PropertyReference, Type: System.Object) (Syntax: 'Prop1.Prop2.Prop3') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'Prop1.Prop2.Prop3') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: System.Object, NarrowedType: System.Object) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, DiagnosticDescription.None, parseOptions: TestOptions.Regular10); } [Fact] public void ExtendedPropertyPatterns_IOperation_FieldsInStructs() { var src = @" class Program { static void M(A a) /*<bind>*/{ _ = a is { Field1.Field2.Field3: null, Field4: null }; }/*</bind>*/ } struct A { public B? Field1; public B? Field4; } struct B { public C? Field2; } struct C { public object Field3; } "; var expectedDiagnostics = new[] { // (9,22): warning CS0649: Field 'A.Field1' is never assigned to, and will always have its default value // struct A { public B? Field1; public B? Field4; } Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field1").WithArguments("A.Field1", "").WithLocation(9, 22), // (9,40): warning CS0649: Field 'A.Field4' is never assigned to, and will always have its default value // struct A { public B? Field1; public B? Field4; } Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field4").WithArguments("A.Field4", "").WithLocation(9, 40), // (10,22): warning CS0649: Field 'B.Field2' is never assigned to, and will always have its default value // struct B { public C? Field2; } Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field2").WithArguments("B.Field2", "").WithLocation(10, 22), // (11,26): warning CS0649: Field 'C.Field3' is never assigned to, and will always have its default value null // struct C { public object Field3; } Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field3").WithArguments("C.Field3", "null").WithLocation(11, 26) }; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); comp.VerifyDiagnostics(expectedDiagnostics); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var isPattern = tree.GetRoot().DescendantNodes().OfType<IsPatternExpressionSyntax>().Single(); VerifyOperationTree(comp, model.GetOperation(isPattern), @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'a is { Fiel ... ld4: null }') Value: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: A) (Syntax: 'a') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null) (Syntax: '{ Field1.Fi ... ld4: null }') (InputType: A, NarrowedType: A, DeclaredSymbol: null, MatchedType: A, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (2): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Field1') Member: IFieldReferenceOperation: B? A.Field1 (OperationKind.FieldReference, Type: B?) (Syntax: 'Field1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Field1') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'Field1') (InputType: B, NarrowedType: B, DeclaredSymbol: null, MatchedType: B, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Field1.Field2') Member: IFieldReferenceOperation: C? B.Field2 (OperationKind.FieldReference, Type: C?) (Syntax: 'Field1.Field2') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Field1.Field2') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'Field1.Field2') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Field1.Field2.Field3') Member: IFieldReferenceOperation: System.Object C.Field3 (OperationKind.FieldReference, Type: System.Object) (Syntax: 'Field1.Field2.Field3') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'Field1.Field2.Field3') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: System.Object, NarrowedType: System.Object) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null) (Syntax: 'Field4: null') Member: IFieldReferenceOperation: B? A.Field4 (OperationKind.FieldReference, Type: B?) (Syntax: 'Field4') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Field4') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: B?, NarrowedType: B?) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: B?, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') "); var expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '_ = a is { ... d4: null };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: '_ = a is { ... ld4: null }') Left: IDiscardOperation (Symbol: System.Boolean _) (OperationKind.Discard, Type: System.Boolean) (Syntax: '_') Right: IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'a is { Fiel ... ld4: null }') Value: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: A) (Syntax: 'a') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null) (Syntax: '{ Field1.Fi ... ld4: null }') (InputType: A, NarrowedType: A, DeclaredSymbol: null, MatchedType: A, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (2): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Field1') Member: IFieldReferenceOperation: B? A.Field1 (OperationKind.FieldReference, Type: B?) (Syntax: 'Field1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Field1') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'Field1') (InputType: B, NarrowedType: B, DeclaredSymbol: null, MatchedType: B, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Field1.Field2') Member: IFieldReferenceOperation: C? B.Field2 (OperationKind.FieldReference, Type: C?) (Syntax: 'Field1.Field2') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: B, IsImplicit) (Syntax: 'Field1.Field2') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'Field1.Field2') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Field1.Field2.Field3') Member: IFieldReferenceOperation: System.Object C.Field3 (OperationKind.FieldReference, Type: System.Object) (Syntax: 'Field1.Field2.Field3') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'Field1.Field2.Field3') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: System.Object, NarrowedType: System.Object) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null) (Syntax: 'Field4: null') Member: IFieldReferenceOperation: B? A.Field4 (OperationKind.FieldReference, Type: B?) (Syntax: 'Field4') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'Field4') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: B?, NarrowedType: B?) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: B?, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NullLiteral) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(src, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.Regular10); } [Fact] public void ExtendedPropertyPatterns_Explainer() { var src = @" class Program { void M(A a) { _ = a switch // 1 { { BProp.BoolProp: true } => 1 }; _ = a switch // 2 { { BProp.IntProp: <= 0 } => 1 }; } } class A { public B BProp => null; } class B { public bool BoolProp => true; public int IntProp => 0; } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); comp.VerifyDiagnostics( // (6,15): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '{ BProp: { BoolProp: false } }' is not covered. // _ = a switch // 1 Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("{ BProp: { BoolProp: false } }").WithLocation(6, 15), // (11,15): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '{ BProp: { IntProp: 1 } }' is not covered. // _ = a switch // 2 Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("{ BProp: { IntProp: 1 } }").WithLocation(11, 15) ); } [Fact, WorkItem(52956, "https://github.com/dotnet/roslyn/issues/52956")] public void ExtendedPropertyPatterns_BadMemberAccess() { var program = @" class C { C Field1, Field2, Field3; public static void Main() { _ = new C() is { Field1?.Field2: {} }; // 1 _ = new C() is { Field1!.Field2: {} }; // 2 _ = new C() is { Missing: null }; // 3 _ = new C() is { Field3.Missing: {} }; // 4 _ = new C() is { Missing1.Missing2: {} }; // 5 } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (4,7): warning CS0169: The field 'C.Field1' is never used // C Field1, Field2, Field3; Diagnostic(ErrorCode.WRN_UnreferencedField, "Field1").WithArguments("C.Field1").WithLocation(4, 7), // (4,15): warning CS0169: The field 'C.Field2' is never used // C Field1, Field2, Field3; Diagnostic(ErrorCode.WRN_UnreferencedField, "Field2").WithArguments("C.Field2").WithLocation(4, 15), // (4,23): warning CS0649: Field 'C.Field3' is never assigned to, and will always have its default value null // C Field1, Field2, Field3; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field3").WithArguments("C.Field3", "null").WithLocation(4, 23), // (7,26): error CS8918: Identifier or a simple member access expected. // _ = new C() is { Field1?.Field2: {} }; // 1 Diagnostic(ErrorCode.ERR_InvalidNameInSubpattern, "Field1?.Field2").WithLocation(7, 26), // (8,26): error CS8918: Identifier or a simple member access expected. // _ = new C() is { Field1!.Field2: {} }; // 2 Diagnostic(ErrorCode.ERR_InvalidNameInSubpattern, "Field1!").WithLocation(8, 26), // (9,26): error CS0117: 'C' does not contain a definition for 'Missing' // _ = new C() is { Missing: null }; // 3 Diagnostic(ErrorCode.ERR_NoSuchMember, "Missing").WithArguments("C", "Missing").WithLocation(9, 26), // (10,33): error CS0117: 'C' does not contain a definition for 'Missing' // _ = new C() is { Field3.Missing: {} }; // 4 Diagnostic(ErrorCode.ERR_NoSuchMember, "Missing").WithArguments("C", "Missing").WithLocation(10, 33), // (11,26): error CS0117: 'C' does not contain a definition for 'Missing1' // _ = new C() is { Missing1.Missing2: {} }; // 5 Diagnostic(ErrorCode.ERR_NoSuchMember, "Missing1").WithArguments("C", "Missing1").WithLocation(11, 26) ); } [Fact] public void ExtendedPropertyPatterns_IOperationOnMissing() { var program = @" class C { public void M() { _ = this is { Missing: null }; } } "; var comp = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); comp.VerifyEmitDiagnostics( // (6,23): error CS0117: 'C' does not contain a definition for 'Missing' // _ = this is { Missing: null }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Missing").WithArguments("C", "Missing").WithLocation(6, 23) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var isPattern = tree.GetRoot().DescendantNodes().OfType<IsPatternExpressionSyntax>().Single(); VerifyOperationTree(comp, model.GetOperation(isPattern), @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'this is { M ... ing: null }') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid) (Syntax: '{ Missing: null }') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid) (Syntax: 'Missing: null') Member: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'Missing') Children(0) Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: ?, NarrowedType: ?) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') "); } [Fact] public void ExtendedPropertyPatterns_IOperationOnNestedMissing() { var program = @" class C { int Property { get; set; } public void M() { _ = this is { Property.Missing: null }; } } "; var comp = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); comp.VerifyEmitDiagnostics( // (7,32): error CS0117: 'int' does not contain a definition for 'Missing' // _ = this is { Property.Missing: null }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Missing").WithArguments("int", "Missing").WithLocation(7, 32) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var isPattern = tree.GetRoot().DescendantNodes().OfType<IsPatternExpressionSyntax>().Single(); VerifyOperationTree(comp, model.GetOperation(isPattern), @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'this is { P ... ing: null }') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid) (Syntax: '{ Property. ... ing: null }') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'Property') Member: IPropertyReferenceOperation: System.Int32 C.Property { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'Property') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'Property') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'Property') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: null, MatchedType: System.Int32, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'Property.Missing') Member: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'Property.Missing') Children(0) Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: ?, NarrowedType: ?) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') "); } [Fact] public void ExtendedPropertyPatterns_IOperationOnTwoMissing() { var program = @" class C { public void M() { _ = this is { Missing1.Missing2: null }; } } "; var comp = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); comp.VerifyEmitDiagnostics( // (6,23): error CS0117: 'C' does not contain a definition for 'Missing1' // _ = this is { Missing1.Missing2: null }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Missing1").WithArguments("C", "Missing1").WithLocation(6, 23) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var isPattern = tree.GetRoot().DescendantNodes().OfType<IsPatternExpressionSyntax>().Single(); VerifyOperationTree(comp, model.GetOperation(isPattern), @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'this is { M ... ng2: null }') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid) (Syntax: '{ Missing1. ... ng2: null }') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'Missing1') Member: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'Missing1') Children(0) Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'Missing1') (InputType: ?, NarrowedType: ?, DeclaredSymbol: null, MatchedType: ?, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'Missing1.Missing2') Member: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'Missing1.Missing2') Children(0) Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: ?, NarrowedType: ?) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') "); } [Fact, WorkItem(53484, "https://github.com/dotnet/roslyn/issues/53484")] public void ExtendedPropertyPatterns_SuppressionOnPattern() { var program = @" #nullable enable public class ContainerType { public class Type { public void M() { const Type c = null!; if (this is c!) {} if (this is (c!)) {} if (this is Type!) {} // 1 if (this is ContainerType!.Type) {} // 2 if (this is ContainerType.Type!) {} // 3 } } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (12,25): error CS8598: The suppression operator is not allowed in this context // if (this is Type!) {} // 1 Diagnostic(ErrorCode.ERR_IllegalSuppression, "Type!").WithLocation(12, 25), // (13,25): error CS8598: The suppression operator is not allowed in this context // if (this is ContainerType!.Type) {} // 2 Diagnostic(ErrorCode.ERR_IllegalSuppression, "ContainerType").WithLocation(13, 25), // (14,25): error CS8598: The suppression operator is not allowed in this context // if (this is ContainerType.Type!) {} // 3 Diagnostic(ErrorCode.ERR_IllegalSuppression, "ContainerType.Type!").WithLocation(14, 25) ); } [Fact, WorkItem(53484, "https://github.com/dotnet/roslyn/issues/53484")] public void ExtendedPropertyPatterns_PointerAccessInPattern() { var program = @" public class Type { public unsafe void M(S* s) { if (0 is s->X) {} } } public struct S { public int X; } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns, options: TestOptions.UnsafeDebugDll); compilation.VerifyEmitDiagnostics( // (6,18): error CS0150: A constant value is expected // if (0 is s->X) {} Diagnostic(ErrorCode.ERR_ConstantExpected, "s->X").WithLocation(6, 18) ); } [Fact] public void ExtendedPropertyPatterns_SymbolInfo_01() { var source = @" using System; class Program { public static void Main() { P p = new P(); Console.WriteLine(p is { X.Y: {}, Y.X: {} }); } } class P { public P X { get; } public P Y; } "; var compilation = CreatePatternCompilation(source); compilation.VerifyEmitDiagnostics( // (14,14): warning CS0649: Field 'P.Y' is never assigned to, and will always have its default value null // public P Y; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Y").WithArguments("P.Y", "null").WithLocation(14, 14) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var subpatterns = tree.GetRoot().DescendantNodes().OfType<SubpatternSyntax>().ToArray(); Assert.Equal(2, subpatterns.Length); AssertEmpty(model.GetSymbolInfo(subpatterns[0])); AssertEmpty(model.GetSymbolInfo(subpatterns[0].ExpressionColon)); var xy = subpatterns[0].ExpressionColon.Expression; var xySymbol = model.GetSymbolInfo(xy); Assert.Equal(CandidateReason.None, xySymbol.CandidateReason); Assert.Equal("P P.Y", xySymbol.Symbol.ToTestDisplayString()); var x = ((MemberAccessExpressionSyntax)subpatterns[0].ExpressionColon.Expression).Expression; var xSymbol = model.GetSymbolInfo(x); Assert.Equal(CandidateReason.None, xSymbol.CandidateReason); Assert.Equal("P P.X { get; }", xSymbol.Symbol.ToTestDisplayString()); var yName = ((MemberAccessExpressionSyntax)subpatterns[0].ExpressionColon.Expression).Name; var yNameSymbol = model.GetSymbolInfo(yName); Assert.Equal(CandidateReason.None, yNameSymbol.CandidateReason); Assert.Equal("P P.Y", yNameSymbol.Symbol.ToTestDisplayString()); AssertEmpty(model.GetSymbolInfo(subpatterns[1])); AssertEmpty(model.GetSymbolInfo(subpatterns[1].ExpressionColon)); var yx = subpatterns[1].ExpressionColon.Expression; var yxSymbol = model.GetSymbolInfo(yx); Assert.NotEqual(default, yxSymbol); Assert.Equal(CandidateReason.None, yxSymbol.CandidateReason); Assert.Equal("P P.X { get; }", yxSymbol.Symbol.ToTestDisplayString()); var y = ((MemberAccessExpressionSyntax)subpatterns[1].ExpressionColon.Expression).Expression; var ySymbol = model.GetSymbolInfo(y); Assert.Equal(CandidateReason.None, ySymbol.CandidateReason); Assert.Equal("P P.Y", ySymbol.Symbol.ToTestDisplayString()); var xName = ((MemberAccessExpressionSyntax)subpatterns[1].ExpressionColon.Expression).Name; var xNameSymbol = model.GetSymbolInfo(xName); Assert.Equal(CandidateReason.None, xNameSymbol.CandidateReason); Assert.Equal("P P.X { get; }", xNameSymbol.Symbol.ToTestDisplayString()); } [Fact] public void ExtendedPropertyPatterns_SymbolInfo_02() { var source = @" using System; class Program { public static void Main() { P p = null; Console.WriteLine(p is { X.Y: {}, Y.X: {}, }); } } interface I1 { P X { get; } P Y { get; } } interface I2 { P X { get; } P Y { get; } } interface P : I1, I2 { // X and Y inherited ambiguously } "; var compilation = CreatePatternCompilation(source); compilation.VerifyEmitDiagnostics( // (8,34): error CS0229: Ambiguity between 'I1.X' and 'I2.X' // Console.WriteLine(p is { X.Y: {}, Y.X: {}, }); Diagnostic(ErrorCode.ERR_AmbigMember, "X").WithArguments("I1.X", "I2.X").WithLocation(8, 34), // (8,43): error CS0229: Ambiguity between 'I1.Y' and 'I2.Y' // Console.WriteLine(p is { X.Y: {}, Y.X: {}, }); Diagnostic(ErrorCode.ERR_AmbigMember, "Y").WithArguments("I1.Y", "I2.Y").WithLocation(8, 43) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var subpatterns = tree.GetRoot().DescendantNodes().OfType<SubpatternSyntax>().ToArray(); Assert.Equal(2, subpatterns.Length); AssertEmpty(model.GetSymbolInfo(subpatterns[0])); AssertEmpty(model.GetSymbolInfo(subpatterns[0].ExpressionColon)); var x = ((MemberAccessExpressionSyntax)subpatterns[0].ExpressionColon.Expression).Expression; var xSymbol = model.GetSymbolInfo(x); Assert.Equal(CandidateReason.Ambiguous, xSymbol.CandidateReason); Assert.Null(xSymbol.Symbol); Assert.Equal(2, xSymbol.CandidateSymbols.Length); Assert.Equal("P I1.X { get; }", xSymbol.CandidateSymbols[0].ToTestDisplayString()); Assert.Equal("P I2.X { get; }", xSymbol.CandidateSymbols[1].ToTestDisplayString()); AssertEmpty(model.GetSymbolInfo(subpatterns[1])); AssertEmpty(model.GetSymbolInfo(subpatterns[1].ExpressionColon)); var y = ((MemberAccessExpressionSyntax)subpatterns[1].ExpressionColon.Expression).Expression; var ySymbol = model.GetSymbolInfo(y); Assert.Equal(CandidateReason.Ambiguous, ySymbol.CandidateReason); Assert.Null(ySymbol.Symbol); Assert.Equal(2, ySymbol.CandidateSymbols.Length); Assert.Equal("P I1.Y { get; }", ySymbol.CandidateSymbols[0].ToTestDisplayString()); Assert.Equal("P I2.Y { get; }", ySymbol.CandidateSymbols[1].ToTestDisplayString()); } [Fact] public void ExtendedPropertyPatterns_SymbolInfo_03() { var source = @" using System; class Program { public static void Main() { P p = null; Console.WriteLine(p is { X.Y: {}, Y.X: {}, }); } } class P { } "; var compilation = CreatePatternCompilation(source); compilation.VerifyEmitDiagnostics( // (8,34): error CS0117: 'P' does not contain a definition for 'X' // Console.WriteLine(p is { X: 3, Y: 4 }); Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("P", "X").WithLocation(8, 34) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var subpatterns = tree.GetRoot().DescendantNodes().OfType<SubpatternSyntax>().ToArray(); Assert.Equal(2, subpatterns.Length); AssertEmpty(model.GetSymbolInfo(subpatterns[0])); AssertEmpty(model.GetSymbolInfo(subpatterns[0].ExpressionColon)); var x = subpatterns[0].ExpressionColon.Expression; var xSymbol = model.GetSymbolInfo(x); Assert.Equal(CandidateReason.None, xSymbol.CandidateReason); Assert.Null(xSymbol.Symbol); Assert.Empty(xSymbol.CandidateSymbols); AssertEmpty(model.GetSymbolInfo(subpatterns[1])); AssertEmpty(model.GetSymbolInfo(subpatterns[1].ExpressionColon)); var y = subpatterns[1].ExpressionColon.Expression; var ySymbol = model.GetSymbolInfo(y); Assert.Equal(CandidateReason.None, ySymbol.CandidateReason); Assert.Null(ySymbol.Symbol); Assert.Empty(ySymbol.CandidateSymbols); } [Fact] public void ExtendedPropertyPatterns_SymbolInfo_04() { var source = @" using System; class Program { public static void Main() { Console.WriteLine(new C() is { X.Y: {} }); Console.WriteLine(new S() is { Y.X: {} }); } } class C { public S? X { get; } } struct S { public C Y; } "; var compilation = CreatePatternCompilation(source); compilation.VerifyEmitDiagnostics( // (17,14): warning CS0649: Field 'S.Y' is never assigned to, and will always have its default value null // public C Y; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Y").WithArguments("S.Y", "null").WithLocation(17, 14) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var subpatterns = tree.GetRoot().DescendantNodes().OfType<SubpatternSyntax>().ToArray(); Assert.Equal(2, subpatterns.Length); AssertEmpty(model.GetSymbolInfo(subpatterns[0])); AssertEmpty(model.GetSymbolInfo(subpatterns[0].ExpressionColon)); var xy = subpatterns[0].ExpressionColon.Expression; var xySymbol = model.GetSymbolInfo(xy); Assert.Equal(CandidateReason.None, xySymbol.CandidateReason); Assert.Equal("C S.Y", xySymbol.Symbol.ToTestDisplayString()); var xyType = model.GetTypeInfo(xy); Assert.Equal("C", xyType.Type.ToTestDisplayString()); Assert.Equal("C", xyType.ConvertedType.ToTestDisplayString()); var x = ((MemberAccessExpressionSyntax)subpatterns[0].ExpressionColon.Expression).Expression; var xSymbol = model.GetSymbolInfo(x); Assert.Equal(CandidateReason.None, xSymbol.CandidateReason); Assert.Equal("S? C.X { get; }", xSymbol.Symbol.ToTestDisplayString()); var xType = model.GetTypeInfo(x); Assert.Equal("S?", xType.Type.ToTestDisplayString()); Assert.Equal("S?", xType.ConvertedType.ToTestDisplayString()); var yName = ((MemberAccessExpressionSyntax)subpatterns[0].ExpressionColon.Expression).Name; var yNameSymbol = model.GetSymbolInfo(yName); Assert.Equal(CandidateReason.None, yNameSymbol.CandidateReason); Assert.Equal("C S.Y", yNameSymbol.Symbol.ToTestDisplayString()); var yNameType = model.GetTypeInfo(yName); Assert.Equal("C", yNameType.Type.ToTestDisplayString()); Assert.Equal("C", yNameType.ConvertedType.ToTestDisplayString()); AssertEmpty(model.GetSymbolInfo(subpatterns[1])); AssertEmpty(model.GetSymbolInfo(subpatterns[1].ExpressionColon)); var yx = subpatterns[1].ExpressionColon.Expression; var yxSymbol = model.GetSymbolInfo(yx); Assert.NotEqual(default, yxSymbol); Assert.Equal(CandidateReason.None, yxSymbol.CandidateReason); Assert.Equal("S? C.X { get; }", yxSymbol.Symbol.ToTestDisplayString()); var yxType = model.GetTypeInfo(yx); Assert.Equal("S?", yxType.Type.ToTestDisplayString()); Assert.Equal("S?", yxType.ConvertedType.ToTestDisplayString()); var y = ((MemberAccessExpressionSyntax)subpatterns[1].ExpressionColon.Expression).Expression; var ySymbol = model.GetSymbolInfo(y); Assert.Equal(CandidateReason.None, ySymbol.CandidateReason); Assert.Equal("C S.Y", ySymbol.Symbol.ToTestDisplayString()); var yType = model.GetTypeInfo(y); Assert.Equal("C", yType.Type.ToTestDisplayString()); Assert.Equal("C", yType.ConvertedType.ToTestDisplayString()); var xName = ((MemberAccessExpressionSyntax)subpatterns[1].ExpressionColon.Expression).Name; var xNameSymbol = model.GetSymbolInfo(xName); Assert.Equal(CandidateReason.None, xNameSymbol.CandidateReason); Assert.Equal("S? C.X { get; }", xNameSymbol.Symbol.ToTestDisplayString()); var xNameType = model.GetTypeInfo(xName); Assert.Equal("S?", xNameType.Type.ToTestDisplayString()); Assert.Equal("S?", xNameType.ConvertedType.ToTestDisplayString()); var verifier = CompileAndVerify(compilation); verifier.VerifyIL("Program.Main", @" { // Code size 92 (0x5c) .maxstack 2 .locals init (C V_0, S? V_1, S V_2) IL_0000: nop IL_0001: newobj ""C..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_002b IL_000a: ldloc.0 IL_000b: callvirt ""S? C.X.get"" IL_0010: stloc.1 IL_0011: ldloca.s V_1 IL_0013: call ""bool S?.HasValue.get"" IL_0018: brfalse.s IL_002b IL_001a: ldloca.s V_1 IL_001c: call ""S S?.GetValueOrDefault()"" IL_0021: ldfld ""C S.Y"" IL_0026: ldnull IL_0027: cgt.un IL_0029: br.s IL_002c IL_002b: ldc.i4.0 IL_002c: call ""void System.Console.WriteLine(bool)"" IL_0031: nop IL_0032: ldloca.s V_2 IL_0034: initobj ""S"" IL_003a: ldloc.2 IL_003b: ldfld ""C S.Y"" IL_0040: stloc.0 IL_0041: ldloc.0 IL_0042: brfalse.s IL_0054 IL_0044: ldloc.0 IL_0045: callvirt ""S? C.X.get"" IL_004a: stloc.1 IL_004b: ldloca.s V_1 IL_004d: call ""bool S?.HasValue.get"" IL_0052: br.s IL_0055 IL_0054: ldc.i4.0 IL_0055: call ""void System.Console.WriteLine(bool)"" IL_005a: nop IL_005b: ret } "); } [Fact] public void ExtendedPropertyPatterns_Nullability_Properties() { var program = @" #nullable enable class C { C? Prop { get; } public void M() { if (this is { Prop.Prop: null }) { this.Prop.ToString(); this.Prop.Prop.ToString(); // 1 } if (this is { Prop.Prop: {} }) { this.Prop.ToString(); this.Prop.Prop.ToString(); } if (this is { Prop: null } && this is { Prop.Prop: null }) { this.Prop.ToString(); this.Prop.Prop.ToString(); // 2 } if (this is { Prop: null } || this is { Prop.Prop: null }) { this.Prop.ToString(); // 3 this.Prop.Prop.ToString(); // 4 } } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // this.Prop.Prop.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "this.Prop.Prop").WithLocation(9, 13), // (20,13): warning CS8602: Dereference of a possibly null reference. // this.Prop.Prop.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "this.Prop.Prop").WithLocation(20, 13), // (25,13): warning CS8602: Dereference of a possibly null reference. // this.Prop.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "this.Prop").WithLocation(25, 13), // (26,13): warning CS8602: Dereference of a possibly null reference. // this.Prop.Prop.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "this.Prop.Prop").WithLocation(26, 13)); } [Fact] public void ExtendedPropertyPatterns_Nullability_AnnotatedFields() { var program = @" #nullable enable class C { public void M(C1 c1) { if (c1 is { Prop1.Prop2: null }) { c1.Prop1.ToString(); c1.Prop1.Prop2.ToString(); // 1 } if (c1 is { Prop1.Prop2: {} }) { c1.Prop1.ToString(); c1.Prop1.Prop2.ToString(); } if (c1 is { Prop1: null } && c1 is { Prop1.Prop2: null }) { c1.Prop1.ToString(); c1.Prop1.Prop2.ToString(); // 2 } if (c1 is { Prop1: null } || c1 is { Prop1.Prop2: null }) { c1.Prop1.ToString(); // 3 c1.Prop1.Prop2.ToString(); // 4 } } } class C1 { public C2? Prop1 = null; } class C2 { public object? Prop2 = null; } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // c1.Prop1.Prop2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.Prop1.Prop2").WithLocation(8, 13), // (19,13): warning CS8602: Dereference of a possibly null reference. // c1.Prop1.Prop2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.Prop1.Prop2").WithLocation(19, 13), // (24,13): warning CS8602: Dereference of a possibly null reference. // c1.Prop1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.Prop1").WithLocation(24, 13), // (25,13): warning CS8602: Dereference of a possibly null reference. // c1.Prop1.Prop2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.Prop1.Prop2").WithLocation(25, 13) ); } [Fact] public void ExtendedPropertyPatterns_Nullability_UnannotatedFields() { var program = @" #nullable enable class C { public void M1(C1 c1) { if (c1 is { Prop1.Prop2: null }) { c1.Prop1.ToString(); c1.Prop1.Prop2.ToString(); // 1 } else { c1.Prop1.ToString(); c1.Prop1.Prop2.ToString(); } } public void M2(C1 c1) { if (c1 is { Prop1.Prop2: {} }) { c1.Prop1.ToString(); c1.Prop1.Prop2.ToString(); } } public void M3(C1 c1) { if (c1 is { Prop1: null } && c1 is { Prop1.Prop2: null }) { c1.Prop1.ToString(); c1.Prop1.Prop2.ToString(); // 2 } else { c1.Prop1.ToString(); // 3 c1.Prop1.Prop2.ToString(); } } public void M4(C1 c1) { if (c1 is { Prop1: null } || c1 is { Prop1.Prop2: null }) { c1.Prop1.ToString(); // 4 c1.Prop1.Prop2.ToString(); // 5 } else { c1.Prop1.ToString(); c1.Prop1.Prop2.ToString(); } } } class C1 { public C2 Prop1 = null!; } class C2 { public object Prop2 = null!; } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // c1.Prop1.Prop2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.Prop1.Prop2").WithLocation(10, 13), // (34,13): warning CS8602: Dereference of a possibly null reference. // c1.Prop1.Prop2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.Prop1.Prop2").WithLocation(34, 13), // (38,13): warning CS8602: Dereference of a possibly null reference. // c1.Prop1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.Prop1").WithLocation(38, 13), // (48,13): warning CS8602: Dereference of a possibly null reference. // c1.Prop1.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.Prop1").WithLocation(48, 13), // (49,13): warning CS8602: Dereference of a possibly null reference. // c1.Prop1.Prop2.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.Prop1.Prop2").WithLocation(49, 13) ); } [Fact] public void ExtendedPropertyPatterns_ExpressionColonInPositionalPattern() { var source = @" class C { C Property { get; set; } void M() { _ = this is (Property.Property: null, Property: null); } public void Deconstruct(out C c1, out C c2) => throw null; } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular9); compilation.VerifyEmitDiagnostics( // (8,22): error CS8773: Feature 'extended property patterns' is not available in C# 9.0. Please use language version 10.0 or greater. // _ = this is (Property.Property: null, Property: null); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "Property.Property").WithArguments("extended property patterns", "10.0").WithLocation(8, 22), // (8,22): error CS1001: Identifier expected // _ = this is (Property.Property: null, Property: null); Diagnostic(ErrorCode.ERR_IdentifierExpected, "Property.Property").WithLocation(8, 22), // (8,47): error CS8517: The name 'Property' does not match the corresponding 'Deconstruct' parameter 'c2'. // _ = this is (Property.Property: null, Property: null); Diagnostic(ErrorCode.ERR_DeconstructParameterNameMismatch, "Property").WithArguments("Property", "c2").WithLocation(8, 47) ); } [Fact] public void ExtendedPropertyPatterns_ExpressionColonInITuplePattern() { var source = @" class C { void M() { System.Runtime.CompilerServices.ITuple t = null; var r = t is (X.Y: 3, Y.Z: 4); } } namespace System.Runtime.CompilerServices { public interface ITuple { int Length { get; } object this[int index] { get; } } } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (7,23): error CS1001: Identifier expected // var r = t is (X.Y: 3, Y.Z: 4); Diagnostic(ErrorCode.ERR_IdentifierExpected, "X.Y").WithLocation(7, 23), // (7,31): error CS1001: Identifier expected // var r = t is (X.Y: 3, Y.Z: 4); Diagnostic(ErrorCode.ERR_IdentifierExpected, "Y.Z").WithLocation(7, 31) ); } [Fact] public void ExtendedPropertyPatterns_ExpressionColonInValueTuplePattern() { var source = @" class C { void M() { _ = (1, 2) is (X.Y: 3, Y.Z: 4); } } namespace System.Runtime.CompilerServices { public interface ITuple { int Length { get; } object this[int index] { get; } } } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (6,24): error CS1001: Identifier expected // _ = (1, 2) is (X.Y: 3, Y.Z: 4); Diagnostic(ErrorCode.ERR_IdentifierExpected, "X.Y").WithLocation(6, 24), // (6,32): error CS1001: Identifier expected // _ = (1, 2) is (X.Y: 3, Y.Z: 4); Diagnostic(ErrorCode.ERR_IdentifierExpected, "Y.Z").WithLocation(6, 32) ); } [Fact] public void ExtendedPropertyPatterns_ObsoleteProperty() { var program = @" using System; class C { public void M1(C1 c1) { _ = c1 is { Prop1.Prop2: null }; } } class C1 { [ObsoleteAttribute(""error Prop1"", true)] public C2 Prop1 { get; set; } } class C2 { [ObsoleteAttribute(""error Prop2"", true)] public object Prop2 { get; set; } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (7,21): error CS0619: 'C1.Prop1' is obsolete: 'error Prop1' // _ = c1 is { Prop1.Prop2: null }; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "Prop1").WithArguments("C1.Prop1", "error Prop1").WithLocation(7, 21), // (7,27): error CS0619: 'C2.Prop2' is obsolete: 'error Prop2' // _ = c1 is { Prop1.Prop2: null }; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "Prop2").WithArguments("C2.Prop2", "error Prop2").WithLocation(7, 27) ); } [Fact] public void ExtendedPropertyPatterns_ObsoleteAccessor() { var program = @" using System; class C { public void M1(C1 c1) { _ = c1 is { Prop1.Prop2: null }; } } class C1 { public C2 Prop1 { [ObsoleteAttribute(""error Prop1"", true)] get; set; } } class C2 { public object Prop2 { get; [ObsoleteAttribute(""error Prop2"", true)] set; } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (7,21): error CS0619: 'C1.Prop1.get' is obsolete: 'error Prop1' // _ = c1 is { Prop1.Prop2: null }; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "Prop1.Prop2").WithArguments("C1.Prop1.get", "error Prop1").WithLocation(7, 21) ); } [Fact] public void ExtendedPropertyPatterns_InaccessibleProperty() { var program = @" using System; class C { public void M1(C1 c1) { _ = c1 is { Prop1.Prop2: null }; } } class C1 { private C2 Prop1 { get; set; } } class C2 { private object Prop2 { get; set; } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (7,21): error CS0122: 'C1.Prop1' is inaccessible due to its protection level // _ = c1 is { Prop1.Prop2: null }; Diagnostic(ErrorCode.ERR_BadAccess, "Prop1").WithArguments("C1.Prop1").WithLocation(7, 21) ); } [Fact] public void ExtendedPropertyPatterns_ExpressionTree() { var program = @" using System; using System.Collections.Generic; using System.Linq.Expressions; class C { public void M1(C1 c1) { Expression<Func<C1, bool>> f = (c1) => c1 is { Prop1.Prop2: null }; } } class C1 { public C2 Prop1 { get; set; } } class C2 { public object Prop2 { get; set; } } "; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); compilation.VerifyEmitDiagnostics( // (9,48): error CS8122: An expression tree may not contain an 'is' pattern-matching operator. // Expression<Func<C1, bool>> f = (c1) => c1 is { Prop1.Prop2: null }; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsIsMatch, "c1 is { Prop1.Prop2: null }").WithLocation(9, 48) ); } [Fact] public void ExtendedPropertyPatterns_EvaluationOrder() { var program = @" if (new C() is { Prop1.True: true, Prop1.Prop2: not null }) { System.Console.WriteLine(""matched1""); } if (new C() is { Prop1.Prop2: not null, Prop1.True: true }) { System.Console.WriteLine(""matched2""); } if (new C() is { Prop1.Prop2: not null, Prop2.True: true }) { System.Console.WriteLine(""matched3""); } if (new C() is { Prop1.Prop2.Prop3.True: true }) { System.Console.WriteLine(""matched3""); } if (new C() is { Prop1: { Prop2.Prop3.True: true } }) { System.Console.WriteLine(""matched4""); } if (new C() is { Prop1.True: false, Prop1.Prop2: not null }) { throw null; } class C { public C Prop1 { get { System.Console.Write(""Prop1 ""); return this; } } public C Prop2 { get { System.Console.Write(""Prop2 ""); return this; } } public C Prop3 { get { System.Console.Write(""Prop3 ""); return this; } } public bool True { get { System.Console.Write(""True ""); return true; } } } "; CompileAndVerify(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns, expectedOutput: @" Prop1 True Prop2 matched1 Prop1 Prop2 True matched2 Prop1 Prop2 Prop2 True matched3 Prop1 Prop2 Prop3 True matched3 Prop1 Prop2 Prop3 True matched4 Prop1 True"); } [Fact] public void ExtendedPropertyPatterns_StaticMembers() { var program = @" _ = new C() is { Static: null }; // 1 _ = new C() is { Instance.Static: null }; // 2 _ = new C() is { Static.Instance: null }; // 3 class C { public C Instance { get; set; } public static C Static { get; set; } } "; var comp = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); comp.VerifyEmitDiagnostics( // (2,18): error CS0176: Member 'C.Static' cannot be accessed with an instance reference; qualify it with a type name instead // _ = new C() is { Static: null }; // 1 Diagnostic(ErrorCode.ERR_ObjectProhibited, "Static").WithArguments("C.Static").WithLocation(2, 18), // (3,27): error CS0176: Member 'C.Static' cannot be accessed with an instance reference; qualify it with a type name instead // _ = new C() is { Instance.Static: null }; // 2 Diagnostic(ErrorCode.ERR_ObjectProhibited, "Static").WithArguments("C.Static").WithLocation(3, 27), // (4,18): error CS0176: Member 'C.Static' cannot be accessed with an instance reference; qualify it with a type name instead // _ = new C() is { Static.Instance: null }; // 3 Diagnostic(ErrorCode.ERR_ObjectProhibited, "Static").WithArguments("C.Static").WithLocation(4, 18) ); } [Fact] public void ExtendedPropertyPatterns_Exhaustiveness() { var program = @" _ = new C() switch // 1 { { Prop.True: true } => 0 }; _ = new C() switch { { Prop.True: true } => 0, { Prop.True: false } => 0 }; #nullable enable _ = new C() switch // 2 { { Prop.Prop: null } => 0 }; class C { public C Prop { get => throw null!; } public bool True { get => throw null!; } } "; var comp = CreateCompilation(program, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); comp.VerifyEmitDiagnostics( // (2,13): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '{ Prop: { True: false } }' is not covered. // _ = new C() switch // 1 Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("{ Prop: { True: false } }").WithLocation(2, 13), // (14,13): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '{ Prop: { Prop: not null } }' is not covered. // _ = new C() switch // 2 Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("{ Prop: { Prop: not null } }").WithLocation(14, 13) ); } [Fact, WorkItem(55184, "https://github.com/dotnet/roslyn/issues/55184")] public void Repro55184() { var source = @" var x = """"; _ = x is { Error: { Length: > 0 } }; _ = x is { Error.Length: > 0 }; _ = x is { Length: { Error: > 0 } }; _ = x is { Length.Error: > 0 }; "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,12): error CS0117: 'string' does not contain a definition for 'Error' // _ = x is { Error: { Length: > 0 } }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Error").WithArguments("string", "Error").WithLocation(4, 12), // (5,12): error CS0117: 'string' does not contain a definition for 'Error' // _ = x is { Error.Length: > 0 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Error").WithArguments("string", "Error").WithLocation(5, 12), // (6,22): error CS0117: 'int' does not contain a definition for 'Error' // _ = x is { Length: { Error: > 0 } }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Error").WithArguments("int", "Error").WithLocation(6, 22), // (7,19): error CS0117: 'int' does not contain a definition for 'Error' // _ = x is { Length.Error: > 0 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Error").WithArguments("int", "Error").WithLocation(7, 19) ); } public class FlowAnalysisTests : FlowTestBase { [Fact] public void RegionInIsPattern01() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void M(object o) { _ = o switch { string { Length: 0 } s => /*<bind>*/s.ToString()/*</bind>*/, _ = throw null }; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("o", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("o, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.UnsafeAddressTaken)); } } } }
1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/Implementation/IntelliSense/AsyncCompletion/CommitManager.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Threading; using Roslyn.Utilities; using AsyncCompletionData = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; using RoslynCompletionItem = Microsoft.CodeAnalysis.Completion.CompletionItem; using VSCompletionItem = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data.CompletionItem; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion { internal sealed class CommitManager : ForegroundThreadAffinitizedObject, IAsyncCompletionCommitManager { private static readonly AsyncCompletionData.CommitResult CommitResultUnhandled = new(isHandled: false, AsyncCompletionData.CommitBehavior.None); private readonly RecentItemsManager _recentItemsManager; private readonly ITextView _textView; public IEnumerable<char> PotentialCommitCharacters { get { if (_textView.Properties.TryGetProperty(CompletionSource.PotentialCommitCharacters, out ImmutableArray<char> potentialCommitCharacters)) { return potentialCommitCharacters; } else { // If we were not initialized with a CompletionService or are called for a wrong textView, we should not make a commit. return ImmutableArray<char>.Empty; } } } internal CommitManager(ITextView textView, RecentItemsManager recentItemsManager, IThreadingContext threadingContext) : base(threadingContext) { _recentItemsManager = recentItemsManager; _textView = textView; } /// <summary> /// The method performs a preliminarily filtering of commit availability. /// In case of a doubt, it should respond with true. /// We will be able to cancel later in /// <see cref="TryCommit(IAsyncCompletionSession, ITextBuffer, VSCompletionItem, char, CancellationToken)"/> /// based on <see cref="VSCompletionItem"/> item, e.g. based on <see cref="CompletionItemRules"/>. /// </summary> public bool ShouldCommitCompletion( IAsyncCompletionSession session, SnapshotPoint location, char typedChar, CancellationToken cancellationToken) { if (!PotentialCommitCharacters.Contains(typedChar)) { return false; } return !(session.Properties.TryGetProperty(CompletionSource.ExcludedCommitCharacters, out ImmutableArray<char> excludedCommitCharacter) && excludedCommitCharacter.Contains(typedChar)); } public AsyncCompletionData.CommitResult TryCommit( IAsyncCompletionSession session, ITextBuffer subjectBuffer, VSCompletionItem item, char typeChar, CancellationToken cancellationToken) { // We can make changes to buffers. We would like to be sure nobody can change them at the same time. AssertIsForeground(); var document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return CommitResultUnhandled; } var completionService = document.GetLanguageService<CompletionService>(); if (completionService == null) { return CommitResultUnhandled; } if (!item.Properties.TryGetProperty(CompletionSource.RoslynItem, out RoslynCompletionItem roslynItem)) { // Roslyn should not be called if the item committing was not provided by Roslyn. return CommitResultUnhandled; } var filterText = session.ApplicableToSpan.GetText(session.ApplicableToSpan.TextBuffer.CurrentSnapshot) + typeChar; if (Helpers.IsFilterCharacter(roslynItem, typeChar, filterText)) { // Returning Cancel means we keep the current session and consider the character for further filtering. return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.CancelCommit); } var serviceRules = completionService.GetRules(); // We can be called before for ShouldCommitCompletion. However, that call does not provide rules applied for the completion item. // Now we check for the commit charcter in the context of Rules that could change the list of commit characters. if (!Helpers.IsStandardCommitCharacter(typeChar) && !IsCommitCharacter(serviceRules, roslynItem, typeChar)) { // Returning None means we complete the current session with a void commit. // The Editor then will try to trigger a new completion session for the character. return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.None); } if (!Helpers.TryGetInitialTriggerLocation(session, out var triggerLocation)) { // Need the trigger snapshot to calculate the span when the commit changes to be applied. // They should always be available from VS. Just to be defensive, if it's not found here, Roslyn should not make a commit. return CommitResultUnhandled; } if (!session.Properties.TryGetProperty(CompletionSource.CompletionListSpan, out TextSpan completionListSpan)) { return CommitResultUnhandled; } var triggerDocument = triggerLocation.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (triggerDocument == null) { return CommitResultUnhandled; } // Telemetry if (session.TextView.Properties.TryGetProperty(CompletionSource.TypeImportCompletionEnabled, out bool isTyperImportCompletionEnabled) && isTyperImportCompletionEnabled) { AsyncCompletionLogger.LogCommitWithTypeImportCompletionEnabled(); } if (session.TextView.Properties.TryGetProperty(CompletionSource.TargetTypeFilterExperimentEnabled, out bool isExperimentEnabled) && isExperimentEnabled) { // Capture the % of committed completion items that would have appeared in the "Target type matches" filter // (regardless of whether that filter button was active at the time of commit). AsyncCompletionLogger.LogCommitWithTargetTypeCompletionExperimentEnabled(); if (item.Filters.Any(f => f.DisplayText == FeaturesResources.Target_type_matches)) { AsyncCompletionLogger.LogCommitItemWithTargetTypeFilter(); } } // Commit with completion service assumes that null is provided is case of invoke. VS provides '\0' in the case. var commitChar = typeChar == '\0' ? null : (char?)typeChar; return Commit( session, triggerDocument, completionService, subjectBuffer, roslynItem, completionListSpan, commitChar, triggerLocation.Snapshot, serviceRules, filterText, cancellationToken); } private AsyncCompletionData.CommitResult Commit( IAsyncCompletionSession session, Document document, CompletionService completionService, ITextBuffer subjectBuffer, RoslynCompletionItem roslynItem, TextSpan completionListSpan, char? commitCharacter, ITextSnapshot triggerSnapshot, CompletionRules rules, string filterText, CancellationToken cancellationToken) { AssertIsForeground(); bool includesCommitCharacter; if (!subjectBuffer.CheckEditAccess()) { // We are on the wrong thread. FatalError.ReportAndCatch(new InvalidOperationException("Subject buffer did not provide Edit Access")); return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.None); } if (subjectBuffer.EditInProgress) { FatalError.ReportAndCatch(new InvalidOperationException("Subject buffer is editing by someone else.")); return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.None); } CompletionChange change; // We met an issue when external code threw an OperationCanceledException and the cancellationToken is not cancelled. // Catching this scenario for further investigations. // See https://github.com/dotnet/roslyn/issues/38455. try { // Cached items have a span computed at the point they were created. This span may no // longer be valid when used again. In that case, override the span with the latest span // for the completion list itself. if (roslynItem.Flags.IsCached()) roslynItem.Span = completionListSpan; change = completionService.GetChangeAsync(document, roslynItem, commitCharacter, cancellationToken).WaitAndGetResult(cancellationToken); } catch (OperationCanceledException e) when (e.CancellationToken != cancellationToken && FatalError.ReportAndCatch(e)) { return CommitResultUnhandled; } cancellationToken.ThrowIfCancellationRequested(); var view = session.TextView; var provider = GetCompletionProvider(completionService, roslynItem); if (provider is ICustomCommitCompletionProvider customCommitProvider) { customCommitProvider.Commit(roslynItem, view, subjectBuffer, triggerSnapshot, commitCharacter); return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.None); } var textChange = change.TextChange; var triggerSnapshotSpan = new SnapshotSpan(triggerSnapshot, textChange.Span.ToSpan()); var mappedSpan = triggerSnapshotSpan.TranslateTo(subjectBuffer.CurrentSnapshot, SpanTrackingMode.EdgeInclusive); using (var edit = subjectBuffer.CreateEdit(EditOptions.DefaultMinimalChange, reiteratedVersionNumber: null, editTag: null)) { edit.Replace(mappedSpan.Span, change.TextChange.NewText); // edit.Apply() may trigger changes made by extensions. // updatedCurrentSnapshot will contain changes made by Roslyn but not by other extensions. var updatedCurrentSnapshot = edit.Apply(); if (change.NewPosition.HasValue) { // Roslyn knows how to positionate the caret in the snapshot we just created. // If there were more edits made by extensions, TryMoveCaretToAndEnsureVisible maps the snapshot point to the most recent one. view.TryMoveCaretToAndEnsureVisible(new SnapshotPoint(updatedCurrentSnapshot, change.NewPosition.Value)); } else { // Or, If we're doing a minimal change, then the edit that we make to the // buffer may not make the total text change that places the caret where we // would expect it to go based on the requested change. In this case, // determine where the item should go and set the care manually. // Note: we only want to move the caret if the caret would have been moved // by the edit. i.e. if the caret was actually in the mapped span that // we're replacing. var caretPositionInBuffer = view.GetCaretPoint(subjectBuffer); if (caretPositionInBuffer.HasValue && mappedSpan.IntersectsWith(caretPositionInBuffer.Value)) { view.TryMoveCaretToAndEnsureVisible(new SnapshotPoint(subjectBuffer.CurrentSnapshot, mappedSpan.Start.Position + textChange.NewText?.Length ?? 0)); } else { view.Caret.EnsureVisible(); } } includesCommitCharacter = change.IncludesCommitCharacter; if (roslynItem.Rules.FormatOnCommit) { // The edit updates the snapshot however other extensions may make changes there. // Therefore, it is required to use subjectBuffer.CurrentSnapshot for further calculations rather than the updated current snapsot defined above. var currentDocument = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); var formattingService = currentDocument?.GetRequiredLanguageService<IFormattingInteractionService>(); if (currentDocument != null && formattingService != null) { var spanToFormat = triggerSnapshotSpan.TranslateTo(subjectBuffer.CurrentSnapshot, SpanTrackingMode.EdgeInclusive); var changes = formattingService.GetFormattingChangesAsync( currentDocument, spanToFormat.Span.ToTextSpan(), documentOptions: null, CancellationToken.None).WaitAndGetResult(CancellationToken.None); currentDocument.Project.Solution.Workspace.ApplyTextChanges(currentDocument.Id, changes, CancellationToken.None); } } } _recentItemsManager.MakeMostRecentItem(roslynItem.FilterText); if (provider is INotifyCommittingItemCompletionProvider notifyProvider) { _ = ThreadingContext.JoinableTaskFactory.RunAsync(async () => { // Make sure the notification isn't sent on UI thread. await TaskScheduler.Default; _ = notifyProvider.NotifyCommittingItemAsync(document, roslynItem, commitCharacter, cancellationToken).ReportNonFatalErrorAsync(); }); } if (includesCommitCharacter) { return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.SuppressFurtherTypeCharCommandHandlers); } if (commitCharacter == '\n' && SendEnterThroughToEditor(rules, roslynItem, filterText)) { return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.RaiseFurtherReturnKeyAndTabKeyCommandHandlers); } return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.None); } internal static bool IsCommitCharacter(CompletionRules completionRules, CompletionItem item, char ch) { // First see if the item has any specifc commit rules it wants followed. foreach (var rule in item.Rules.CommitCharacterRules) { switch (rule.Kind) { case CharacterSetModificationKind.Add: if (rule.Characters.Contains(ch)) { return true; } continue; case CharacterSetModificationKind.Remove: if (rule.Characters.Contains(ch)) { return false; } continue; case CharacterSetModificationKind.Replace: return rule.Characters.Contains(ch); } } // Fall back to the default rules for this language's completion service. return completionRules.DefaultCommitCharacters.IndexOf(ch) >= 0; } internal static bool SendEnterThroughToEditor(CompletionRules rules, RoslynCompletionItem item, string textTypedSoFar) { var rule = item.Rules.EnterKeyRule; if (rule == EnterKeyRule.Default) { rule = rules.DefaultEnterKeyRule; } switch (rule) { default: case EnterKeyRule.Default: case EnterKeyRule.Never: return false; case EnterKeyRule.Always: return true; case EnterKeyRule.AfterFullyTypedWord: // textTypedSoFar is concatenated from individual chars typed. // '\n' is the enter char. // That is why, there is no need to check for '\r\n'. if (textTypedSoFar.LastOrDefault() == '\n') { textTypedSoFar = textTypedSoFar.Substring(0, textTypedSoFar.Length - 1); } return item.GetEntireDisplayText() == textTypedSoFar; } } private static CompletionProvider? GetCompletionProvider(CompletionService completionService, CompletionItem item) { if (completionService is CompletionServiceWithProviders completionServiceWithProviders) { return completionServiceWithProviders.GetProvider(item); } return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Threading; using Roslyn.Utilities; using AsyncCompletionData = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; using RoslynCompletionItem = Microsoft.CodeAnalysis.Completion.CompletionItem; using VSCompletionItem = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data.CompletionItem; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion { internal sealed class CommitManager : ForegroundThreadAffinitizedObject, IAsyncCompletionCommitManager { private static readonly AsyncCompletionData.CommitResult CommitResultUnhandled = new(isHandled: false, AsyncCompletionData.CommitBehavior.None); private readonly RecentItemsManager _recentItemsManager; private readonly ITextView _textView; public IEnumerable<char> PotentialCommitCharacters { get { if (_textView.Properties.TryGetProperty(CompletionSource.PotentialCommitCharacters, out ImmutableArray<char> potentialCommitCharacters)) { return potentialCommitCharacters; } else { // If we were not initialized with a CompletionService or are called for a wrong textView, we should not make a commit. return ImmutableArray<char>.Empty; } } } internal CommitManager(ITextView textView, RecentItemsManager recentItemsManager, IThreadingContext threadingContext) : base(threadingContext) { _recentItemsManager = recentItemsManager; _textView = textView; } /// <summary> /// The method performs a preliminarily filtering of commit availability. /// In case of a doubt, it should respond with true. /// We will be able to cancel later in /// <see cref="TryCommit(IAsyncCompletionSession, ITextBuffer, VSCompletionItem, char, CancellationToken)"/> /// based on <see cref="VSCompletionItem"/> item, e.g. based on <see cref="CompletionItemRules"/>. /// </summary> public bool ShouldCommitCompletion( IAsyncCompletionSession session, SnapshotPoint location, char typedChar, CancellationToken cancellationToken) { if (!PotentialCommitCharacters.Contains(typedChar)) { return false; } return !(session.Properties.TryGetProperty(CompletionSource.ExcludedCommitCharacters, out ImmutableArray<char> excludedCommitCharacter) && excludedCommitCharacter.Contains(typedChar)); } public AsyncCompletionData.CommitResult TryCommit( IAsyncCompletionSession session, ITextBuffer subjectBuffer, VSCompletionItem item, char typeChar, CancellationToken cancellationToken) { // We can make changes to buffers. We would like to be sure nobody can change them at the same time. AssertIsForeground(); var document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return CommitResultUnhandled; } var completionService = document.GetLanguageService<CompletionService>(); if (completionService == null) { return CommitResultUnhandled; } if (!item.Properties.TryGetProperty(CompletionSource.RoslynItem, out RoslynCompletionItem roslynItem)) { // Roslyn should not be called if the item committing was not provided by Roslyn. return CommitResultUnhandled; } var filterText = session.ApplicableToSpan.GetText(session.ApplicableToSpan.TextBuffer.CurrentSnapshot) + typeChar; if (Helpers.IsFilterCharacter(roslynItem, typeChar, filterText)) { // Returning Cancel means we keep the current session and consider the character for further filtering. return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.CancelCommit); } var serviceRules = completionService.GetRules(); // We can be called before for ShouldCommitCompletion. However, that call does not provide rules applied for the completion item. // Now we check for the commit charcter in the context of Rules that could change the list of commit characters. if (!Helpers.IsStandardCommitCharacter(typeChar) && !IsCommitCharacter(serviceRules, roslynItem, typeChar)) { // Returning None means we complete the current session with a void commit. // The Editor then will try to trigger a new completion session for the character. return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.None); } if (!item.Properties.TryGetProperty(CompletionSource.TriggerLocation, out SnapshotPoint triggerLocation)) { // Need the trigger snapshot to calculate the span when the commit changes to be applied. // They should always be available from items provided by Roslyn CompletionSource. // Just to be defensive, if it's not found here, Roslyn should not make a commit. return CommitResultUnhandled; } if (!session.Properties.TryGetProperty(CompletionSource.CompletionListSpan, out TextSpan completionListSpan)) { return CommitResultUnhandled; } var triggerDocument = triggerLocation.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (triggerDocument == null) { return CommitResultUnhandled; } // Telemetry if (session.TextView.Properties.TryGetProperty(CompletionSource.TypeImportCompletionEnabled, out bool isTyperImportCompletionEnabled) && isTyperImportCompletionEnabled) { AsyncCompletionLogger.LogCommitWithTypeImportCompletionEnabled(); } if (session.TextView.Properties.TryGetProperty(CompletionSource.TargetTypeFilterExperimentEnabled, out bool isExperimentEnabled) && isExperimentEnabled) { // Capture the % of committed completion items that would have appeared in the "Target type matches" filter // (regardless of whether that filter button was active at the time of commit). AsyncCompletionLogger.LogCommitWithTargetTypeCompletionExperimentEnabled(); if (item.Filters.Any(f => f.DisplayText == FeaturesResources.Target_type_matches)) { AsyncCompletionLogger.LogCommitItemWithTargetTypeFilter(); } } // Commit with completion service assumes that null is provided is case of invoke. VS provides '\0' in the case. var commitChar = typeChar == '\0' ? null : (char?)typeChar; return Commit( session, triggerDocument, completionService, subjectBuffer, roslynItem, completionListSpan, commitChar, triggerLocation.Snapshot, serviceRules, filterText, cancellationToken); } private AsyncCompletionData.CommitResult Commit( IAsyncCompletionSession session, Document document, CompletionService completionService, ITextBuffer subjectBuffer, RoslynCompletionItem roslynItem, TextSpan completionListSpan, char? commitCharacter, ITextSnapshot triggerSnapshot, CompletionRules rules, string filterText, CancellationToken cancellationToken) { AssertIsForeground(); bool includesCommitCharacter; if (!subjectBuffer.CheckEditAccess()) { // We are on the wrong thread. FatalError.ReportAndCatch(new InvalidOperationException("Subject buffer did not provide Edit Access")); return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.None); } if (subjectBuffer.EditInProgress) { FatalError.ReportAndCatch(new InvalidOperationException("Subject buffer is editing by someone else.")); return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.None); } CompletionChange change; // We met an issue when external code threw an OperationCanceledException and the cancellationToken is not cancelled. // Catching this scenario for further investigations. // See https://github.com/dotnet/roslyn/issues/38455. try { // Cached items have a span computed at the point they were created. This span may no // longer be valid when used again. In that case, override the span with the latest span // for the completion list itself. if (roslynItem.Flags.IsCached()) roslynItem.Span = completionListSpan; change = completionService.GetChangeAsync(document, roslynItem, commitCharacter, cancellationToken).WaitAndGetResult(cancellationToken); } catch (OperationCanceledException e) when (e.CancellationToken != cancellationToken && FatalError.ReportAndCatch(e)) { return CommitResultUnhandled; } cancellationToken.ThrowIfCancellationRequested(); var view = session.TextView; var provider = GetCompletionProvider(completionService, roslynItem); if (provider is ICustomCommitCompletionProvider customCommitProvider) { customCommitProvider.Commit(roslynItem, view, subjectBuffer, triggerSnapshot, commitCharacter); return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.None); } var textChange = change.TextChange; var triggerSnapshotSpan = new SnapshotSpan(triggerSnapshot, textChange.Span.ToSpan()); var mappedSpan = triggerSnapshotSpan.TranslateTo(subjectBuffer.CurrentSnapshot, SpanTrackingMode.EdgeInclusive); using (var edit = subjectBuffer.CreateEdit(EditOptions.DefaultMinimalChange, reiteratedVersionNumber: null, editTag: null)) { edit.Replace(mappedSpan.Span, change.TextChange.NewText); // edit.Apply() may trigger changes made by extensions. // updatedCurrentSnapshot will contain changes made by Roslyn but not by other extensions. var updatedCurrentSnapshot = edit.Apply(); if (change.NewPosition.HasValue) { // Roslyn knows how to positionate the caret in the snapshot we just created. // If there were more edits made by extensions, TryMoveCaretToAndEnsureVisible maps the snapshot point to the most recent one. view.TryMoveCaretToAndEnsureVisible(new SnapshotPoint(updatedCurrentSnapshot, change.NewPosition.Value)); } else { // Or, If we're doing a minimal change, then the edit that we make to the // buffer may not make the total text change that places the caret where we // would expect it to go based on the requested change. In this case, // determine where the item should go and set the care manually. // Note: we only want to move the caret if the caret would have been moved // by the edit. i.e. if the caret was actually in the mapped span that // we're replacing. var caretPositionInBuffer = view.GetCaretPoint(subjectBuffer); if (caretPositionInBuffer.HasValue && mappedSpan.IntersectsWith(caretPositionInBuffer.Value)) { view.TryMoveCaretToAndEnsureVisible(new SnapshotPoint(subjectBuffer.CurrentSnapshot, mappedSpan.Start.Position + textChange.NewText?.Length ?? 0)); } else { view.Caret.EnsureVisible(); } } includesCommitCharacter = change.IncludesCommitCharacter; if (roslynItem.Rules.FormatOnCommit) { // The edit updates the snapshot however other extensions may make changes there. // Therefore, it is required to use subjectBuffer.CurrentSnapshot for further calculations rather than the updated current snapsot defined above. var currentDocument = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); var formattingService = currentDocument?.GetRequiredLanguageService<IFormattingInteractionService>(); if (currentDocument != null && formattingService != null) { var spanToFormat = triggerSnapshotSpan.TranslateTo(subjectBuffer.CurrentSnapshot, SpanTrackingMode.EdgeInclusive); var changes = formattingService.GetFormattingChangesAsync( currentDocument, spanToFormat.Span.ToTextSpan(), documentOptions: null, CancellationToken.None).WaitAndGetResult(CancellationToken.None); currentDocument.Project.Solution.Workspace.ApplyTextChanges(currentDocument.Id, changes, CancellationToken.None); } } } _recentItemsManager.MakeMostRecentItem(roslynItem.FilterText); if (provider is INotifyCommittingItemCompletionProvider notifyProvider) { _ = ThreadingContext.JoinableTaskFactory.RunAsync(async () => { // Make sure the notification isn't sent on UI thread. await TaskScheduler.Default; _ = notifyProvider.NotifyCommittingItemAsync(document, roslynItem, commitCharacter, cancellationToken).ReportNonFatalErrorAsync(); }); } if (includesCommitCharacter) { return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.SuppressFurtherTypeCharCommandHandlers); } if (commitCharacter == '\n' && SendEnterThroughToEditor(rules, roslynItem, filterText)) { return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.RaiseFurtherReturnKeyAndTabKeyCommandHandlers); } return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.None); } internal static bool IsCommitCharacter(CompletionRules completionRules, CompletionItem item, char ch) { // First see if the item has any specifc commit rules it wants followed. foreach (var rule in item.Rules.CommitCharacterRules) { switch (rule.Kind) { case CharacterSetModificationKind.Add: if (rule.Characters.Contains(ch)) { return true; } continue; case CharacterSetModificationKind.Remove: if (rule.Characters.Contains(ch)) { return false; } continue; case CharacterSetModificationKind.Replace: return rule.Characters.Contains(ch); } } // Fall back to the default rules for this language's completion service. return completionRules.DefaultCommitCharacters.IndexOf(ch) >= 0; } internal static bool SendEnterThroughToEditor(CompletionRules rules, RoslynCompletionItem item, string textTypedSoFar) { var rule = item.Rules.EnterKeyRule; if (rule == EnterKeyRule.Default) { rule = rules.DefaultEnterKeyRule; } switch (rule) { default: case EnterKeyRule.Default: case EnterKeyRule.Never: return false; case EnterKeyRule.Always: return true; case EnterKeyRule.AfterFullyTypedWord: // textTypedSoFar is concatenated from individual chars typed. // '\n' is the enter char. // That is why, there is no need to check for '\r\n'. if (textTypedSoFar.LastOrDefault() == '\n') { textTypedSoFar = textTypedSoFar.Substring(0, textTypedSoFar.Length - 1); } return item.GetEntireDisplayText() == textTypedSoFar; } } private static CompletionProvider? GetCompletionProvider(CompletionService completionService, CompletionItem item) { if (completionService is CompletionServiceWithProviders completionServiceWithProviders) { return completionServiceWithProviders.GetProvider(item); } return null; } } }
1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/Implementation/IntelliSense/AsyncCompletion/CompletionSource.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.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Core.Imaging; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Adornments; using Microsoft.VisualStudio.Text.Editor; using AsyncCompletionData = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; using RoslynCompletionItem = Microsoft.CodeAnalysis.Completion.CompletionItem; using VSCompletionItem = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data.CompletionItem; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion { internal sealed class CompletionSource : ForegroundThreadAffinitizedObject, IAsyncExpandingCompletionSource { internal const string RoslynItem = nameof(RoslynItem); internal const string TriggerLocation = nameof(TriggerLocation); internal const string CompletionListSpan = nameof(CompletionListSpan); internal const string InsertionText = nameof(InsertionText); internal const string HasSuggestionItemOptions = nameof(HasSuggestionItemOptions); internal const string Description = nameof(Description); internal const string PotentialCommitCharacters = nameof(PotentialCommitCharacters); internal const string ExcludedCommitCharacters = nameof(ExcludedCommitCharacters); internal const string NonBlockingCompletion = nameof(NonBlockingCompletion); internal const string TypeImportCompletionEnabled = nameof(TypeImportCompletionEnabled); internal const string TargetTypeFilterExperimentEnabled = nameof(TargetTypeFilterExperimentEnabled); private static readonly ImmutableArray<ImageElement> s_WarningImageAttributeImagesArray = ImmutableArray.Create(new ImageElement(Glyph.CompletionWarning.GetImageId(), EditorFeaturesResources.Warning_image_element)); private static readonly EditorOptionKey<bool> NonBlockingCompletionEditorOption = new(NonBlockingCompletion); // Use CWT to cache data needed to create VSCompletionItem, so the table would be cleared when Roslyn completion item cache is cleared. private static readonly ConditionalWeakTable<RoslynCompletionItem, StrongBox<VSCompletionItemData>> s_roslynItemToVsItemData = new(); private readonly ITextView _textView; private readonly bool _isDebuggerTextView; private readonly ImmutableHashSet<string> _roles; private readonly Lazy<IStreamingFindUsagesPresenter> _streamingPresenter; private bool _snippetCompletionTriggeredIndirectly; internal CompletionSource( ITextView textView, Lazy<IStreamingFindUsagesPresenter> streamingPresenter, IThreadingContext threadingContext) : base(threadingContext) { _textView = textView; _streamingPresenter = streamingPresenter; _isDebuggerTextView = textView is IDebuggerTextView; _roles = textView.Roles.ToImmutableHashSet(); } public AsyncCompletionData.CompletionStartData InitializeCompletion( AsyncCompletionData.CompletionTrigger trigger, SnapshotPoint triggerLocation, CancellationToken cancellationToken) { // We take sourceText from document to get a snapshot span. // We would like to be sure that nobody changes buffers at the same time. AssertIsForeground(); if (_textView.Selection.Mode == TextSelectionMode.Box) { // No completion with multiple selection return AsyncCompletionData.CompletionStartData.DoesNotParticipateInCompletion; } var document = triggerLocation.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return AsyncCompletionData.CompletionStartData.DoesNotParticipateInCompletion; } var service = document.GetLanguageService<CompletionService>(); if (service == null) { return AsyncCompletionData.CompletionStartData.DoesNotParticipateInCompletion; } // The Editor supports the option per textView. // There could be mixed desired behavior per textView and even per same completion session. // The right fix would be to send this information as a result of the method. // Then, the Editor would choose the right behavior for mixed cases. _textView.Options.GlobalOptions.SetOptionValue(NonBlockingCompletionEditorOption, !document.Project.Solution.Workspace.Options.GetOption(CompletionOptions.BlockForCompletionItems2, service.Language)); // In case of calls with multiple completion services for the same view (e.g. TypeScript and C#), those completion services must not be called simultaneously for the same session. // Therefore, in each completion session we use a list of commit character for a specific completion service and a specific content type. _textView.Properties[PotentialCommitCharacters] = service.GetRules().DefaultCommitCharacters; // Reset a flag which means a snippet triggered by ? + Tab. // Set it later if met the condition. _snippetCompletionTriggeredIndirectly = false; CheckForExperimentStatus(_textView, document); var sourceText = document.GetTextSynchronously(cancellationToken); return ShouldTriggerCompletion(trigger, triggerLocation, sourceText, document, service) ? new AsyncCompletionData.CompletionStartData( participation: AsyncCompletionData.CompletionParticipation.ProvidesItems, applicableToSpan: new SnapshotSpan( triggerLocation.Snapshot, service.GetDefaultCompletionListSpan(sourceText, triggerLocation.Position).ToSpan())) : AsyncCompletionData.CompletionStartData.DoesNotParticipateInCompletion; // For telemetry reporting purpose static void CheckForExperimentStatus(ITextView textView, Document document) { var workspace = document.Project.Solution.Workspace; var experimentationService = workspace.Services.GetRequiredService<IExperimentationService>(); textView.Properties[TargetTypeFilterExperimentEnabled] = experimentationService.IsExperimentEnabled(WellKnownExperimentNames.TargetTypedCompletionFilter); var importCompletionOptionValue = workspace.Options.GetOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, document.Project.Language); var importCompletionExperimentValue = experimentationService.IsExperimentEnabled(WellKnownExperimentNames.TypeImportCompletion); var isTypeImportEnababled = importCompletionOptionValue == true || (importCompletionOptionValue == null && importCompletionExperimentValue); textView.Properties[TypeImportCompletionEnabled] = isTypeImportEnababled; } } private bool ShouldTriggerCompletion( AsyncCompletionData.CompletionTrigger trigger, SnapshotPoint triggerLocation, SourceText sourceText, Document document, CompletionService completionService) { // The trigger reason guarantees that user wants a completion. if (trigger.Reason == AsyncCompletionData.CompletionTriggerReason.Invoke || trigger.Reason == AsyncCompletionData.CompletionTriggerReason.InvokeAndCommitIfUnique) { return true; } // Enter does not trigger completion. if (trigger.Reason == AsyncCompletionData.CompletionTriggerReason.Insertion && trigger.Character == '\n') { return false; } //The user may be trying to invoke snippets through question-tab. // We may provide a completion after that. // Otherwise, tab should not be a completion trigger. if (trigger.Reason == AsyncCompletionData.CompletionTriggerReason.Insertion && trigger.Character == '\t') { return TryInvokeSnippetCompletion(completionService, document, sourceText, triggerLocation.Position); } var roslynTrigger = Helpers.GetRoslynTrigger(trigger, triggerLocation); // The completion service decides that user may want a completion. if (completionService.ShouldTriggerCompletion(document.Project, sourceText, triggerLocation.Position, roslynTrigger)) { return true; } return false; } private bool TryInvokeSnippetCompletion( CompletionService completionService, Document document, SourceText text, int caretPoint) { var rules = completionService.GetRules(); // Do not invoke snippet if the corresponding rule is not set in options. if (rules.SnippetsRule != SnippetsRule.IncludeAfterTypingIdentifierQuestionTab) { return false; } var syntaxFactsOpt = document.GetLanguageService<ISyntaxFactsService>(); // Snippets are included if the user types: <quesiton><tab> // If at least one condition for snippets do not hold, bail out. if (syntaxFactsOpt == null || caretPoint < 3 || text[caretPoint - 2] != '?' || !QuestionMarkIsPrecededByIdentifierAndWhitespace(text, caretPoint - 2, syntaxFactsOpt)) { return false; } // Because <question><tab> is actually a command to bring up snippets, // we delete the last <question> that was typed. var textChange = new TextChange(TextSpan.FromBounds(caretPoint - 2, caretPoint), string.Empty); document.Project.Solution.Workspace.ApplyTextChanges(document.Id, textChange, CancellationToken.None); _snippetCompletionTriggeredIndirectly = true; return true; } public Task<AsyncCompletionData.CompletionContext> GetCompletionContextAsync( IAsyncCompletionSession session, AsyncCompletionData.CompletionTrigger trigger, SnapshotPoint triggerLocation, SnapshotSpan applicableToSpan, CancellationToken cancellationToken) { if (session is null) throw new ArgumentNullException(nameof(session)); session.Properties[TriggerLocation] = triggerLocation; return GetCompletionContextWorkerAsync(session, trigger, triggerLocation, isExpanded: false, cancellationToken); } public async Task<AsyncCompletionData.CompletionContext> GetExpandedCompletionContextAsync( IAsyncCompletionSession session, AsyncCompletionData.CompletionExpander expander, AsyncCompletionData.CompletionTrigger intialTrigger, SnapshotSpan applicableToSpan, CancellationToken cancellationToken) { // We only want to provide expanded items for Roslyn's expander. if ((object)expander == FilterSet.Expander) { if (Helpers.TryGetInitialTriggerLocation(session, out var initialTriggerLocation)) { return await GetCompletionContextWorkerAsync(session, intialTrigger, initialTriggerLocation, isExpanded: true, cancellationToken).ConfigureAwait(false); } } return AsyncCompletionData.CompletionContext.Empty; } private async Task<AsyncCompletionData.CompletionContext> GetCompletionContextWorkerAsync( IAsyncCompletionSession session, AsyncCompletionData.CompletionTrigger trigger, SnapshotPoint triggerLocation, bool isExpanded, CancellationToken cancellationToken) { var document = triggerLocation.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return AsyncCompletionData.CompletionContext.Empty; } var completionService = document.GetRequiredLanguageService<CompletionService>(); var roslynTrigger = Helpers.GetRoslynTrigger(trigger, triggerLocation); if (_snippetCompletionTriggeredIndirectly) { roslynTrigger = new CompletionTrigger(CompletionTriggerKind.Snippets); } var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var options = documentOptions .WithChangedOption(CompletionServiceOptions.IsExpandedCompletion, isExpanded); if (_isDebuggerTextView) { options = options .WithChangedOption(CompletionControllerOptions.FilterOutOfScopeLocals, false) .WithChangedOption(CompletionControllerOptions.ShowXmlDocCommentCompletion, false); } var (completionList, expandItemsAvailable) = await completionService.GetCompletionsInternalAsync( document, triggerLocation, roslynTrigger, _roles, options, cancellationToken).ConfigureAwait(false); ImmutableArray<VSCompletionItem> items; AsyncCompletionData.SuggestionItemOptions? suggestionItemOptions; var filterSet = new FilterSet(); if (completionList == null) { items = ImmutableArray<VSCompletionItem>.Empty; suggestionItemOptions = null; } else { var itemsBuilder = new ArrayBuilder<VSCompletionItem>(completionList.Items.Length); foreach (var roslynItem in completionList.Items) { cancellationToken.ThrowIfCancellationRequested(); var item = Convert(document, roslynItem, filterSet); itemsBuilder.Add(item); } items = itemsBuilder.ToImmutableAndFree(); suggestionItemOptions = completionList.SuggestionModeItem != null ? new AsyncCompletionData.SuggestionItemOptions( completionList.SuggestionModeItem.DisplayText, completionList.SuggestionModeItem.Properties.TryGetValue(Description, out var description) ? description : string.Empty) : null; // Store around the span this completion list applies to. We'll use this later // to pass this value in when we're committing a completion list item. // It's OK to overwrite this value when expanded items are requested. session.Properties[CompletionListSpan] = completionList.Span; // This is a code supporting original completion scenarios: // Controller.Session_ComputeModel: if completionList.SuggestionModeItem != null, then suggestionMode = true // If there are suggestionItemOptions, then later HandleNormalFiltering should set selection to SoftSelection. if (!session.Properties.TryGetProperty(HasSuggestionItemOptions, out bool hasSuggestionItemOptionsBefore) || !hasSuggestionItemOptionsBefore) { session.Properties[HasSuggestionItemOptions] = suggestionItemOptions != null; } var excludedCommitCharacters = GetExcludedCommitCharacters(completionList.Items); if (excludedCommitCharacters.Length > 0) { if (session.Properties.TryGetProperty(ExcludedCommitCharacters, out ImmutableArray<char> excludedCommitCharactersBefore)) { excludedCommitCharacters = excludedCommitCharacters.Union(excludedCommitCharactersBefore).ToImmutableArray(); } session.Properties[ExcludedCommitCharacters] = excludedCommitCharacters; } } // It's possible that some providers can provide expanded items, in which case we will need to show expander as unselected. return new AsyncCompletionData.CompletionContext( items, suggestionItemOptions, suggestionItemOptions == null ? AsyncCompletionData.InitialSelectionHint.RegularSelection : AsyncCompletionData.InitialSelectionHint.SoftSelection, filterSet.GetFilterStatesInSet(addUnselectedExpander: expandItemsAvailable)); } public async Task<object?> GetDescriptionAsync(IAsyncCompletionSession session, VSCompletionItem item, CancellationToken cancellationToken) { if (session is null) throw new ArgumentNullException(nameof(session)); if (item is null) throw new ArgumentNullException(nameof(item)); if (!item.Properties.TryGetProperty(RoslynItem, out RoslynCompletionItem roslynItem) || !Helpers.TryGetInitialTriggerLocation(session, out var triggerLocation)) { return null; } var document = triggerLocation.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return null; } var service = document.GetLanguageService<CompletionService>(); if (service == null) { return null; } var description = await service.GetDescriptionAsync(document, roslynItem, cancellationToken).ConfigureAwait(false); var context = new IntellisenseQuickInfoBuilderContext(document, ThreadingContext, _streamingPresenter); var elements = IntelliSense.Helpers.BuildInteractiveTextElements(description.TaggedParts, context).ToArray(); if (elements.Length == 0) { return new ClassifiedTextElement(); } else if (elements.Length == 1) { return elements[0]; } else { return new ContainerElement(ContainerElementStyle.Stacked | ContainerElementStyle.VerticalPadding, elements); } } /// <summary> /// We'd like to cache VS Completion item directly to avoid allocation completely. However it holds references /// to transient objects, which would cause memory leak (among other potential issues) if cached. /// So as a compromise, we cache data that can be calculated from Roslyn completion item to avoid repeated /// calculation cost for cached Roslyn completion items. /// </summary> private readonly struct VSCompletionItemData { public VSCompletionItemData( string displayText, ImageElement icon, ImmutableArray<AsyncCompletionData.CompletionFilter> filters, int filterSetData, ImmutableArray<ImageElement> attributeIcons, string insertionText) { DisplayText = displayText; Icon = icon; Filters = filters; FilterSetData = filterSetData; AttributeIcons = attributeIcons; InsertionText = insertionText; } public string DisplayText { get; } public ImageElement Icon { get; } public ImmutableArray<AsyncCompletionData.CompletionFilter> Filters { get; } /// <summary> /// This is the bit vector value from the FilterSet of this item. /// </summary> public int FilterSetData { get; } public ImmutableArray<ImageElement> AttributeIcons { get; } public string InsertionText { get; } } private VSCompletionItem Convert( Document document, RoslynCompletionItem roslynItem, FilterSet filterSet) { VSCompletionItemData itemData; if (roslynItem.Flags.IsCached() && s_roslynItemToVsItemData.TryGetValue(roslynItem, out var boxedItemData)) { itemData = boxedItemData.Value; filterSet.CombineData(itemData.FilterSetData); } else { var imageId = roslynItem.Tags.GetFirstGlyph().GetImageId(); var (filters, filterSetData) = filterSet.GetFiltersAndAddToSet(roslynItem); // roslynItem generated by providers can contain an insertionText in a property bag. // We will not use it but other providers may need it. // We actually will calculate the insertion text once again when called TryCommit. if (!roslynItem.Properties.TryGetValue(InsertionText, out var insertionText)) { insertionText = roslynItem.DisplayText; } var supportedPlatforms = SymbolCompletionItem.GetSupportedPlatforms(roslynItem, document.Project.Solution.Workspace); var attributeImages = supportedPlatforms != null ? s_WarningImageAttributeImagesArray : ImmutableArray<ImageElement>.Empty; itemData = new VSCompletionItemData( displayText: roslynItem.GetEntireDisplayText(), icon: new ImageElement(new ImageId(imageId.Guid, imageId.Id), roslynItem.DisplayText), filters: filters, filterSetData: filterSetData, attributeIcons: attributeImages, insertionText: insertionText); // It doesn't make sense to cache VS item data for those Roslyn items created from scratch for each session, // since CWT uses object identity for comparison. if (roslynItem.Flags.IsCached()) { s_roslynItemToVsItemData.Add(roslynItem, new StrongBox<VSCompletionItemData>(itemData)); } } var item = new VSCompletionItem( displayText: itemData.DisplayText, source: this, icon: itemData.Icon, filters: itemData.Filters, suffix: roslynItem.InlineDescription, // InlineDescription will be right-aligned in the selection popup insertText: itemData.InsertionText, sortText: roslynItem.SortText, filterText: roslynItem.FilterText, automationText: roslynItem.AutomationText ?? roslynItem.DisplayText, attributeIcons: itemData.AttributeIcons); item.Properties.AddProperty(RoslynItem, roslynItem); return item; } private static ImmutableArray<char> GetExcludedCommitCharacters(ImmutableArray<RoslynCompletionItem> roslynItems) { var hashSet = new HashSet<char>(); foreach (var roslynItem in roslynItems) { foreach (var rule in roslynItem.Rules.FilterCharacterRules) { if (rule.Kind == CharacterSetModificationKind.Add) { foreach (var c in rule.Characters) { hashSet.Add(c); } } } } return hashSet.ToImmutableArray(); } internal static bool QuestionMarkIsPrecededByIdentifierAndWhitespace( SourceText text, int questionPosition, ISyntaxFactsService syntaxFacts) { var startOfLine = text.Lines.GetLineFromPosition(questionPosition).Start; // First, skip all the whitespace. var current = startOfLine; while (current < questionPosition && char.IsWhiteSpace(text[current])) { current++; } if (current < questionPosition && syntaxFacts.IsIdentifierStartCharacter(text[current])) { current++; } else { return false; } while (current < questionPosition && syntaxFacts.IsIdentifierPartCharacter(text[current])) { current++; } return current == questionPosition; } } }
// Licensed to the .NET Foundation under one or more 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.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Core.Imaging; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Adornments; using Microsoft.VisualStudio.Text.Editor; using AsyncCompletionData = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; using RoslynCompletionItem = Microsoft.CodeAnalysis.Completion.CompletionItem; using VSCompletionItem = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data.CompletionItem; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion { internal sealed class CompletionSource : ForegroundThreadAffinitizedObject, IAsyncExpandingCompletionSource { internal const string RoslynItem = nameof(RoslynItem); internal const string TriggerLocation = nameof(TriggerLocation); internal const string ExpandedItemTriggerLocation = nameof(ExpandedItemTriggerLocation); internal const string CompletionListSpan = nameof(CompletionListSpan); internal const string InsertionText = nameof(InsertionText); internal const string HasSuggestionItemOptions = nameof(HasSuggestionItemOptions); internal const string Description = nameof(Description); internal const string PotentialCommitCharacters = nameof(PotentialCommitCharacters); internal const string ExcludedCommitCharacters = nameof(ExcludedCommitCharacters); internal const string NonBlockingCompletion = nameof(NonBlockingCompletion); internal const string TypeImportCompletionEnabled = nameof(TypeImportCompletionEnabled); internal const string TargetTypeFilterExperimentEnabled = nameof(TargetTypeFilterExperimentEnabled); private static readonly ImmutableArray<ImageElement> s_WarningImageAttributeImagesArray = ImmutableArray.Create(new ImageElement(Glyph.CompletionWarning.GetImageId(), EditorFeaturesResources.Warning_image_element)); private static readonly EditorOptionKey<bool> NonBlockingCompletionEditorOption = new(NonBlockingCompletion); // Use CWT to cache data needed to create VSCompletionItem, so the table would be cleared when Roslyn completion item cache is cleared. private static readonly ConditionalWeakTable<RoslynCompletionItem, StrongBox<VSCompletionItemData>> s_roslynItemToVsItemData = new(); private readonly ITextView _textView; private readonly bool _isDebuggerTextView; private readonly ImmutableHashSet<string> _roles; private readonly Lazy<IStreamingFindUsagesPresenter> _streamingPresenter; private bool _snippetCompletionTriggeredIndirectly; internal CompletionSource( ITextView textView, Lazy<IStreamingFindUsagesPresenter> streamingPresenter, IThreadingContext threadingContext) : base(threadingContext) { _textView = textView; _streamingPresenter = streamingPresenter; _isDebuggerTextView = textView is IDebuggerTextView; _roles = textView.Roles.ToImmutableHashSet(); } public AsyncCompletionData.CompletionStartData InitializeCompletion( AsyncCompletionData.CompletionTrigger trigger, SnapshotPoint triggerLocation, CancellationToken cancellationToken) { // We take sourceText from document to get a snapshot span. // We would like to be sure that nobody changes buffers at the same time. AssertIsForeground(); if (_textView.Selection.Mode == TextSelectionMode.Box) { // No completion with multiple selection return AsyncCompletionData.CompletionStartData.DoesNotParticipateInCompletion; } var document = triggerLocation.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return AsyncCompletionData.CompletionStartData.DoesNotParticipateInCompletion; } var service = document.GetLanguageService<CompletionService>(); if (service == null) { return AsyncCompletionData.CompletionStartData.DoesNotParticipateInCompletion; } // The Editor supports the option per textView. // There could be mixed desired behavior per textView and even per same completion session. // The right fix would be to send this information as a result of the method. // Then, the Editor would choose the right behavior for mixed cases. _textView.Options.GlobalOptions.SetOptionValue(NonBlockingCompletionEditorOption, !document.Project.Solution.Workspace.Options.GetOption(CompletionOptions.BlockForCompletionItems2, service.Language)); // In case of calls with multiple completion services for the same view (e.g. TypeScript and C#), those completion services must not be called simultaneously for the same session. // Therefore, in each completion session we use a list of commit character for a specific completion service and a specific content type. _textView.Properties[PotentialCommitCharacters] = service.GetRules().DefaultCommitCharacters; // Reset a flag which means a snippet triggered by ? + Tab. // Set it later if met the condition. _snippetCompletionTriggeredIndirectly = false; CheckForExperimentStatus(_textView, document); var sourceText = document.GetTextSynchronously(cancellationToken); return ShouldTriggerCompletion(trigger, triggerLocation, sourceText, document, service) ? new AsyncCompletionData.CompletionStartData( participation: AsyncCompletionData.CompletionParticipation.ProvidesItems, applicableToSpan: new SnapshotSpan( triggerLocation.Snapshot, service.GetDefaultCompletionListSpan(sourceText, triggerLocation.Position).ToSpan())) : AsyncCompletionData.CompletionStartData.DoesNotParticipateInCompletion; // For telemetry reporting purpose static void CheckForExperimentStatus(ITextView textView, Document document) { var workspace = document.Project.Solution.Workspace; var experimentationService = workspace.Services.GetRequiredService<IExperimentationService>(); textView.Properties[TargetTypeFilterExperimentEnabled] = experimentationService.IsExperimentEnabled(WellKnownExperimentNames.TargetTypedCompletionFilter); var importCompletionOptionValue = workspace.Options.GetOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, document.Project.Language); var importCompletionExperimentValue = experimentationService.IsExperimentEnabled(WellKnownExperimentNames.TypeImportCompletion); var isTypeImportEnababled = importCompletionOptionValue == true || (importCompletionOptionValue == null && importCompletionExperimentValue); textView.Properties[TypeImportCompletionEnabled] = isTypeImportEnababled; } } private bool ShouldTriggerCompletion( AsyncCompletionData.CompletionTrigger trigger, SnapshotPoint triggerLocation, SourceText sourceText, Document document, CompletionService completionService) { // The trigger reason guarantees that user wants a completion. if (trigger.Reason == AsyncCompletionData.CompletionTriggerReason.Invoke || trigger.Reason == AsyncCompletionData.CompletionTriggerReason.InvokeAndCommitIfUnique) { return true; } // Enter does not trigger completion. if (trigger.Reason == AsyncCompletionData.CompletionTriggerReason.Insertion && trigger.Character == '\n') { return false; } //The user may be trying to invoke snippets through question-tab. // We may provide a completion after that. // Otherwise, tab should not be a completion trigger. if (trigger.Reason == AsyncCompletionData.CompletionTriggerReason.Insertion && trigger.Character == '\t') { return TryInvokeSnippetCompletion(completionService, document, sourceText, triggerLocation.Position); } var roslynTrigger = Helpers.GetRoslynTrigger(trigger, triggerLocation); // The completion service decides that user may want a completion. if (completionService.ShouldTriggerCompletion(document.Project, sourceText, triggerLocation.Position, roslynTrigger)) { return true; } return false; } private bool TryInvokeSnippetCompletion( CompletionService completionService, Document document, SourceText text, int caretPoint) { var rules = completionService.GetRules(); // Do not invoke snippet if the corresponding rule is not set in options. if (rules.SnippetsRule != SnippetsRule.IncludeAfterTypingIdentifierQuestionTab) { return false; } var syntaxFactsOpt = document.GetLanguageService<ISyntaxFactsService>(); // Snippets are included if the user types: <quesiton><tab> // If at least one condition for snippets do not hold, bail out. if (syntaxFactsOpt == null || caretPoint < 3 || text[caretPoint - 2] != '?' || !QuestionMarkIsPrecededByIdentifierAndWhitespace(text, caretPoint - 2, syntaxFactsOpt)) { return false; } // Because <question><tab> is actually a command to bring up snippets, // we delete the last <question> that was typed. var textChange = new TextChange(TextSpan.FromBounds(caretPoint - 2, caretPoint), string.Empty); document.Project.Solution.Workspace.ApplyTextChanges(document.Id, textChange, CancellationToken.None); _snippetCompletionTriggeredIndirectly = true; return true; } public Task<AsyncCompletionData.CompletionContext> GetCompletionContextAsync( IAsyncCompletionSession session, AsyncCompletionData.CompletionTrigger trigger, SnapshotPoint triggerLocation, SnapshotSpan applicableToSpan, CancellationToken cancellationToken) { if (session is null) throw new ArgumentNullException(nameof(session)); return GetCompletionContextWorkerAsync(session, trigger, triggerLocation, isExpanded: false, cancellationToken); } public async Task<AsyncCompletionData.CompletionContext> GetExpandedCompletionContextAsync( IAsyncCompletionSession session, AsyncCompletionData.CompletionExpander expander, AsyncCompletionData.CompletionTrigger intialTrigger, SnapshotSpan applicableToSpan, CancellationToken cancellationToken) { // We only want to provide expanded items for Roslyn's expander. if ((object)expander == FilterSet.Expander && session.Properties.TryGetProperty(ExpandedItemTriggerLocation, out SnapshotPoint initialTriggerLocation)) { return await GetCompletionContextWorkerAsync(session, intialTrigger, initialTriggerLocation, isExpanded: true, cancellationToken).ConfigureAwait(false); } return AsyncCompletionData.CompletionContext.Empty; } private async Task<AsyncCompletionData.CompletionContext> GetCompletionContextWorkerAsync( IAsyncCompletionSession session, AsyncCompletionData.CompletionTrigger trigger, SnapshotPoint triggerLocation, bool isExpanded, CancellationToken cancellationToken) { var document = triggerLocation.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return AsyncCompletionData.CompletionContext.Empty; } var completionService = document.GetRequiredLanguageService<CompletionService>(); var roslynTrigger = Helpers.GetRoslynTrigger(trigger, triggerLocation); if (_snippetCompletionTriggeredIndirectly) { roslynTrigger = new CompletionTrigger(CompletionTriggerKind.Snippets); } var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var options = documentOptions .WithChangedOption(CompletionServiceOptions.IsExpandedCompletion, isExpanded); if (_isDebuggerTextView) { options = options .WithChangedOption(CompletionControllerOptions.FilterOutOfScopeLocals, false) .WithChangedOption(CompletionControllerOptions.ShowXmlDocCommentCompletion, false); } var (completionList, expandItemsAvailable) = await completionService.GetCompletionsInternalAsync( document, triggerLocation, roslynTrigger, _roles, options, cancellationToken).ConfigureAwait(false); ImmutableArray<VSCompletionItem> items; AsyncCompletionData.SuggestionItemOptions? suggestionItemOptions; var filterSet = new FilterSet(); if (completionList == null) { items = ImmutableArray<VSCompletionItem>.Empty; suggestionItemOptions = null; } else { var itemsBuilder = new ArrayBuilder<VSCompletionItem>(completionList.Items.Length); foreach (var roslynItem in completionList.Items) { cancellationToken.ThrowIfCancellationRequested(); var item = Convert(document, roslynItem, filterSet, triggerLocation); itemsBuilder.Add(item); } items = itemsBuilder.ToImmutableAndFree(); suggestionItemOptions = completionList.SuggestionModeItem != null ? new AsyncCompletionData.SuggestionItemOptions( completionList.SuggestionModeItem.DisplayText, completionList.SuggestionModeItem.Properties.TryGetValue(Description, out var description) ? description : string.Empty) : null; // Store around the span this completion list applies to. We'll use this later // to pass this value in when we're committing a completion list item. // It's OK to overwrite this value when expanded items are requested. session.Properties[CompletionListSpan] = completionList.Span; // This is a code supporting original completion scenarios: // Controller.Session_ComputeModel: if completionList.SuggestionModeItem != null, then suggestionMode = true // If there are suggestionItemOptions, then later HandleNormalFiltering should set selection to SoftSelection. if (!session.Properties.TryGetProperty(HasSuggestionItemOptions, out bool hasSuggestionItemOptionsBefore) || !hasSuggestionItemOptionsBefore) { session.Properties[HasSuggestionItemOptions] = suggestionItemOptions != null; } var excludedCommitCharacters = GetExcludedCommitCharacters(completionList.Items); if (excludedCommitCharacters.Length > 0) { if (session.Properties.TryGetProperty(ExcludedCommitCharacters, out ImmutableArray<char> excludedCommitCharactersBefore)) { excludedCommitCharacters = excludedCommitCharacters.Union(excludedCommitCharactersBefore).ToImmutableArray(); } session.Properties[ExcludedCommitCharacters] = excludedCommitCharacters; } } // We need to remember the trigger location for when a completion service claims expanded items are available // since the initial trigger we are able to get from IAsyncCompletionSession might not be the same (e.g. in projection scenarios) // so when they are requested via expander later, we can retrieve it. // Technically we should save the trigger location for each individual service that made such claim, but in reality only Roslyn's // completion service uses expander, so we can get away with not making such distinction. if (!isExpanded && expandItemsAvailable) { session.Properties[ExpandedItemTriggerLocation] = triggerLocation; } // It's possible that some providers can provide expanded items, in which case we will need to show expander as unselected. return new AsyncCompletionData.CompletionContext( items, suggestionItemOptions, suggestionItemOptions == null ? AsyncCompletionData.InitialSelectionHint.RegularSelection : AsyncCompletionData.InitialSelectionHint.SoftSelection, filterSet.GetFilterStatesInSet(addUnselectedExpander: expandItemsAvailable)); } public async Task<object?> GetDescriptionAsync(IAsyncCompletionSession session, VSCompletionItem item, CancellationToken cancellationToken) { if (session is null) throw new ArgumentNullException(nameof(session)); if (item is null) throw new ArgumentNullException(nameof(item)); if (!item.Properties.TryGetProperty(RoslynItem, out RoslynCompletionItem roslynItem) || !item.Properties.TryGetProperty(TriggerLocation, out SnapshotPoint triggerLocation)) { return null; } var document = triggerLocation.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return null; } var service = document.GetLanguageService<CompletionService>(); if (service == null) { return null; } var description = await service.GetDescriptionAsync(document, roslynItem, cancellationToken).ConfigureAwait(false); var context = new IntellisenseQuickInfoBuilderContext(document, ThreadingContext, _streamingPresenter); var elements = IntelliSense.Helpers.BuildInteractiveTextElements(description.TaggedParts, context).ToArray(); if (elements.Length == 0) { return new ClassifiedTextElement(); } else if (elements.Length == 1) { return elements[0]; } else { return new ContainerElement(ContainerElementStyle.Stacked | ContainerElementStyle.VerticalPadding, elements); } } /// <summary> /// We'd like to cache VS Completion item directly to avoid allocation completely. However it holds references /// to transient objects, which would cause memory leak (among other potential issues) if cached. /// So as a compromise, we cache data that can be calculated from Roslyn completion item to avoid repeated /// calculation cost for cached Roslyn completion items. /// </summary> private readonly struct VSCompletionItemData { public VSCompletionItemData( string displayText, ImageElement icon, ImmutableArray<AsyncCompletionData.CompletionFilter> filters, int filterSetData, ImmutableArray<ImageElement> attributeIcons, string insertionText) { DisplayText = displayText; Icon = icon; Filters = filters; FilterSetData = filterSetData; AttributeIcons = attributeIcons; InsertionText = insertionText; } public string DisplayText { get; } public ImageElement Icon { get; } public ImmutableArray<AsyncCompletionData.CompletionFilter> Filters { get; } /// <summary> /// This is the bit vector value from the FilterSet of this item. /// </summary> public int FilterSetData { get; } public ImmutableArray<ImageElement> AttributeIcons { get; } public string InsertionText { get; } } private VSCompletionItem Convert( Document document, RoslynCompletionItem roslynItem, FilterSet filterSet, SnapshotPoint initialTriggerLocation) { VSCompletionItemData itemData; if (roslynItem.Flags.IsCached() && s_roslynItemToVsItemData.TryGetValue(roslynItem, out var boxedItemData)) { itemData = boxedItemData.Value; filterSet.CombineData(itemData.FilterSetData); } else { var imageId = roslynItem.Tags.GetFirstGlyph().GetImageId(); var (filters, filterSetData) = filterSet.GetFiltersAndAddToSet(roslynItem); // roslynItem generated by providers can contain an insertionText in a property bag. // We will not use it but other providers may need it. // We actually will calculate the insertion text once again when called TryCommit. if (!roslynItem.Properties.TryGetValue(InsertionText, out var insertionText)) { insertionText = roslynItem.DisplayText; } var supportedPlatforms = SymbolCompletionItem.GetSupportedPlatforms(roslynItem, document.Project.Solution.Workspace); var attributeImages = supportedPlatforms != null ? s_WarningImageAttributeImagesArray : ImmutableArray<ImageElement>.Empty; itemData = new VSCompletionItemData( displayText: roslynItem.GetEntireDisplayText(), icon: new ImageElement(new ImageId(imageId.Guid, imageId.Id), roslynItem.DisplayText), filters: filters, filterSetData: filterSetData, attributeIcons: attributeImages, insertionText: insertionText); // It doesn't make sense to cache VS item data for those Roslyn items created from scratch for each session, // since CWT uses object identity for comparison. if (roslynItem.Flags.IsCached()) { s_roslynItemToVsItemData.Add(roslynItem, new StrongBox<VSCompletionItemData>(itemData)); } } var item = new VSCompletionItem( displayText: itemData.DisplayText, source: this, icon: itemData.Icon, filters: itemData.Filters, suffix: roslynItem.InlineDescription, // InlineDescription will be right-aligned in the selection popup insertText: itemData.InsertionText, sortText: roslynItem.SortText, filterText: roslynItem.FilterText, automationText: roslynItem.AutomationText ?? roslynItem.DisplayText, attributeIcons: itemData.AttributeIcons); item.Properties.AddProperty(RoslynItem, roslynItem); item.Properties.AddProperty(TriggerLocation, initialTriggerLocation); return item; } private static ImmutableArray<char> GetExcludedCommitCharacters(ImmutableArray<RoslynCompletionItem> roslynItems) { var hashSet = new HashSet<char>(); foreach (var roslynItem in roslynItems) { foreach (var rule in roslynItem.Rules.FilterCharacterRules) { if (rule.Kind == CharacterSetModificationKind.Add) { foreach (var c in rule.Characters) { hashSet.Add(c); } } } } return hashSet.ToImmutableArray(); } internal static bool QuestionMarkIsPrecededByIdentifierAndWhitespace( SourceText text, int questionPosition, ISyntaxFactsService syntaxFacts) { var startOfLine = text.Lines.GetLineFromPosition(questionPosition).Start; // First, skip all the whitespace. var current = startOfLine; while (current < questionPosition && char.IsWhiteSpace(text[current])) { current++; } if (current < questionPosition && syntaxFacts.IsIdentifierStartCharacter(text[current])) { current++; } else { return false; } while (current < questionPosition && syntaxFacts.IsIdentifierPartCharacter(text[current])) { current++; } return current == questionPosition; } } }
1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/Implementation/IntelliSense/AsyncCompletion/Helpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.Completion; using Microsoft.VisualStudio.Text; using EditorAsyncCompletion = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; using EditorAsyncCompletionData = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; using RoslynCompletionItem = Microsoft.CodeAnalysis.Completion.CompletionItem; using RoslynTrigger = Microsoft.CodeAnalysis.Completion.CompletionTrigger; using VSCompletionItem = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data.CompletionItem; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion { internal static class Helpers { /// <summary> /// Attempts to convert VS Completion trigger into Roslyn completion trigger /// </summary> /// <param name="trigger">VS completion trigger</param> /// <param name="triggerLocation">Character. /// VS provides Backspace and Delete characters inside the trigger while Roslyn needs the char deleted by the trigger. /// Therefore, we provide this character separately and use it for Delete and Backspace cases only. /// We retrieve this character from triggerLocation. /// </param> /// <returns>Roslyn completion trigger</returns> internal static RoslynTrigger GetRoslynTrigger(EditorAsyncCompletionData.CompletionTrigger trigger, SnapshotPoint triggerLocation) { var completionTriggerKind = GetRoslynTriggerKind(trigger); if (completionTriggerKind == CompletionTriggerKind.Deletion) { var snapshotBeforeEdit = trigger.ViewSnapshotBeforeTrigger; char characterRemoved; if (triggerLocation.Position >= 0 && triggerLocation.Position < snapshotBeforeEdit.Length) { // If multiple characters were removed (selection), this finds the first character from the left. characterRemoved = snapshotBeforeEdit[triggerLocation.Position]; } else { characterRemoved = (char)0; } return RoslynTrigger.CreateDeletionTrigger(characterRemoved); } else { return new RoslynTrigger(completionTriggerKind, trigger.Character); } } internal static CompletionTriggerKind GetRoslynTriggerKind(EditorAsyncCompletionData.CompletionTrigger trigger) { switch (trigger.Reason) { case EditorAsyncCompletionData.CompletionTriggerReason.InvokeAndCommitIfUnique: return CompletionTriggerKind.InvokeAndCommitIfUnique; case EditorAsyncCompletionData.CompletionTriggerReason.Insertion: return CompletionTriggerKind.Insertion; case EditorAsyncCompletionData.CompletionTriggerReason.Deletion: case EditorAsyncCompletionData.CompletionTriggerReason.Backspace: return CompletionTriggerKind.Deletion; case EditorAsyncCompletionData.CompletionTriggerReason.SnippetsMode: return CompletionTriggerKind.Snippets; default: return CompletionTriggerKind.Invoke; } } internal static CompletionFilterReason GetFilterReason(EditorAsyncCompletionData.CompletionTrigger trigger) { switch (trigger.Reason) { case EditorAsyncCompletionData.CompletionTriggerReason.Insertion: return CompletionFilterReason.Insertion; case EditorAsyncCompletionData.CompletionTriggerReason.Deletion: case EditorAsyncCompletionData.CompletionTriggerReason.Backspace: return CompletionFilterReason.Deletion; default: return CompletionFilterReason.Other; } } internal static bool IsFilterCharacter(RoslynCompletionItem item, char ch, string textTypedSoFar) { // Exclude standard commit character upfront because TextTypedSoFarMatchesItem can miss them on non-Windows platforms. if (IsStandardCommitCharacter(ch)) { return false; } // First see if the item has any specific filter rules it wants followed. foreach (var rule in item.Rules.FilterCharacterRules) { switch (rule.Kind) { case CharacterSetModificationKind.Add: if (rule.Characters.Contains(ch)) { return true; } continue; case CharacterSetModificationKind.Remove: if (rule.Characters.Contains(ch)) { return false; } continue; case CharacterSetModificationKind.Replace: return rule.Characters.Contains(ch); } } // general rule: if the filtering text exactly matches the start of the item then it must be a filter character if (TextTypedSoFarMatchesItem(item, textTypedSoFar)) { return true; } return false; } internal static bool TextTypedSoFarMatchesItem(RoslynCompletionItem item, string textTypedSoFar) { if (textTypedSoFar.Length > 0) { // Note that StartsWith ignores \0 at the end of textTypedSoFar on VS Mac and Mono. return item.DisplayText.StartsWith(textTypedSoFar, StringComparison.CurrentCultureIgnoreCase) || item.FilterText.StartsWith(textTypedSoFar, StringComparison.CurrentCultureIgnoreCase); } return false; } // Tab, Enter and Null (call invoke commit) are always commit characters. internal static bool IsStandardCommitCharacter(char c) => c == '\t' || c == '\n' || c == '\0'; internal static bool TryGetInitialTriggerLocation(EditorAsyncCompletion.IAsyncCompletionSession session, out SnapshotPoint initialTriggerLocation) => session.Properties.TryGetProperty(CompletionSource.TriggerLocation, out initialTriggerLocation); // This is a temporarily method to support preference of IntelliCode items comparing to non-IntelliCode items. // We expect that Editor will introduce this support and we will get rid of relying on the "★" then. internal static bool IsPreferredItem(this VSCompletionItem completionItem) => completionItem.DisplayText.StartsWith("★"); } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.Completion; using Microsoft.VisualStudio.Text; using EditorAsyncCompletion = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; using EditorAsyncCompletionData = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; using RoslynCompletionItem = Microsoft.CodeAnalysis.Completion.CompletionItem; using RoslynTrigger = Microsoft.CodeAnalysis.Completion.CompletionTrigger; using VSCompletionItem = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data.CompletionItem; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion { internal static class Helpers { /// <summary> /// Attempts to convert VS Completion trigger into Roslyn completion trigger /// </summary> /// <param name="trigger">VS completion trigger</param> /// <param name="triggerLocation">Character. /// VS provides Backspace and Delete characters inside the trigger while Roslyn needs the char deleted by the trigger. /// Therefore, we provide this character separately and use it for Delete and Backspace cases only. /// We retrieve this character from triggerLocation. /// </param> /// <returns>Roslyn completion trigger</returns> internal static RoslynTrigger GetRoslynTrigger(EditorAsyncCompletionData.CompletionTrigger trigger, SnapshotPoint triggerLocation) { var completionTriggerKind = GetRoslynTriggerKind(trigger); if (completionTriggerKind == CompletionTriggerKind.Deletion) { var snapshotBeforeEdit = trigger.ViewSnapshotBeforeTrigger; char characterRemoved; if (triggerLocation.Position >= 0 && triggerLocation.Position < snapshotBeforeEdit.Length) { // If multiple characters were removed (selection), this finds the first character from the left. characterRemoved = snapshotBeforeEdit[triggerLocation.Position]; } else { characterRemoved = (char)0; } return RoslynTrigger.CreateDeletionTrigger(characterRemoved); } else { return new RoslynTrigger(completionTriggerKind, trigger.Character); } } internal static CompletionTriggerKind GetRoslynTriggerKind(EditorAsyncCompletionData.CompletionTrigger trigger) { switch (trigger.Reason) { case EditorAsyncCompletionData.CompletionTriggerReason.InvokeAndCommitIfUnique: return CompletionTriggerKind.InvokeAndCommitIfUnique; case EditorAsyncCompletionData.CompletionTriggerReason.Insertion: return CompletionTriggerKind.Insertion; case EditorAsyncCompletionData.CompletionTriggerReason.Deletion: case EditorAsyncCompletionData.CompletionTriggerReason.Backspace: return CompletionTriggerKind.Deletion; case EditorAsyncCompletionData.CompletionTriggerReason.SnippetsMode: return CompletionTriggerKind.Snippets; default: return CompletionTriggerKind.Invoke; } } internal static CompletionFilterReason GetFilterReason(EditorAsyncCompletionData.CompletionTrigger trigger) { switch (trigger.Reason) { case EditorAsyncCompletionData.CompletionTriggerReason.Insertion: return CompletionFilterReason.Insertion; case EditorAsyncCompletionData.CompletionTriggerReason.Deletion: case EditorAsyncCompletionData.CompletionTriggerReason.Backspace: return CompletionFilterReason.Deletion; default: return CompletionFilterReason.Other; } } internal static bool IsFilterCharacter(RoslynCompletionItem item, char ch, string textTypedSoFar) { // Exclude standard commit character upfront because TextTypedSoFarMatchesItem can miss them on non-Windows platforms. if (IsStandardCommitCharacter(ch)) { return false; } // First see if the item has any specific filter rules it wants followed. foreach (var rule in item.Rules.FilterCharacterRules) { switch (rule.Kind) { case CharacterSetModificationKind.Add: if (rule.Characters.Contains(ch)) { return true; } continue; case CharacterSetModificationKind.Remove: if (rule.Characters.Contains(ch)) { return false; } continue; case CharacterSetModificationKind.Replace: return rule.Characters.Contains(ch); } } // general rule: if the filtering text exactly matches the start of the item then it must be a filter character if (TextTypedSoFarMatchesItem(item, textTypedSoFar)) { return true; } return false; } internal static bool TextTypedSoFarMatchesItem(RoslynCompletionItem item, string textTypedSoFar) { if (textTypedSoFar.Length > 0) { // Note that StartsWith ignores \0 at the end of textTypedSoFar on VS Mac and Mono. return item.DisplayText.StartsWith(textTypedSoFar, StringComparison.CurrentCultureIgnoreCase) || item.FilterText.StartsWith(textTypedSoFar, StringComparison.CurrentCultureIgnoreCase); } return false; } // Tab, Enter and Null (call invoke commit) are always commit characters. internal static bool IsStandardCommitCharacter(char c) => c == '\t' || c == '\n' || c == '\0'; // This is a temporarily method to support preference of IntelliCode items comparing to non-IntelliCode items. // We expect that Editor will introduce this support and we will get rid of relying on the "★" then. internal static bool IsPreferredItem(this VSCompletionItem completionItem) => completionItem.DisplayText.StartsWith("★"); } }
1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/Implementation/IntelliSense/AsyncCompletion/ItemManager.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.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.PatternMatching; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; using RoslynCompletionItem = Microsoft.CodeAnalysis.Completion.CompletionItem; using VSCompletionItem = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data.CompletionItem; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion { internal class ItemManager : IAsyncCompletionItemManager { /// <summary> /// Used for filtering non-Roslyn data only. /// </summary> private readonly CompletionHelper _defaultCompletionHelper; private readonly RecentItemsManager _recentItemsManager; /// <summary> /// For telemetry. /// </summary> private readonly object _targetTypeCompletionFilterChosenMarker = new(); internal ItemManager(RecentItemsManager recentItemsManager) { // Let us make the completion Helper used for non-Roslyn items case-sensitive. // We can change this if get requests from partner teams. _defaultCompletionHelper = new CompletionHelper(isCaseSensitive: true); _recentItemsManager = recentItemsManager; } public Task<ImmutableArray<VSCompletionItem>> SortCompletionListAsync( IAsyncCompletionSession session, AsyncCompletionSessionInitialDataSnapshot data, CancellationToken cancellationToken) { if (session.TextView.Properties.TryGetProperty(CompletionSource.TargetTypeFilterExperimentEnabled, out bool isTargetTypeFilterEnabled) && isTargetTypeFilterEnabled) { AsyncCompletionLogger.LogSessionHasTargetTypeFilterEnabled(); // This method is called exactly once, so use the opportunity to set a baseline for telemetry. if (data.InitialList.Any(i => i.Filters.Any(f => f.DisplayText == FeaturesResources.Target_type_matches))) { AsyncCompletionLogger.LogSessionContainsTargetTypeFilter(); } } if (session.TextView.Properties.TryGetProperty(CompletionSource.TypeImportCompletionEnabled, out bool isTypeImportCompletionEnabled) && isTypeImportCompletionEnabled) { AsyncCompletionLogger.LogSessionWithTypeImportCompletionEnabled(); } // Sort by default comparer of Roslyn CompletionItem var sortedItems = data.InitialList.OrderBy(GetOrAddRoslynCompletionItem).ToImmutableArray(); return Task.FromResult(sortedItems); } public Task<FilteredCompletionModel?> UpdateCompletionListAsync( IAsyncCompletionSession session, AsyncCompletionSessionDataSnapshot data, CancellationToken cancellationToken) => Task.FromResult(UpdateCompletionList(session, data, cancellationToken)); // We might need to handle large amount of items with import completion enabled, // so use a dedicated pool to minimize/avoid array allocations (especially in LOH) // Set the size of pool to 1 because we don't expect UpdateCompletionListAsync to be // called concurrently, which essentially makes the pooled list a singleton, // but we still use ObjectPool for concurrency handling just to be robust. private static readonly ObjectPool<List<MatchResult<VSCompletionItem>>> s_listOfMatchResultPool = new(factory: () => new(), size: 1); private FilteredCompletionModel? UpdateCompletionList( IAsyncCompletionSession session, AsyncCompletionSessionDataSnapshot data, CancellationToken cancellationToken) { if (!session.Properties.TryGetProperty(CompletionSource.HasSuggestionItemOptions, out bool hasSuggestedItemOptions)) { // This is the scenario when the session is created out of Roslyn, in some other provider, e.g. in Debugger. // For now, the default hasSuggestedItemOptions is false. hasSuggestedItemOptions = false; } hasSuggestedItemOptions |= data.DisplaySuggestionItem; var filterText = session.ApplicableToSpan.GetText(data.Snapshot); var reason = data.Trigger.Reason; var initialRoslynTriggerKind = Helpers.GetRoslynTriggerKind(data.InitialTrigger); // Check if the user is typing a number. If so, only proceed if it's a number // directly after a <dot>. That's because it is actually reasonable for completion // to be brought up after a <dot> and for the user to want to filter completion // items based on a number that exists in the name of the item. However, when // we are not after a dot (i.e. we're being brought up after <space> is typed) // then we don't want to filter things. Consider the user writing: // // dim i =<space> // // We'll bring up the completion list here (as VB has completion on <space>). // If the user then types '3', we don't want to match against Int32. if (filterText.Length > 0 && char.IsNumber(filterText[0])) { if (!IsAfterDot(data.Snapshot, session.ApplicableToSpan)) { // Dismiss the session. return null; } } // We need to filter if // 1. a non-empty strict subset of filters are selected // 2. a non-empty set of expanders are unselected var nonExpanderFilterStates = data.SelectedFilters.WhereAsArray(f => !(f.Filter is CompletionExpander)); var selectedNonExpanderFilters = nonExpanderFilterStates.SelectAsArray(f => f.IsSelected, f => f.Filter); var needToFilter = selectedNonExpanderFilters.Length > 0 && selectedNonExpanderFilters.Length < nonExpanderFilterStates.Length; var unselectedExpanders = data.SelectedFilters.SelectAsArray(f => !f.IsSelected && f.Filter is CompletionExpander, f => f.Filter); var needToFilterExpanded = unselectedExpanders.Length > 0; if (session.TextView.Properties.TryGetProperty(CompletionSource.TargetTypeFilterExperimentEnabled, out bool isExperimentEnabled) && isExperimentEnabled) { // Telemetry: Want to know % of sessions with the "Target type matches" filter where that filter is actually enabled if (needToFilter && !session.Properties.ContainsProperty(_targetTypeCompletionFilterChosenMarker) && selectedNonExpanderFilters.Any(f => f.DisplayText == FeaturesResources.Target_type_matches)) { AsyncCompletionLogger.LogTargetTypeFilterChosenInSession(); // Make sure we only record one enabling of the filter per session session.Properties.AddProperty(_targetTypeCompletionFilterChosenMarker, _targetTypeCompletionFilterChosenMarker); } } var filterReason = Helpers.GetFilterReason(data.Trigger); // If the session was created/maintained out of Roslyn, e.g. in debugger; no properties are set and we should use data.Snapshot. // However, we prefer using the original snapshot in some projection scenarios. var snapshotForDocument = Helpers.TryGetInitialTriggerLocation(session, out var triggerLocation) ? triggerLocation.Snapshot : data.Snapshot; var document = snapshotForDocument.TextBuffer.AsTextContainer().GetOpenDocumentInCurrentContext(); var completionService = document?.GetLanguageService<CompletionService>(); var completionRules = completionService?.GetRules() ?? CompletionRules.Default; var completionHelper = document != null ? CompletionHelper.GetHelper(document) : _defaultCompletionHelper; // DismissIfLastCharacterDeleted should be applied only when started with Insertion, and then Deleted all characters typed. // This conforms with the original VS 2010 behavior. if (initialRoslynTriggerKind == CompletionTriggerKind.Insertion && data.Trigger.Reason == CompletionTriggerReason.Backspace && completionRules.DismissIfLastCharacterDeleted && session.ApplicableToSpan.GetText(data.Snapshot).Length == 0) { // Dismiss the session return null; } var options = document?.Project.Solution.Options; var highlightMatchingPortions = options?.GetOption(CompletionOptions.HighlightMatchingPortionsOfCompletionListItems, document?.Project.Language) ?? false; // Nothing to highlight if user hasn't typed anything yet. highlightMatchingPortions = highlightMatchingPortions && filterText.Length > 0; // Use a monotonically increasing integer to keep track the original alphabetical order of each item. var currentIndex = 0; var initialListOfItemsToBeIncluded = s_listOfMatchResultPool.Allocate(); try { // Filter items based on the selected filters and matching. foreach (var item in data.InitialSortedList) { cancellationToken.ThrowIfCancellationRequested(); if (needToFilter && ShouldBeFilteredOutOfCompletionList(item, selectedNonExpanderFilters)) { continue; } if (needToFilterExpanded && ShouldBeFilteredOutOfExpandedCompletionList(item, unselectedExpanders)) { continue; } if (TryCreateMatchResult( completionHelper, item, filterText, initialRoslynTriggerKind, filterReason, _recentItemsManager.RecentItems, highlightMatchingPortions: highlightMatchingPortions, currentIndex, out var matchResult)) { initialListOfItemsToBeIncluded.Add(matchResult); currentIndex++; } } if (initialListOfItemsToBeIncluded.Count == 0) { return HandleAllItemsFilteredOut(reason, data.SelectedFilters, completionRules); } // Sort the items by pattern matching results. // Note that we want to preserve the original alphabetical order for items with same pattern match score, // but `List<T>.Sort` isn't stable. Therefore we have to add a monotonically increasing integer // to `MatchResult` to achieve this. initialListOfItemsToBeIncluded.Sort(MatchResult<VSCompletionItem>.SortingComparer); var showCompletionItemFilters = options?.GetOption(CompletionOptions.ShowCompletionItemFilters, document?.Project.Language) ?? true; var updatedFilters = showCompletionItemFilters ? GetUpdatedFilters(initialListOfItemsToBeIncluded, data.SelectedFilters) : ImmutableArray<CompletionFilterWithState>.Empty; // If this was deletion, then we control the entire behavior of deletion ourselves. if (initialRoslynTriggerKind == CompletionTriggerKind.Deletion) { return HandleDeletionTrigger(reason, initialListOfItemsToBeIncluded, filterText, updatedFilters, hasSuggestedItemOptions, highlightMatchingPortions, completionHelper); } Func<ImmutableArray<(RoslynCompletionItem, PatternMatch?)>, string, ImmutableArray<RoslynCompletionItem>> filterMethod; if (completionService == null) { filterMethod = (itemsWithPatternMatches, text) => CompletionService.FilterItems(completionHelper, itemsWithPatternMatches); } else { filterMethod = (itemsWithPatternMatches, text) => completionService.FilterItems(document, itemsWithPatternMatches, text); } return HandleNormalFiltering( filterMethod, filterText, updatedFilters, filterReason, data.Trigger.Character, initialListOfItemsToBeIncluded, hasSuggestedItemOptions, highlightMatchingPortions, completionHelper); } finally { // Don't call ClearAndFree, which resets the capacity to a default value. initialListOfItemsToBeIncluded.Clear(); s_listOfMatchResultPool.Free(initialListOfItemsToBeIncluded); } static bool ShouldBeFilteredOutOfCompletionList(VSCompletionItem item, ImmutableArray<CompletionFilter> activeNonExpanderFilters) { if (item.Filters.Any(filter => activeNonExpanderFilters.Contains(filter))) { return false; } return true; } static bool ShouldBeFilteredOutOfExpandedCompletionList(VSCompletionItem item, ImmutableArray<CompletionFilter> unselectedExpanders) { var associatedWithUnselectedExpander = false; foreach (var itemFilter in item.Filters) { if (itemFilter is CompletionExpander) { if (!unselectedExpanders.Contains(itemFilter)) { // If any of the associated expander is selected, the item should be included in the expanded list. return false; } associatedWithUnselectedExpander = true; } } // at this point, the item either: // 1. has no expander filter, therefore should be included // 2. or, all associated expanders are unselected, therefore should be excluded return associatedWithUnselectedExpander; } } private static bool IsAfterDot(ITextSnapshot snapshot, ITrackingSpan applicableToSpan) { var position = applicableToSpan.GetStartPoint(snapshot).Position; return position > 0 && snapshot[position - 1] == '.'; } private FilteredCompletionModel? HandleNormalFiltering( Func<ImmutableArray<(RoslynCompletionItem, PatternMatch?)>, string, ImmutableArray<RoslynCompletionItem>> filterMethod, string filterText, ImmutableArray<CompletionFilterWithState> filters, CompletionFilterReason filterReason, char typeChar, List<MatchResult<VSCompletionItem>> itemsInList, bool hasSuggestedItemOptions, bool highlightMatchingPortions, CompletionHelper completionHelper) { // Not deletion. Defer to the language to decide which item it thinks best // matches the text typed so far. // Ask the language to determine which of the *matched* items it wants to select. var matchingItems = itemsInList.Where(r => r.MatchedFilterText) .SelectAsArray(t => (t.RoslynCompletionItem, t.PatternMatch)); var chosenItems = filterMethod(matchingItems, filterText); int selectedItemIndex; VSCompletionItem? uniqueItem = null; MatchResult<VSCompletionItem> bestOrFirstMatchResult; if (chosenItems.Length == 0) { // We do not have matches: pick the one with longest common prefix or the first item from the list. selectedItemIndex = 0; bestOrFirstMatchResult = itemsInList[0]; var longestCommonPrefixLength = bestOrFirstMatchResult.RoslynCompletionItem.FilterText.GetCaseInsensitivePrefixLength(filterText); for (var i = 1; i < itemsInList.Count; ++i) { var item = itemsInList[i]; var commonPrefixLength = item.RoslynCompletionItem.FilterText.GetCaseInsensitivePrefixLength(filterText); if (commonPrefixLength > longestCommonPrefixLength) { selectedItemIndex = i; bestOrFirstMatchResult = item; longestCommonPrefixLength = commonPrefixLength; } } } else { var recentItems = _recentItemsManager.RecentItems; // Of the items the service returned, pick the one most recently committed var bestItem = GetBestCompletionItemBasedOnMRU(chosenItems, recentItems); // Determine if we should consider this item 'unique' or not. A unique item // will be automatically committed if the user hits the 'invoke completion' // without bringing up the completion list. An item is unique if it was the // only item to match the text typed so far, and there was at least some text // typed. i.e. if we have "Console.$$" we don't want to commit something // like "WriteLine" since no filter text has actually been provided. However, // if "Console.WriteL$$" is typed, then we do want "WriteLine" to be committed. selectedItemIndex = itemsInList.IndexOf(i => Equals(i.RoslynCompletionItem, bestItem)); bestOrFirstMatchResult = itemsInList[selectedItemIndex]; var deduplicatedListCount = matchingItems.Count(r => !r.RoslynCompletionItem.IsPreferredItem()); if (deduplicatedListCount == 1 && filterText.Length > 0) { uniqueItem = itemsInList[selectedItemIndex].EditorCompletionItem; } } // Check that it is a filter symbol. We can be called for a non-filter symbol. // If inserting a non-filter character (neither IsPotentialFilterCharacter, nor Helpers.IsFilterCharacter), we should dismiss completion // except cases where this is the first symbol typed for the completion session (string.IsNullOrEmpty(filterText) or string.Equals(filterText, typeChar.ToString(), StringComparison.OrdinalIgnoreCase)). // In the latter case, we should keep the completion because it was confirmed just before in InitializeCompletion. if (filterReason == CompletionFilterReason.Insertion && !string.IsNullOrEmpty(filterText) && !string.Equals(filterText, typeChar.ToString(), StringComparison.OrdinalIgnoreCase) && !IsPotentialFilterCharacter(typeChar) && !Helpers.IsFilterCharacter(bestOrFirstMatchResult.RoslynCompletionItem, typeChar, filterText)) { return null; } var isHardSelection = IsHardSelection( filterText, bestOrFirstMatchResult.RoslynCompletionItem, bestOrFirstMatchResult.MatchedFilterText, hasSuggestedItemOptions); var updateSelectionHint = isHardSelection ? UpdateSelectionHint.Selected : UpdateSelectionHint.SoftSelected; return new FilteredCompletionModel( GetHighlightedList(itemsInList, filterText, highlightMatchingPortions, completionHelper), selectedItemIndex, filters, updateSelectionHint, centerSelection: true, uniqueItem); } private static FilteredCompletionModel? HandleDeletionTrigger( CompletionTriggerReason filterTriggerKind, List<MatchResult<VSCompletionItem>> matchResults, string filterText, ImmutableArray<CompletionFilterWithState> filters, bool hasSuggestedItemOptions, bool highlightMatchingSpans, CompletionHelper completionHelper) { var matchingItems = matchResults.Where(r => r.MatchedFilterText); if (filterTriggerKind == CompletionTriggerReason.Insertion && !matchingItems.Any()) { // The user has typed something, but nothing in the actual list matched what // they were typing. In this case, we want to dismiss completion entirely. // The thought process is as follows: we aggressively brought up completion // to help them when they typed delete (in case they wanted to pick another // item). However, they're typing something that doesn't seem to match at all // The completion list is just distracting at this point. return null; } MatchResult<VSCompletionItem>? bestMatchResult = null; var moreThanOneMatchWithSamePriority = false; foreach (var currentMatchResult in matchingItems) { if (bestMatchResult == null) { // We had no best result yet, so this is now our best result. bestMatchResult = currentMatchResult; } else { var match = currentMatchResult.CompareTo(bestMatchResult.Value, filterText); if (match > 0) { moreThanOneMatchWithSamePriority = false; bestMatchResult = currentMatchResult; } else if (match == 0) { moreThanOneMatchWithSamePriority = true; } } } int index; bool hardSelect; // If we had a matching item, then pick the best of the matching items and // choose that one to be hard selected. If we had no actual matching items // (which can happen if the user deletes down to a single character and we // include everything), then we just soft select the first item. if (bestMatchResult != null) { // Only hard select this result if it's a prefix match // We need to do this so that // * deleting and retyping a dot in a member access does not change the // text that originally appeared before the dot // * deleting through a word from the end keeps that word selected // This also preserves the behavior the VB had through Dev12. hardSelect = !hasSuggestedItemOptions && bestMatchResult.Value.EditorCompletionItem.FilterText.StartsWith(filterText, StringComparison.CurrentCultureIgnoreCase); index = matchResults.IndexOf(bestMatchResult.Value); } else { index = 0; hardSelect = false; } return new FilteredCompletionModel( GetHighlightedList(matchResults, filterText, highlightMatchingSpans, completionHelper), index, filters, hardSelect ? UpdateSelectionHint.Selected : UpdateSelectionHint.SoftSelected, centerSelection: true, uniqueItem: moreThanOneMatchWithSamePriority ? null : bestMatchResult.GetValueOrDefault().EditorCompletionItem); } private static ImmutableArray<CompletionItemWithHighlight> GetHighlightedList( List<MatchResult<VSCompletionItem>> matchResults, string filterText, bool highlightMatchingPortions, CompletionHelper completionHelper) { return matchResults.SelectAsArray(matchResult => { var highlightedSpans = GetHighlightedSpans(matchResult, completionHelper, filterText, highlightMatchingPortions); return new CompletionItemWithHighlight(matchResult.EditorCompletionItem, highlightedSpans); }); static ImmutableArray<Span> GetHighlightedSpans( MatchResult<VSCompletionItem> matchResult, CompletionHelper completionHelper, string filterText, bool highlightMatchingPortions) { if (highlightMatchingPortions) { if (matchResult.RoslynCompletionItem.HasDifferentFilterText) { // The PatternMatch in MatchResult is calculated based on Roslyn item's FilterText, // which can be used to calculate highlighted span for VSCompletion item's DisplayText w/o doing the matching again. // However, if the Roslyn item's FilterText is different from its DisplayText, // we need to do the match against the display text of the VS item directly to get the highlighted spans. return completionHelper.GetHighlightedSpans( matchResult.EditorCompletionItem.DisplayText, filterText, CultureInfo.CurrentCulture).SelectAsArray(s => s.ToSpan()); } var patternMatch = matchResult.PatternMatch; if (patternMatch.HasValue) { // Since VS item's display text is created as Prefix + DisplayText + Suffix, // we can calculate the highlighted span by adding an offset that is the length of the Prefix. return patternMatch.Value.MatchedSpans.SelectAsArray(s_highlightSpanGetter, matchResult.RoslynCompletionItem); } } // If there's no match for Roslyn item's filter text which is identical to its display text, // then we can safely assume there'd be no matching to VS item's display text. return ImmutableArray<Span>.Empty; } } private static FilteredCompletionModel? HandleAllItemsFilteredOut( CompletionTriggerReason triggerReason, ImmutableArray<CompletionFilterWithState> filters, CompletionRules completionRules) { if (triggerReason == CompletionTriggerReason.Insertion) { // If the user was just typing, and the list went to empty *and* this is a // language that wants to dismiss on empty, then just return a null model // to stop the completion session. if (completionRules.DismissIfEmpty) { return null; } } // If the user has turned on some filtering states, and we filtered down to // nothing, then we do want the UI to show that to them. That way the user // can turn off filters they don't want and get the right set of items. // If we are going to filter everything out, then just preserve the existing // model (and all the previously filtered items), but switch over to soft // selection. var selection = UpdateSelectionHint.SoftSelected; return new FilteredCompletionModel( ImmutableArray<CompletionItemWithHighlight>.Empty, selectedItemIndex: 0, filters, selection, centerSelection: true, uniqueItem: null); } private static ImmutableArray<CompletionFilterWithState> GetUpdatedFilters( List<MatchResult<VSCompletionItem>> filteredList, ImmutableArray<CompletionFilterWithState> filters) { // See which filters might be enabled based on the typed code using var _ = PooledHashSet<CompletionFilter>.GetInstance(out var textFilteredFilters); textFilteredFilters.AddRange(filteredList.SelectMany(n => n.EditorCompletionItem.Filters)); // When no items are available for a given filter, it becomes unavailable. // Expanders always appear available as long as it's presented. return filters.SelectAsArray(n => n.WithAvailability(n.Filter is CompletionExpander ? true : textFilteredFilters.Contains(n.Filter))); } /// <summary> /// Given multiple possible chosen completion items, pick the one that has the /// best MRU index. /// </summary> private static RoslynCompletionItem GetBestCompletionItemBasedOnMRU( ImmutableArray<RoslynCompletionItem> chosenItems, ImmutableArray<string> recentItems) { // Try to find the chosen item has been most recently used. var bestItem = chosenItems.First(); for (int i = 0, n = chosenItems.Length; i < n; i++) { var chosenItem = chosenItems[i]; var mruIndex1 = GetRecentItemIndex(recentItems, bestItem); var mruIndex2 = GetRecentItemIndex(recentItems, chosenItem); if ((mruIndex2 < mruIndex1) || (mruIndex2 == mruIndex1 && !bestItem.IsPreferredItem() && chosenItem.IsPreferredItem())) { bestItem = chosenItem; } } // If our best item appeared in the MRU list, use it if (GetRecentItemIndex(recentItems, bestItem) <= 0) { return bestItem; } // Otherwise use the chosen item that has the highest // matchPriority. for (int i = 1, n = chosenItems.Length; i < n; i++) { var chosenItem = chosenItems[i]; var bestItemPriority = bestItem.Rules.MatchPriority; var currentItemPriority = chosenItem.Rules.MatchPriority; if ((currentItemPriority > bestItemPriority) || ((currentItemPriority == bestItemPriority) && !bestItem.IsPreferredItem() && chosenItem.IsPreferredItem())) { bestItem = chosenItem; } } return bestItem; } private static int GetRecentItemIndex(ImmutableArray<string> recentItems, RoslynCompletionItem item) { var index = recentItems.IndexOf(item.FilterText); return -index; } private static RoslynCompletionItem GetOrAddRoslynCompletionItem(VSCompletionItem vsItem) { if (!vsItem.Properties.TryGetProperty(CompletionSource.RoslynItem, out RoslynCompletionItem roslynItem)) { roslynItem = RoslynCompletionItem.Create( displayText: vsItem.DisplayText, filterText: vsItem.FilterText, sortText: vsItem.SortText, displayTextSuffix: vsItem.Suffix); vsItem.Properties.AddProperty(CompletionSource.RoslynItem, roslynItem); } return roslynItem; } private static bool TryCreateMatchResult( CompletionHelper completionHelper, VSCompletionItem item, string filterText, CompletionTriggerKind initialTriggerKind, CompletionFilterReason filterReason, ImmutableArray<string> recentItems, bool highlightMatchingPortions, int currentIndex, out MatchResult<VSCompletionItem> matchResult) { var roslynItem = GetOrAddRoslynCompletionItem(item); return CompletionHelper.TryCreateMatchResult(completionHelper, roslynItem, item, filterText, initialTriggerKind, filterReason, recentItems, highlightMatchingPortions, currentIndex, out matchResult); } // PERF: Create a singleton to avoid lambda allocation on hot path private static readonly Func<TextSpan, RoslynCompletionItem, Span> s_highlightSpanGetter = (span, item) => span.MoveTo(item.DisplayTextPrefix?.Length ?? 0).ToSpan(); private static bool IsHardSelection( string filterText, RoslynCompletionItem item, bool matchedFilterText, bool useSuggestionMode) { if (item == null || useSuggestionMode) { return false; } // We don't have a builder and we have a best match. Normally this will be hard // selected, except for a few cases. Specifically, if no filter text has been // provided, and this is not a preselect match then we will soft select it. This // happens when the completion list comes up implicitly and there is something in // the MRU list. In this case we do want to select it, but not with a hard // selection. Otherwise you can end up with the following problem: // // dim i as integer =<space> // // Completion will comes up after = with 'integer' selected (Because of MRU). We do // not want 'space' to commit this. // If all that has been typed is punctuation, then don't hard select anything. // It's possible the user is just typing language punctuation and selecting // anything in the list will interfere. We only allow this if the filter text // exactly matches something in the list already. if (filterText.Length > 0 && IsAllPunctuation(filterText) && filterText != item.DisplayText) { return false; } // If the user hasn't actually typed anything, then don't hard select any item. // The only exception to this is if the completion provider has requested the // item be preselected. if (filterText.Length == 0) { // Item didn't want to be hard selected with no filter text. // So definitely soft select it. if (item.Rules.SelectionBehavior != CompletionItemSelectionBehavior.HardSelection) { return false; } // Item did not ask to be preselected. So definitely soft select it. if (item.Rules.MatchPriority == MatchPriority.Default) { return false; } } // The user typed something, or the item asked to be preselected. In // either case, don't soft select this. Debug.Assert(filterText.Length > 0 || item.Rules.MatchPriority != MatchPriority.Default); // If the user moved the caret left after they started typing, the 'best' match may not match at all // against the full text span that this item would be replacing. if (!matchedFilterText) { return false; } // There was either filter text, or this was a preselect match. In either case, we // can hard select this. return true; } private static bool IsAllPunctuation(string filterText) { foreach (var ch in filterText) { if (!char.IsPunctuation(ch)) { return false; } } return true; } /// <summary> /// A potential filter character is something that can filter a completion lists and is /// *guaranteed* to not be a commit character. /// </summary> private static bool IsPotentialFilterCharacter(char c) { // TODO(cyrusn): Actually use the right Unicode categories here. return char.IsLetter(c) || char.IsNumber(c) || c == '_'; } } }
// Licensed to the .NET Foundation under one or more 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.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.PatternMatching; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; using RoslynCompletionItem = Microsoft.CodeAnalysis.Completion.CompletionItem; using VSCompletionItem = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data.CompletionItem; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion { internal class ItemManager : IAsyncCompletionItemManager { /// <summary> /// Used for filtering non-Roslyn data only. /// </summary> private readonly CompletionHelper _defaultCompletionHelper; private readonly RecentItemsManager _recentItemsManager; /// <summary> /// For telemetry. /// </summary> private readonly object _targetTypeCompletionFilterChosenMarker = new(); internal ItemManager(RecentItemsManager recentItemsManager) { // Let us make the completion Helper used for non-Roslyn items case-sensitive. // We can change this if get requests from partner teams. _defaultCompletionHelper = new CompletionHelper(isCaseSensitive: true); _recentItemsManager = recentItemsManager; } public Task<ImmutableArray<VSCompletionItem>> SortCompletionListAsync( IAsyncCompletionSession session, AsyncCompletionSessionInitialDataSnapshot data, CancellationToken cancellationToken) { if (session.TextView.Properties.TryGetProperty(CompletionSource.TargetTypeFilterExperimentEnabled, out bool isTargetTypeFilterEnabled) && isTargetTypeFilterEnabled) { AsyncCompletionLogger.LogSessionHasTargetTypeFilterEnabled(); // This method is called exactly once, so use the opportunity to set a baseline for telemetry. if (data.InitialList.Any(i => i.Filters.Any(f => f.DisplayText == FeaturesResources.Target_type_matches))) { AsyncCompletionLogger.LogSessionContainsTargetTypeFilter(); } } if (session.TextView.Properties.TryGetProperty(CompletionSource.TypeImportCompletionEnabled, out bool isTypeImportCompletionEnabled) && isTypeImportCompletionEnabled) { AsyncCompletionLogger.LogSessionWithTypeImportCompletionEnabled(); } // Sort by default comparer of Roslyn CompletionItem var sortedItems = data.InitialList.OrderBy(GetOrAddRoslynCompletionItem).ToImmutableArray(); return Task.FromResult(sortedItems); } public Task<FilteredCompletionModel?> UpdateCompletionListAsync( IAsyncCompletionSession session, AsyncCompletionSessionDataSnapshot data, CancellationToken cancellationToken) => Task.FromResult(UpdateCompletionList(session, data, cancellationToken)); // We might need to handle large amount of items with import completion enabled, // so use a dedicated pool to minimize/avoid array allocations (especially in LOH) // Set the size of pool to 1 because we don't expect UpdateCompletionListAsync to be // called concurrently, which essentially makes the pooled list a singleton, // but we still use ObjectPool for concurrency handling just to be robust. private static readonly ObjectPool<List<MatchResult<VSCompletionItem>>> s_listOfMatchResultPool = new(factory: () => new(), size: 1); private FilteredCompletionModel? UpdateCompletionList( IAsyncCompletionSession session, AsyncCompletionSessionDataSnapshot data, CancellationToken cancellationToken) { if (!session.Properties.TryGetProperty(CompletionSource.HasSuggestionItemOptions, out bool hasSuggestedItemOptions)) { // This is the scenario when the session is created out of Roslyn, in some other provider, e.g. in Debugger. // For now, the default hasSuggestedItemOptions is false. hasSuggestedItemOptions = false; } hasSuggestedItemOptions |= data.DisplaySuggestionItem; var filterText = session.ApplicableToSpan.GetText(data.Snapshot); var reason = data.Trigger.Reason; var initialRoslynTriggerKind = Helpers.GetRoslynTriggerKind(data.InitialTrigger); // Check if the user is typing a number. If so, only proceed if it's a number // directly after a <dot>. That's because it is actually reasonable for completion // to be brought up after a <dot> and for the user to want to filter completion // items based on a number that exists in the name of the item. However, when // we are not after a dot (i.e. we're being brought up after <space> is typed) // then we don't want to filter things. Consider the user writing: // // dim i =<space> // // We'll bring up the completion list here (as VB has completion on <space>). // If the user then types '3', we don't want to match against Int32. if (filterText.Length > 0 && char.IsNumber(filterText[0])) { if (!IsAfterDot(data.Snapshot, session.ApplicableToSpan)) { // Dismiss the session. return null; } } // We need to filter if // 1. a non-empty strict subset of filters are selected // 2. a non-empty set of expanders are unselected var nonExpanderFilterStates = data.SelectedFilters.WhereAsArray(f => !(f.Filter is CompletionExpander)); var selectedNonExpanderFilters = nonExpanderFilterStates.SelectAsArray(f => f.IsSelected, f => f.Filter); var needToFilter = selectedNonExpanderFilters.Length > 0 && selectedNonExpanderFilters.Length < nonExpanderFilterStates.Length; var unselectedExpanders = data.SelectedFilters.SelectAsArray(f => !f.IsSelected && f.Filter is CompletionExpander, f => f.Filter); var needToFilterExpanded = unselectedExpanders.Length > 0; if (session.TextView.Properties.TryGetProperty(CompletionSource.TargetTypeFilterExperimentEnabled, out bool isExperimentEnabled) && isExperimentEnabled) { // Telemetry: Want to know % of sessions with the "Target type matches" filter where that filter is actually enabled if (needToFilter && !session.Properties.ContainsProperty(_targetTypeCompletionFilterChosenMarker) && selectedNonExpanderFilters.Any(f => f.DisplayText == FeaturesResources.Target_type_matches)) { AsyncCompletionLogger.LogTargetTypeFilterChosenInSession(); // Make sure we only record one enabling of the filter per session session.Properties.AddProperty(_targetTypeCompletionFilterChosenMarker, _targetTypeCompletionFilterChosenMarker); } } var filterReason = Helpers.GetFilterReason(data.Trigger); // We prefer using the original snapshot, which should always be available from items provided by Roslyn's CompletionSource. // Only use data.Snapshot in the theoretically possible but rare case when all items we are handling are from some non-Roslyn CompletionSource. var snapshotForDocument = TryGetInitialTriggerLocation(data, out var intialTriggerLocation) ? intialTriggerLocation.Snapshot : data.Snapshot; var document = snapshotForDocument?.TextBuffer.AsTextContainer().GetOpenDocumentInCurrentContext(); var completionService = document?.GetLanguageService<CompletionService>(); var completionRules = completionService?.GetRules() ?? CompletionRules.Default; var completionHelper = document != null ? CompletionHelper.GetHelper(document) : _defaultCompletionHelper; // DismissIfLastCharacterDeleted should be applied only when started with Insertion, and then Deleted all characters typed. // This conforms with the original VS 2010 behavior. if (initialRoslynTriggerKind == CompletionTriggerKind.Insertion && data.Trigger.Reason == CompletionTriggerReason.Backspace && completionRules.DismissIfLastCharacterDeleted && session.ApplicableToSpan.GetText(data.Snapshot).Length == 0) { // Dismiss the session return null; } var options = document?.Project.Solution.Options; var highlightMatchingPortions = options?.GetOption(CompletionOptions.HighlightMatchingPortionsOfCompletionListItems, document?.Project.Language) ?? false; // Nothing to highlight if user hasn't typed anything yet. highlightMatchingPortions = highlightMatchingPortions && filterText.Length > 0; // Use a monotonically increasing integer to keep track the original alphabetical order of each item. var currentIndex = 0; var initialListOfItemsToBeIncluded = s_listOfMatchResultPool.Allocate(); try { // Filter items based on the selected filters and matching. foreach (var item in data.InitialSortedList) { cancellationToken.ThrowIfCancellationRequested(); if (needToFilter && ShouldBeFilteredOutOfCompletionList(item, selectedNonExpanderFilters)) { continue; } if (needToFilterExpanded && ShouldBeFilteredOutOfExpandedCompletionList(item, unselectedExpanders)) { continue; } if (TryCreateMatchResult( completionHelper, item, filterText, initialRoslynTriggerKind, filterReason, _recentItemsManager.RecentItems, highlightMatchingPortions: highlightMatchingPortions, currentIndex, out var matchResult)) { initialListOfItemsToBeIncluded.Add(matchResult); currentIndex++; } } if (initialListOfItemsToBeIncluded.Count == 0) { return HandleAllItemsFilteredOut(reason, data.SelectedFilters, completionRules); } // Sort the items by pattern matching results. // Note that we want to preserve the original alphabetical order for items with same pattern match score, // but `List<T>.Sort` isn't stable. Therefore we have to add a monotonically increasing integer // to `MatchResult` to achieve this. initialListOfItemsToBeIncluded.Sort(MatchResult<VSCompletionItem>.SortingComparer); var showCompletionItemFilters = options?.GetOption(CompletionOptions.ShowCompletionItemFilters, document?.Project.Language) ?? true; var updatedFilters = showCompletionItemFilters ? GetUpdatedFilters(initialListOfItemsToBeIncluded, data.SelectedFilters) : ImmutableArray<CompletionFilterWithState>.Empty; // If this was deletion, then we control the entire behavior of deletion ourselves. if (initialRoslynTriggerKind == CompletionTriggerKind.Deletion) { return HandleDeletionTrigger(reason, initialListOfItemsToBeIncluded, filterText, updatedFilters, hasSuggestedItemOptions, highlightMatchingPortions, completionHelper); } Func<ImmutableArray<(RoslynCompletionItem, PatternMatch?)>, string, ImmutableArray<RoslynCompletionItem>> filterMethod; if (completionService == null) { filterMethod = (itemsWithPatternMatches, text) => CompletionService.FilterItems(completionHelper, itemsWithPatternMatches); } else { filterMethod = (itemsWithPatternMatches, text) => completionService.FilterItems(document, itemsWithPatternMatches, text); } return HandleNormalFiltering( filterMethod, filterText, updatedFilters, filterReason, data.Trigger.Character, initialListOfItemsToBeIncluded, hasSuggestedItemOptions, highlightMatchingPortions, completionHelper); } finally { // Don't call ClearAndFree, which resets the capacity to a default value. initialListOfItemsToBeIncluded.Clear(); s_listOfMatchResultPool.Free(initialListOfItemsToBeIncluded); } static bool TryGetInitialTriggerLocation(AsyncCompletionSessionDataSnapshot data, out SnapshotPoint intialTriggerLocation) { var firstItem = data.InitialSortedList.FirstOrDefault(static item => item.Properties.ContainsProperty(CompletionSource.TriggerLocation)); if (firstItem != null) { return firstItem.Properties.TryGetProperty(CompletionSource.TriggerLocation, out intialTriggerLocation); } intialTriggerLocation = default; return false; } static bool ShouldBeFilteredOutOfCompletionList(VSCompletionItem item, ImmutableArray<CompletionFilter> activeNonExpanderFilters) { if (item.Filters.Any(filter => activeNonExpanderFilters.Contains(filter))) { return false; } return true; } static bool ShouldBeFilteredOutOfExpandedCompletionList(VSCompletionItem item, ImmutableArray<CompletionFilter> unselectedExpanders) { var associatedWithUnselectedExpander = false; foreach (var itemFilter in item.Filters) { if (itemFilter is CompletionExpander) { if (!unselectedExpanders.Contains(itemFilter)) { // If any of the associated expander is selected, the item should be included in the expanded list. return false; } associatedWithUnselectedExpander = true; } } // at this point, the item either: // 1. has no expander filter, therefore should be included // 2. or, all associated expanders are unselected, therefore should be excluded return associatedWithUnselectedExpander; } } private static bool IsAfterDot(ITextSnapshot snapshot, ITrackingSpan applicableToSpan) { var position = applicableToSpan.GetStartPoint(snapshot).Position; return position > 0 && snapshot[position - 1] == '.'; } private FilteredCompletionModel? HandleNormalFiltering( Func<ImmutableArray<(RoslynCompletionItem, PatternMatch?)>, string, ImmutableArray<RoslynCompletionItem>> filterMethod, string filterText, ImmutableArray<CompletionFilterWithState> filters, CompletionFilterReason filterReason, char typeChar, List<MatchResult<VSCompletionItem>> itemsInList, bool hasSuggestedItemOptions, bool highlightMatchingPortions, CompletionHelper completionHelper) { // Not deletion. Defer to the language to decide which item it thinks best // matches the text typed so far. // Ask the language to determine which of the *matched* items it wants to select. var matchingItems = itemsInList.Where(r => r.MatchedFilterText) .SelectAsArray(t => (t.RoslynCompletionItem, t.PatternMatch)); var chosenItems = filterMethod(matchingItems, filterText); int selectedItemIndex; VSCompletionItem? uniqueItem = null; MatchResult<VSCompletionItem> bestOrFirstMatchResult; if (chosenItems.Length == 0) { // We do not have matches: pick the one with longest common prefix or the first item from the list. selectedItemIndex = 0; bestOrFirstMatchResult = itemsInList[0]; var longestCommonPrefixLength = bestOrFirstMatchResult.RoslynCompletionItem.FilterText.GetCaseInsensitivePrefixLength(filterText); for (var i = 1; i < itemsInList.Count; ++i) { var item = itemsInList[i]; var commonPrefixLength = item.RoslynCompletionItem.FilterText.GetCaseInsensitivePrefixLength(filterText); if (commonPrefixLength > longestCommonPrefixLength) { selectedItemIndex = i; bestOrFirstMatchResult = item; longestCommonPrefixLength = commonPrefixLength; } } } else { var recentItems = _recentItemsManager.RecentItems; // Of the items the service returned, pick the one most recently committed var bestItem = GetBestCompletionItemBasedOnMRU(chosenItems, recentItems); // Determine if we should consider this item 'unique' or not. A unique item // will be automatically committed if the user hits the 'invoke completion' // without bringing up the completion list. An item is unique if it was the // only item to match the text typed so far, and there was at least some text // typed. i.e. if we have "Console.$$" we don't want to commit something // like "WriteLine" since no filter text has actually been provided. However, // if "Console.WriteL$$" is typed, then we do want "WriteLine" to be committed. selectedItemIndex = itemsInList.IndexOf(i => Equals(i.RoslynCompletionItem, bestItem)); bestOrFirstMatchResult = itemsInList[selectedItemIndex]; var deduplicatedListCount = matchingItems.Count(r => !r.RoslynCompletionItem.IsPreferredItem()); if (deduplicatedListCount == 1 && filterText.Length > 0) { uniqueItem = itemsInList[selectedItemIndex].EditorCompletionItem; } } // Check that it is a filter symbol. We can be called for a non-filter symbol. // If inserting a non-filter character (neither IsPotentialFilterCharacter, nor Helpers.IsFilterCharacter), we should dismiss completion // except cases where this is the first symbol typed for the completion session (string.IsNullOrEmpty(filterText) or string.Equals(filterText, typeChar.ToString(), StringComparison.OrdinalIgnoreCase)). // In the latter case, we should keep the completion because it was confirmed just before in InitializeCompletion. if (filterReason == CompletionFilterReason.Insertion && !string.IsNullOrEmpty(filterText) && !string.Equals(filterText, typeChar.ToString(), StringComparison.OrdinalIgnoreCase) && !IsPotentialFilterCharacter(typeChar) && !Helpers.IsFilterCharacter(bestOrFirstMatchResult.RoslynCompletionItem, typeChar, filterText)) { return null; } var isHardSelection = IsHardSelection( filterText, bestOrFirstMatchResult.RoslynCompletionItem, bestOrFirstMatchResult.MatchedFilterText, hasSuggestedItemOptions); var updateSelectionHint = isHardSelection ? UpdateSelectionHint.Selected : UpdateSelectionHint.SoftSelected; return new FilteredCompletionModel( GetHighlightedList(itemsInList, filterText, highlightMatchingPortions, completionHelper), selectedItemIndex, filters, updateSelectionHint, centerSelection: true, uniqueItem); } private static FilteredCompletionModel? HandleDeletionTrigger( CompletionTriggerReason filterTriggerKind, List<MatchResult<VSCompletionItem>> matchResults, string filterText, ImmutableArray<CompletionFilterWithState> filters, bool hasSuggestedItemOptions, bool highlightMatchingSpans, CompletionHelper completionHelper) { var matchingItems = matchResults.Where(r => r.MatchedFilterText); if (filterTriggerKind == CompletionTriggerReason.Insertion && !matchingItems.Any()) { // The user has typed something, but nothing in the actual list matched what // they were typing. In this case, we want to dismiss completion entirely. // The thought process is as follows: we aggressively brought up completion // to help them when they typed delete (in case they wanted to pick another // item). However, they're typing something that doesn't seem to match at all // The completion list is just distracting at this point. return null; } MatchResult<VSCompletionItem>? bestMatchResult = null; var moreThanOneMatchWithSamePriority = false; foreach (var currentMatchResult in matchingItems) { if (bestMatchResult == null) { // We had no best result yet, so this is now our best result. bestMatchResult = currentMatchResult; } else { var match = currentMatchResult.CompareTo(bestMatchResult.Value, filterText); if (match > 0) { moreThanOneMatchWithSamePriority = false; bestMatchResult = currentMatchResult; } else if (match == 0) { moreThanOneMatchWithSamePriority = true; } } } int index; bool hardSelect; // If we had a matching item, then pick the best of the matching items and // choose that one to be hard selected. If we had no actual matching items // (which can happen if the user deletes down to a single character and we // include everything), then we just soft select the first item. if (bestMatchResult != null) { // Only hard select this result if it's a prefix match // We need to do this so that // * deleting and retyping a dot in a member access does not change the // text that originally appeared before the dot // * deleting through a word from the end keeps that word selected // This also preserves the behavior the VB had through Dev12. hardSelect = !hasSuggestedItemOptions && bestMatchResult.Value.EditorCompletionItem.FilterText.StartsWith(filterText, StringComparison.CurrentCultureIgnoreCase); index = matchResults.IndexOf(bestMatchResult.Value); } else { index = 0; hardSelect = false; } return new FilteredCompletionModel( GetHighlightedList(matchResults, filterText, highlightMatchingSpans, completionHelper), index, filters, hardSelect ? UpdateSelectionHint.Selected : UpdateSelectionHint.SoftSelected, centerSelection: true, uniqueItem: moreThanOneMatchWithSamePriority ? null : bestMatchResult.GetValueOrDefault().EditorCompletionItem); } private static ImmutableArray<CompletionItemWithHighlight> GetHighlightedList( List<MatchResult<VSCompletionItem>> matchResults, string filterText, bool highlightMatchingPortions, CompletionHelper completionHelper) { return matchResults.SelectAsArray(matchResult => { var highlightedSpans = GetHighlightedSpans(matchResult, completionHelper, filterText, highlightMatchingPortions); return new CompletionItemWithHighlight(matchResult.EditorCompletionItem, highlightedSpans); }); static ImmutableArray<Span> GetHighlightedSpans( MatchResult<VSCompletionItem> matchResult, CompletionHelper completionHelper, string filterText, bool highlightMatchingPortions) { if (highlightMatchingPortions) { if (matchResult.RoslynCompletionItem.HasDifferentFilterText) { // The PatternMatch in MatchResult is calculated based on Roslyn item's FilterText, // which can be used to calculate highlighted span for VSCompletion item's DisplayText w/o doing the matching again. // However, if the Roslyn item's FilterText is different from its DisplayText, // we need to do the match against the display text of the VS item directly to get the highlighted spans. return completionHelper.GetHighlightedSpans( matchResult.EditorCompletionItem.DisplayText, filterText, CultureInfo.CurrentCulture).SelectAsArray(s => s.ToSpan()); } var patternMatch = matchResult.PatternMatch; if (patternMatch.HasValue) { // Since VS item's display text is created as Prefix + DisplayText + Suffix, // we can calculate the highlighted span by adding an offset that is the length of the Prefix. return patternMatch.Value.MatchedSpans.SelectAsArray(s_highlightSpanGetter, matchResult.RoslynCompletionItem); } } // If there's no match for Roslyn item's filter text which is identical to its display text, // then we can safely assume there'd be no matching to VS item's display text. return ImmutableArray<Span>.Empty; } } private static FilteredCompletionModel? HandleAllItemsFilteredOut( CompletionTriggerReason triggerReason, ImmutableArray<CompletionFilterWithState> filters, CompletionRules completionRules) { if (triggerReason == CompletionTriggerReason.Insertion) { // If the user was just typing, and the list went to empty *and* this is a // language that wants to dismiss on empty, then just return a null model // to stop the completion session. if (completionRules.DismissIfEmpty) { return null; } } // If the user has turned on some filtering states, and we filtered down to // nothing, then we do want the UI to show that to them. That way the user // can turn off filters they don't want and get the right set of items. // If we are going to filter everything out, then just preserve the existing // model (and all the previously filtered items), but switch over to soft // selection. var selection = UpdateSelectionHint.SoftSelected; return new FilteredCompletionModel( ImmutableArray<CompletionItemWithHighlight>.Empty, selectedItemIndex: 0, filters, selection, centerSelection: true, uniqueItem: null); } private static ImmutableArray<CompletionFilterWithState> GetUpdatedFilters( List<MatchResult<VSCompletionItem>> filteredList, ImmutableArray<CompletionFilterWithState> filters) { // See which filters might be enabled based on the typed code using var _ = PooledHashSet<CompletionFilter>.GetInstance(out var textFilteredFilters); textFilteredFilters.AddRange(filteredList.SelectMany(n => n.EditorCompletionItem.Filters)); // When no items are available for a given filter, it becomes unavailable. // Expanders always appear available as long as it's presented. return filters.SelectAsArray(n => n.WithAvailability(n.Filter is CompletionExpander ? true : textFilteredFilters.Contains(n.Filter))); } /// <summary> /// Given multiple possible chosen completion items, pick the one that has the /// best MRU index. /// </summary> private static RoslynCompletionItem GetBestCompletionItemBasedOnMRU( ImmutableArray<RoslynCompletionItem> chosenItems, ImmutableArray<string> recentItems) { // Try to find the chosen item has been most recently used. var bestItem = chosenItems.First(); for (int i = 0, n = chosenItems.Length; i < n; i++) { var chosenItem = chosenItems[i]; var mruIndex1 = GetRecentItemIndex(recentItems, bestItem); var mruIndex2 = GetRecentItemIndex(recentItems, chosenItem); if ((mruIndex2 < mruIndex1) || (mruIndex2 == mruIndex1 && !bestItem.IsPreferredItem() && chosenItem.IsPreferredItem())) { bestItem = chosenItem; } } // If our best item appeared in the MRU list, use it if (GetRecentItemIndex(recentItems, bestItem) <= 0) { return bestItem; } // Otherwise use the chosen item that has the highest // matchPriority. for (int i = 1, n = chosenItems.Length; i < n; i++) { var chosenItem = chosenItems[i]; var bestItemPriority = bestItem.Rules.MatchPriority; var currentItemPriority = chosenItem.Rules.MatchPriority; if ((currentItemPriority > bestItemPriority) || ((currentItemPriority == bestItemPriority) && !bestItem.IsPreferredItem() && chosenItem.IsPreferredItem())) { bestItem = chosenItem; } } return bestItem; } private static int GetRecentItemIndex(ImmutableArray<string> recentItems, RoslynCompletionItem item) { var index = recentItems.IndexOf(item.FilterText); return -index; } private static RoslynCompletionItem GetOrAddRoslynCompletionItem(VSCompletionItem vsItem) { if (!vsItem.Properties.TryGetProperty(CompletionSource.RoslynItem, out RoslynCompletionItem roslynItem)) { roslynItem = RoslynCompletionItem.Create( displayText: vsItem.DisplayText, filterText: vsItem.FilterText, sortText: vsItem.SortText, displayTextSuffix: vsItem.Suffix); vsItem.Properties.AddProperty(CompletionSource.RoslynItem, roslynItem); } return roslynItem; } private static bool TryCreateMatchResult( CompletionHelper completionHelper, VSCompletionItem item, string filterText, CompletionTriggerKind initialTriggerKind, CompletionFilterReason filterReason, ImmutableArray<string> recentItems, bool highlightMatchingPortions, int currentIndex, out MatchResult<VSCompletionItem> matchResult) { var roslynItem = GetOrAddRoslynCompletionItem(item); return CompletionHelper.TryCreateMatchResult(completionHelper, roslynItem, item, filterText, initialTriggerKind, filterReason, recentItems, highlightMatchingPortions, currentIndex, out matchResult); } // PERF: Create a singleton to avoid lambda allocation on hot path private static readonly Func<TextSpan, RoslynCompletionItem, Span> s_highlightSpanGetter = (span, item) => span.MoveTo(item.DisplayTextPrefix?.Length ?? 0).ToSpan(); private static bool IsHardSelection( string filterText, RoslynCompletionItem item, bool matchedFilterText, bool useSuggestionMode) { if (item == null || useSuggestionMode) { return false; } // We don't have a builder and we have a best match. Normally this will be hard // selected, except for a few cases. Specifically, if no filter text has been // provided, and this is not a preselect match then we will soft select it. This // happens when the completion list comes up implicitly and there is something in // the MRU list. In this case we do want to select it, but not with a hard // selection. Otherwise you can end up with the following problem: // // dim i as integer =<space> // // Completion will comes up after = with 'integer' selected (Because of MRU). We do // not want 'space' to commit this. // If all that has been typed is punctuation, then don't hard select anything. // It's possible the user is just typing language punctuation and selecting // anything in the list will interfere. We only allow this if the filter text // exactly matches something in the list already. if (filterText.Length > 0 && IsAllPunctuation(filterText) && filterText != item.DisplayText) { return false; } // If the user hasn't actually typed anything, then don't hard select any item. // The only exception to this is if the completion provider has requested the // item be preselected. if (filterText.Length == 0) { // Item didn't want to be hard selected with no filter text. // So definitely soft select it. if (item.Rules.SelectionBehavior != CompletionItemSelectionBehavior.HardSelection) { return false; } // Item did not ask to be preselected. So definitely soft select it. if (item.Rules.MatchPriority == MatchPriority.Default) { return false; } } // The user typed something, or the item asked to be preselected. In // either case, don't soft select this. Debug.Assert(filterText.Length > 0 || item.Rules.MatchPriority != MatchPriority.Default); // If the user moved the caret left after they started typing, the 'best' match may not match at all // against the full text span that this item would be replacing. if (!matchedFilterText) { return false; } // There was either filter text, or this was a preselect match. In either case, we // can hard select this. return true; } private static bool IsAllPunctuation(string filterText) { foreach (var ch in filterText) { if (!char.IsPunctuation(ch)) { return false; } } return true; } /// <summary> /// A potential filter character is something that can filter a completion lists and is /// *guaranteed* to not be a commit character. /// </summary> private static bool IsPotentialFilterCharacter(char c) { // TODO(cyrusn): Actually use the right Unicode categories here. return char.IsLetter(c) || char.IsNumber(c) || c == '_'; } } }
1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/UseExpressionBody/UseExpressionBodyForAccessorsAnalyzerTests.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.Tasks; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.UseExpressionBody; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody { using VerifyCS = CSharpCodeFixVerifier< UseExpressionBodyDiagnosticAnalyzer, UseExpressionBodyCodeFixProvider>; public class UseExpressionBodyForAccessorsTests { private static async Task TestWithUseExpressionBody(string code, string fixedCode, LanguageVersion version = LanguageVersion.CSharp8) { await new VerifyCS.Test { ReferenceAssemblies = version == LanguageVersion.CSharp9 ? ReferenceAssemblies.Net.Net50 : ReferenceAssemblies.Default, TestCode = code, FixedCode = fixedCode, LanguageVersion = version, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.WhenPossible }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.Never }, } }.RunAsync(); } private static async Task TestWithUseExpressionBodyIncludingPropertiesAndIndexers(string code, string fixedCode, LanguageVersion version = LanguageVersion.CSharp8) { await new VerifyCS.Test { ReferenceAssemblies = version == LanguageVersion.CSharp9 ? ReferenceAssemblies.Net.Net50 : ReferenceAssemblies.Default, TestCode = code, FixedCode = fixedCode, LanguageVersion = version, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.WhenPossible }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.WhenPossible }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.WhenPossible }, } }.RunAsync(); } private static async Task TestWithUseBlockBodyIncludingPropertiesAndIndexers(string code, string fixedCode, LanguageVersion version = LanguageVersion.CSharp8) { await new VerifyCS.Test { ReferenceAssemblies = version == LanguageVersion.CSharp9 ? ReferenceAssemblies.Net.Net50 : ReferenceAssemblies.Default, TestCode = code, FixedCode = fixedCode, LanguageVersion = version, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.Never }, } }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody1() { var code = @" class C { int Bar() { return 0; } int Goo { {|IDE0027:get { return Bar(); }|} } }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo { get => Bar(); } }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUpdatePropertyInsteadOfAccessor() { // TODO: Should this test move to properties tests? var code = @" class C { int Bar() { return 0; } {|IDE0025:int Goo { get { return Bar(); } }|} }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo => Bar(); }"; await TestWithUseExpressionBodyIncludingPropertiesAndIndexers(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOnIndexer1() { var code = @" class C { int Bar() { return 0; } int this[int i] { {|IDE0027:get { return Bar(); }|} } }"; var fixedCode = @" class C { int Bar() { return 0; } int this[int i] { get => Bar(); } }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUpdateIndexerIfIndexerAndAccessorCanBeUpdated() { // TODO: Should this test move to indexers tests? var code = @" class C { int Bar() { return 0; } {|IDE0026:int this[int i] { get { return Bar(); } }|} }"; var fixedCode = @" class C { int Bar() { return 0; } int this[int i] => Bar(); }"; await TestWithUseExpressionBodyIncludingPropertiesAndIndexers(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOnSetter1() { var code = @" class C { void Bar() { } int Goo { {|IDE0027:set { Bar(); }|} } }"; var fixedCode = @" class C { void Bar() { } int Goo { set => Bar(); } }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOnInit1() { var code = @"class C { int Goo { {|IDE0027:init { Bar(); }|} } int Bar() { return 0; } }"; var fixedCode = @"class C { int Goo { init => Bar(); } int Bar() { return 0; } }"; await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp9); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestMissingWithOnlySetter() { await VerifyCS.VerifyAnalyzerAsync(@" class C { void Bar() { } int Goo { set => Bar(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestMissingWithOnlyInit() { var code = @"class C { int Goo { init => Bar(); } int Bar() { return 0; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = code, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody3() { var code = @" using System; class C { int Goo { {|IDE0027:get { throw new NotImplementedException(); }|} } }"; var fixedCode = @" using System; class C { int Goo { get => throw new NotImplementedException(); } }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody4() { var code = @" using System; class C { int Goo { {|IDE0027:get { throw new NotImplementedException(); // comment }|} } }"; var fixedCode = @" using System; class C { int Goo { get => throw new NotImplementedException(); // comment } }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody1() { var code = @" class C { int Bar() { return 0; } int Goo { {|IDE0027:get => Bar();|} } }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo { get { return Bar(); } } }"; await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBodyForSetter1() { var code = @" class C { void Bar() { } int Goo { {|IDE0027:set => Bar();|} } }"; var fixedCode = @" class C { void Bar() { } int Goo { set { Bar(); } } }"; await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBodyForInit1() { var code = @"class C { int Goo { {|IDE0027:init => Bar();|} } int Bar() { return 0; } }"; var fixedCode = @"class C { int Goo { init { Bar(); } } int Bar() { return 0; } }"; await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode, LanguageVersion.CSharp9); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody3() { var code = @" using System; class C { int Goo { {|IDE0027:get => throw new NotImplementedException();|} } }"; var fixedCode = @" using System; class C { int Goo { get { throw new NotImplementedException(); } } }"; await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody4() { var code = @" using System; class C { int Goo { {|IDE0027:get => throw new NotImplementedException();|} // comment } }"; var fixedCode = @" using System; class C { int Goo { get { throw new NotImplementedException(); // comment } } }"; await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode); } [WorkItem(31308, "https://github.com/dotnet/roslyn/issues/31308")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody5() { var code = @" class C { C this[int index] { get => default; } }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.WhenOnSingleLine, NotificationOption2.None }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.WhenOnSingleLine, NotificationOption2.None }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.WhenOnSingleLine, NotificationOption2.None }, } }.RunAsync(); } [WorkItem(20350, "https://github.com/dotnet/roslyn/issues/20350")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestAccessorListFormatting() { var code = @" class C { int Bar() { return 0; } int Goo { {|IDE0027:get => Bar();|} } }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo { get { return Bar(); } } }"; await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode); } [WorkItem(20350, "https://github.com/dotnet/roslyn/issues/20350")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestAccessorListFormatting_FixAll() { var code = @" class C { int Bar() { return 0; } int Goo { {|IDE0027:get => Bar();|} {|IDE0027:set => Bar();|} } }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo { get { return Bar(); } set { Bar(); } } }"; var batchFixedCode = @" class C { int Bar() { return 0; } int Goo { get { return Bar(); } set { Bar(); } } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, BatchFixedCode = batchFixedCode, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.Never }, }, }.RunAsync(); } [WorkItem(20350, "https://github.com/dotnet/roslyn/issues/20350")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestAccessorListFormatting_FixAll2() { var code = @"class C { int Goo { {|IDE0027:get => Bar();|} {|IDE0027:init => Bar();|} } int Bar() { return 0; } }"; var fixedCode = @"class C { int Goo { get { return Bar(); } init { Bar(); } } int Bar() { return 0; } }"; var batchFixedCode = @"class C { int Goo { get { return Bar(); } init { Bar(); } } int Bar() { return 0; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = code, FixedCode = fixedCode, BatchFixedCode = batchFixedCode, LanguageVersion = LanguageVersion.CSharp9, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.Never }, } }.RunAsync(); } [WorkItem(20362, "https://github.com/dotnet/roslyn/issues/20362")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferToConvertToBlockEvenIfExpressionBodyPreferredIfPriorToCSharp7() { var code = @" using System; class C { int Goo { {|IDE0027:get {|CS8059:=> {|CS8059:throw new NotImplementedException()|}|};|} } }"; var fixedCode = @" using System; class C { int Goo { get { throw new NotImplementedException(); } } }"; await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp6); } [WorkItem(20362, "https://github.com/dotnet/roslyn/issues/20362")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferToConvertToBlockEvenIfExpressionBodyPreferredIfPriorToCSharp7_FixAll() { var code = @" using System; class C { int Goo { {|IDE0027:get {|CS8059:=> {|CS8059:throw new NotImplementedException()|}|};|} } int Bar { {|IDE0027:get {|CS8059:=> {|CS8059:throw new NotImplementedException()|}|};|} } }"; var fixedCode = @" using System; class C { int Goo { get { throw new NotImplementedException(); } } int Bar { get { throw new NotImplementedException(); } } }"; await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp6); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.UseExpressionBody; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody { using VerifyCS = CSharpCodeFixVerifier< UseExpressionBodyDiagnosticAnalyzer, UseExpressionBodyCodeFixProvider>; public class UseExpressionBodyForAccessorsTests { private static async Task TestWithUseExpressionBody(string code, string fixedCode, LanguageVersion version = LanguageVersion.CSharp8) { await new VerifyCS.Test { ReferenceAssemblies = version == LanguageVersion.CSharp9 ? ReferenceAssemblies.Net.Net50 : ReferenceAssemblies.Default, TestCode = code, FixedCode = fixedCode, LanguageVersion = version, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.WhenPossible }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.Never }, } }.RunAsync(); } private static async Task TestWithUseExpressionBodyIncludingPropertiesAndIndexers(string code, string fixedCode, LanguageVersion version = LanguageVersion.CSharp8) { await new VerifyCS.Test { ReferenceAssemblies = version == LanguageVersion.CSharp9 ? ReferenceAssemblies.Net.Net50 : ReferenceAssemblies.Default, TestCode = code, FixedCode = fixedCode, LanguageVersion = version, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.WhenPossible }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.WhenPossible }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.WhenPossible }, } }.RunAsync(); } private static async Task TestWithUseBlockBodyIncludingPropertiesAndIndexers(string code, string fixedCode, LanguageVersion version = LanguageVersion.CSharp8) { await new VerifyCS.Test { ReferenceAssemblies = version == LanguageVersion.CSharp9 ? ReferenceAssemblies.Net.Net50 : ReferenceAssemblies.Default, TestCode = code, FixedCode = fixedCode, LanguageVersion = version, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.Never }, } }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody1() { var code = @" class C { int Bar() { return 0; } int Goo { {|IDE0027:get { return Bar(); }|} } }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo { get => Bar(); } }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUpdatePropertyInsteadOfAccessor() { // TODO: Should this test move to properties tests? var code = @" class C { int Bar() { return 0; } {|IDE0025:int Goo { get { return Bar(); } }|} }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo => Bar(); }"; await TestWithUseExpressionBodyIncludingPropertiesAndIndexers(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOnIndexer1() { var code = @" class C { int Bar() { return 0; } int this[int i] { {|IDE0027:get { return Bar(); }|} } }"; var fixedCode = @" class C { int Bar() { return 0; } int this[int i] { get => Bar(); } }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUpdateIndexerIfIndexerAndAccessorCanBeUpdated() { // TODO: Should this test move to indexers tests? var code = @" class C { int Bar() { return 0; } {|IDE0026:int this[int i] { get { return Bar(); } }|} }"; var fixedCode = @" class C { int Bar() { return 0; } int this[int i] => Bar(); }"; await TestWithUseExpressionBodyIncludingPropertiesAndIndexers(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOnSetter1() { var code = @" class C { void Bar() { } int Goo { {|IDE0027:set { Bar(); }|} } }"; var fixedCode = @" class C { void Bar() { } int Goo { set => Bar(); } }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOnInit1() { var code = @"class C { int Goo { {|IDE0027:init { Bar(); }|} } int Bar() { return 0; } }"; var fixedCode = @"class C { int Goo { init => Bar(); } int Bar() { return 0; } }"; await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp9); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestMissingWithOnlySetter() { await VerifyCS.VerifyAnalyzerAsync(@" class C { void Bar() { } int Goo { set => Bar(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestMissingWithOnlyInit() { var code = @"class C { int Goo { init => Bar(); } int Bar() { return 0; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = code, LanguageVersion = LanguageVersion.CSharp9, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody3() { var code = @" using System; class C { int Goo { {|IDE0027:get { throw new NotImplementedException(); }|} } }"; var fixedCode = @" using System; class C { int Goo { get => throw new NotImplementedException(); } }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody4() { var code = @" using System; class C { int Goo { {|IDE0027:get { throw new NotImplementedException(); // comment }|} } }"; var fixedCode = @" using System; class C { int Goo { get => throw new NotImplementedException(); // comment } }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody1() { var code = @" class C { int Bar() { return 0; } int Goo { {|IDE0027:get => Bar();|} } }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo { get { return Bar(); } } }"; await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBodyForSetter1() { var code = @" class C { void Bar() { } int Goo { {|IDE0027:set => Bar();|} } }"; var fixedCode = @" class C { void Bar() { } int Goo { set { Bar(); } } }"; await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBodyForInit1() { var code = @"class C { int Goo { {|IDE0027:init => Bar();|} } int Bar() { return 0; } }"; var fixedCode = @"class C { int Goo { init { Bar(); } } int Bar() { return 0; } }"; await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode, LanguageVersion.CSharp9); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody3() { var code = @" using System; class C { int Goo { {|IDE0027:get => throw new NotImplementedException();|} } }"; var fixedCode = @" using System; class C { int Goo { get { throw new NotImplementedException(); } } }"; await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody4() { var code = @" using System; class C { int Goo { {|IDE0027:get => throw new NotImplementedException();|} // comment } }"; var fixedCode = @" using System; class C { int Goo { get { throw new NotImplementedException(); // comment } } }"; await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode); } [WorkItem(31308, "https://github.com/dotnet/roslyn/issues/31308")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody5() { var code = @" class C { C this[int index] { get => default; } }"; await new VerifyCS.Test { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.WhenOnSingleLine, NotificationOption2.None }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.WhenOnSingleLine, NotificationOption2.None }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.WhenOnSingleLine, NotificationOption2.None }, } }.RunAsync(); } [WorkItem(20350, "https://github.com/dotnet/roslyn/issues/20350")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestAccessorListFormatting() { var code = @" class C { int Bar() { return 0; } int Goo { {|IDE0027:get => Bar();|} } }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo { get { return Bar(); } } }"; await TestWithUseBlockBodyIncludingPropertiesAndIndexers(code, fixedCode); } [WorkItem(20350, "https://github.com/dotnet/roslyn/issues/20350")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestAccessorListFormatting_FixAll() { var code = @" class C { int Bar() { return 0; } int Goo { {|IDE0027:get => Bar();|} {|IDE0027:set => Bar();|} } }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo { get { return Bar(); } set { Bar(); } } }"; var batchFixedCode = @" class C { int Bar() { return 0; } int Goo { get { return Bar(); } set { Bar(); } } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, BatchFixedCode = batchFixedCode, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.Never }, }, }.RunAsync(); } [WorkItem(20350, "https://github.com/dotnet/roslyn/issues/20350")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestAccessorListFormatting_FixAll2() { var code = @"class C { int Goo { {|IDE0027:get => Bar();|} {|IDE0027:init => Bar();|} } int Bar() { return 0; } }"; var fixedCode = @"class C { int Goo { get { return Bar(); } init { Bar(); } } int Bar() { return 0; } }"; var batchFixedCode = @"class C { int Goo { get { return Bar(); } init { Bar(); } } int Bar() { return 0; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = code, FixedCode = fixedCode, BatchFixedCode = batchFixedCode, LanguageVersion = LanguageVersion.CSharp9, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.Never }, } }.RunAsync(); } [WorkItem(20362, "https://github.com/dotnet/roslyn/issues/20362")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferToConvertToBlockEvenIfExpressionBodyPreferredIfPriorToCSharp7() { var code = @" using System; class C { int Goo { {|IDE0027:get {|CS8059:=> {|CS8059:throw new NotImplementedException()|}|};|} } }"; var fixedCode = @" using System; class C { int Goo { get { throw new NotImplementedException(); } } }"; await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp6); } [WorkItem(20362, "https://github.com/dotnet/roslyn/issues/20362")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferToConvertToBlockEvenIfExpressionBodyPreferredIfPriorToCSharp7_FixAll() { var code = @" using System; class C { int Goo { {|IDE0027:get {|CS8059:=> {|CS8059:throw new NotImplementedException()|}|};|} } int Bar { {|IDE0027:get {|CS8059:=> {|CS8059:throw new NotImplementedException()|}|};|} } }"; var fixedCode = @" using System; class C { int Goo { get { throw new NotImplementedException(); } } int Bar { get { throw new NotImplementedException(); } } }"; await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp6); } } }
-1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/Symbols/AbstractTypeMap.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 Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Abstract base class for mutable and immutable type maps. /// </summary> internal abstract class AbstractTypeMap { /// <summary> /// Substitute for a type declaration. May use alpha renaming if the container is substituted. /// </summary> internal virtual NamedTypeSymbol SubstituteTypeDeclaration(NamedTypeSymbol previous) { Debug.Assert((object)previous.ConstructedFrom == (object)previous); NamedTypeSymbol newContainingType = SubstituteNamedType(previous.ContainingType); if ((object)newContainingType == null) { return previous; } return previous.OriginalDefinition.AsMember(newContainingType); } /// <summary> /// SubstType, but for NamedTypeSymbols only. This is used for concrete types, so no alpha substitution appears in the result. /// </summary> internal NamedTypeSymbol SubstituteNamedType(NamedTypeSymbol previous) { if (ReferenceEquals(previous, null)) return null; if (previous.IsUnboundGenericType) return previous; if (previous.IsAnonymousType) { ImmutableArray<TypeWithAnnotations> oldFieldTypes = AnonymousTypeManager.GetAnonymousTypePropertyTypesWithAnnotations(previous); ImmutableArray<TypeWithAnnotations> newFieldTypes = SubstituteTypes(oldFieldTypes); return (oldFieldTypes == newFieldTypes) ? previous : AnonymousTypeManager.ConstructAnonymousTypeSymbol(previous, newFieldTypes); } // TODO: we could construct the result's ConstructedFrom lazily by using a "deep" // construct operation here (as VB does), thereby avoiding alpha renaming in most cases. // Aleksey has shown that would reduce GC pressure if substitutions of deeply nested generics are common. NamedTypeSymbol oldConstructedFrom = previous.ConstructedFrom; NamedTypeSymbol newConstructedFrom = SubstituteTypeDeclaration(oldConstructedFrom); ImmutableArray<TypeWithAnnotations> oldTypeArguments = previous.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; bool changed = !ReferenceEquals(oldConstructedFrom, newConstructedFrom); var newTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(oldTypeArguments.Length); for (int i = 0; i < oldTypeArguments.Length; i++) { var oldArgument = oldTypeArguments[i]; var newArgument = oldArgument.SubstituteType(this); if (!changed && !oldArgument.IsSameAs(newArgument)) { changed = true; } newTypeArguments.Add(newArgument); } if (!changed) { newTypeArguments.Free(); return previous; } return newConstructedFrom.ConstructIfGeneric(newTypeArguments.ToImmutableAndFree()).WithTupleDataFrom(previous); } /// <summary> /// Perform the substitution on the given type. Each occurrence of the type parameter is /// replaced with its corresponding type argument from the map. /// </summary> /// <param name="previous">The type to be rewritten.</param> /// <returns>The type with type parameters replaced with the type arguments.</returns> internal TypeWithAnnotations SubstituteType(TypeSymbol previous) { if (ReferenceEquals(previous, null)) return default(TypeWithAnnotations); TypeSymbol result; switch (previous.Kind) { case SymbolKind.NamedType: result = SubstituteNamedType((NamedTypeSymbol)previous); break; case SymbolKind.TypeParameter: return SubstituteTypeParameter((TypeParameterSymbol)previous); case SymbolKind.ArrayType: result = SubstituteArrayType((ArrayTypeSymbol)previous); break; case SymbolKind.PointerType: result = SubstitutePointerType((PointerTypeSymbol)previous); break; case SymbolKind.FunctionPointerType: result = SubstituteFunctionPointerType((FunctionPointerTypeSymbol)previous); break; case SymbolKind.DynamicType: result = SubstituteDynamicType(); break; case SymbolKind.ErrorType: return ((ErrorTypeSymbol)previous).Substitute(this); default: result = previous; break; } return TypeWithAnnotations.Create(result); } internal TypeWithAnnotations SubstituteType(TypeWithAnnotations previous) { return previous.SubstituteType(this); } internal virtual ImmutableArray<CustomModifier> SubstituteCustomModifiers(ImmutableArray<CustomModifier> customModifiers) { if (customModifiers.IsDefaultOrEmpty) { return customModifiers; } for (int i = 0; i < customModifiers.Length; i++) { NamedTypeSymbol modifier = ((CSharpCustomModifier)customModifiers[i]).ModifierSymbol; var substituted = SubstituteNamedType(modifier); if (!TypeSymbol.Equals(modifier, substituted, TypeCompareKind.ConsiderEverything2)) { var builder = ArrayBuilder<CustomModifier>.GetInstance(customModifiers.Length); builder.AddRange(customModifiers, i); builder.Add(customModifiers[i].IsOptional ? CSharpCustomModifier.CreateOptional(substituted) : CSharpCustomModifier.CreateRequired(substituted)); for (i++; i < customModifiers.Length; i++) { modifier = ((CSharpCustomModifier)customModifiers[i]).ModifierSymbol; substituted = SubstituteNamedType(modifier); if (!TypeSymbol.Equals(modifier, substituted, TypeCompareKind.ConsiderEverything2)) { builder.Add(customModifiers[i].IsOptional ? CSharpCustomModifier.CreateOptional(substituted) : CSharpCustomModifier.CreateRequired(substituted)); } else { builder.Add(customModifiers[i]); } } Debug.Assert(builder.Count == customModifiers.Length); return builder.ToImmutableAndFree(); } } return customModifiers; } protected virtual TypeSymbol SubstituteDynamicType() { return DynamicTypeSymbol.Instance; } protected virtual TypeWithAnnotations SubstituteTypeParameter(TypeParameterSymbol typeParameter) { return TypeWithAnnotations.Create(typeParameter); } private ArrayTypeSymbol SubstituteArrayType(ArrayTypeSymbol t) { var oldElement = t.ElementTypeWithAnnotations; TypeWithAnnotations element = oldElement.SubstituteType(this); if (element.IsSameAs(oldElement)) { return t; } if (t.IsSZArray) { ImmutableArray<NamedTypeSymbol> interfaces = t.InterfacesNoUseSiteDiagnostics(); Debug.Assert(0 <= interfaces.Length && interfaces.Length <= 2); if (interfaces.Length == 1) { Debug.Assert(interfaces[0] is NamedTypeSymbol); // IList<T> interfaces = ImmutableArray.Create<NamedTypeSymbol>(SubstituteNamedType(interfaces[0])); } else if (interfaces.Length == 2) { Debug.Assert(interfaces[0] is NamedTypeSymbol); // IList<T> interfaces = ImmutableArray.Create<NamedTypeSymbol>(SubstituteNamedType(interfaces[0]), SubstituteNamedType(interfaces[1])); } else if (interfaces.Length != 0) { throw ExceptionUtilities.Unreachable; } return ArrayTypeSymbol.CreateSZArray( element, t.BaseTypeNoUseSiteDiagnostics, interfaces); } return ArrayTypeSymbol.CreateMDArray( element, t.Rank, t.Sizes, t.LowerBounds, t.BaseTypeNoUseSiteDiagnostics); } private PointerTypeSymbol SubstitutePointerType(PointerTypeSymbol t) { var oldPointedAtType = t.PointedAtTypeWithAnnotations; var pointedAtType = oldPointedAtType.SubstituteType(this); if (pointedAtType.IsSameAs(oldPointedAtType)) { return t; } return new PointerTypeSymbol(pointedAtType); } private FunctionPointerTypeSymbol SubstituteFunctionPointerType(FunctionPointerTypeSymbol f) { var substitutedReturnType = f.Signature.ReturnTypeWithAnnotations.SubstituteType(this); var refCustomModifiers = f.Signature.RefCustomModifiers; var substitutedRefCustomModifiers = SubstituteCustomModifiers(refCustomModifiers); var parameterTypesWithAnnotations = f.Signature.ParameterTypesWithAnnotations; ImmutableArray<TypeWithAnnotations> substitutedParamTypes = SubstituteTypes(parameterTypesWithAnnotations); ImmutableArray<ImmutableArray<CustomModifier>> substitutedParamModifiers = default; var paramCount = f.Signature.Parameters.Length; if (paramCount > 0) { var builder = ArrayBuilder<ImmutableArray<CustomModifier>>.GetInstance(paramCount); bool didSubstitute = false; foreach (var param in f.Signature.Parameters) { var substituted = SubstituteCustomModifiers(param.RefCustomModifiers); builder.Add(substituted); if (substituted != param.RefCustomModifiers) { didSubstitute = true; } } if (didSubstitute) { substitutedParamModifiers = builder.ToImmutableAndFree(); } else { builder.Free(); } } if (substitutedParamTypes != parameterTypesWithAnnotations || !substitutedParamModifiers.IsDefault || !f.Signature.ReturnTypeWithAnnotations.IsSameAs(substitutedReturnType) || substitutedRefCustomModifiers != refCustomModifiers) { f = f.SubstituteTypeSymbol(substitutedReturnType, substitutedParamTypes, refCustomModifiers, substitutedParamModifiers); } return f; } internal ImmutableArray<TypeSymbol> SubstituteTypesWithoutModifiers(ImmutableArray<TypeSymbol> original) { if (original.IsDefault) { return original; } TypeSymbol[] result = null; for (int i = 0; i < original.Length; i++) { var t = original[i]; var substituted = SubstituteType(t).Type; if (!Object.ReferenceEquals(substituted, t)) { if (result == null) { result = new TypeSymbol[original.Length]; for (int j = 0; j < i; j++) { result[j] = original[j]; } } } if (result != null) { result[i] = substituted; } } return result != null ? result.AsImmutableOrNull() : original; } internal ImmutableArray<TypeWithAnnotations> SubstituteTypes(ImmutableArray<TypeWithAnnotations> original) { if (original.IsDefault) { return default(ImmutableArray<TypeWithAnnotations>); } var result = ArrayBuilder<TypeWithAnnotations>.GetInstance(original.Length); foreach (TypeWithAnnotations t in original) { result.Add(SubstituteType(t)); } return result.ToImmutableAndFree(); } /// <summary> /// Substitute types, and return the results without duplicates, preserving the original order. /// Note, all occurrences of 'dynamic' in resulting types will be replaced with 'object'. /// </summary> internal void SubstituteConstraintTypesDistinctWithoutModifiers( TypeParameterSymbol owner, ImmutableArray<TypeWithAnnotations> original, ArrayBuilder<TypeWithAnnotations> result, HashSet<TypeParameterSymbol> ignoreTypesDependentOnTypeParametersOpt) { DynamicTypeEraser dynamicEraser = null; if (original.Length == 0) { return; } else if (original.Length == 1) { var type = original[0]; if (ignoreTypesDependentOnTypeParametersOpt == null || !type.Type.ContainsTypeParameters(ignoreTypesDependentOnTypeParametersOpt)) { result.Add(substituteConstraintType(type)); } } else { var map = PooledDictionary<TypeSymbol, int>.GetInstance(); foreach (var type in original) { if (ignoreTypesDependentOnTypeParametersOpt == null || !type.Type.ContainsTypeParameters(ignoreTypesDependentOnTypeParametersOpt)) { var substituted = substituteConstraintType(type); if (!map.TryGetValue(substituted.Type, out int mergeWith)) { map.Add(substituted.Type, result.Count); result.Add(substituted); } else { result[mergeWith] = ConstraintsHelper.ConstraintWithMostSignificantNullability(result[mergeWith], substituted); } } } map.Free(); } TypeWithAnnotations substituteConstraintType(TypeWithAnnotations type) { if (dynamicEraser == null) { dynamicEraser = new DynamicTypeEraser(owner.ContainingAssembly.CorLibrary.GetSpecialType(SpecialType.System_Object)); } TypeWithAnnotations substituted = SubstituteType(type); return substituted.WithTypeAndModifiers(dynamicEraser.EraseDynamic(substituted.Type), substituted.CustomModifiers); } } internal ImmutableArray<TypeParameterSymbol> SubstituteTypeParameters(ImmutableArray<TypeParameterSymbol> original) { return original.SelectAsArray((tp, m) => (TypeParameterSymbol)m.SubstituteTypeParameter(tp).AsTypeSymbolOnly(), this); } /// <summary> /// Like SubstTypes, but for NamedTypeSymbols. /// </summary> internal ImmutableArray<NamedTypeSymbol> SubstituteNamedTypes(ImmutableArray<NamedTypeSymbol> original) { NamedTypeSymbol[] result = null; for (int i = 0; i < original.Length; i++) { var t = original[i]; var substituted = SubstituteNamedType(t); if (!Object.ReferenceEquals(substituted, t)) { if (result == null) { result = new NamedTypeSymbol[original.Length]; for (int j = 0; j < i; j++) { result[j] = original[j]; } } } if (result != null) { result[i] = substituted; } } return result != null ? result.AsImmutableOrNull() : original; } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Abstract base class for mutable and immutable type maps. /// </summary> internal abstract class AbstractTypeMap { /// <summary> /// Substitute for a type declaration. May use alpha renaming if the container is substituted. /// </summary> internal virtual NamedTypeSymbol SubstituteTypeDeclaration(NamedTypeSymbol previous) { Debug.Assert((object)previous.ConstructedFrom == (object)previous); NamedTypeSymbol newContainingType = SubstituteNamedType(previous.ContainingType); if ((object)newContainingType == null) { return previous; } return previous.OriginalDefinition.AsMember(newContainingType); } /// <summary> /// SubstType, but for NamedTypeSymbols only. This is used for concrete types, so no alpha substitution appears in the result. /// </summary> internal NamedTypeSymbol SubstituteNamedType(NamedTypeSymbol previous) { if (ReferenceEquals(previous, null)) return null; if (previous.IsUnboundGenericType) return previous; if (previous.IsAnonymousType) { ImmutableArray<TypeWithAnnotations> oldFieldTypes = AnonymousTypeManager.GetAnonymousTypePropertyTypesWithAnnotations(previous); ImmutableArray<TypeWithAnnotations> newFieldTypes = SubstituteTypes(oldFieldTypes); return (oldFieldTypes == newFieldTypes) ? previous : AnonymousTypeManager.ConstructAnonymousTypeSymbol(previous, newFieldTypes); } // TODO: we could construct the result's ConstructedFrom lazily by using a "deep" // construct operation here (as VB does), thereby avoiding alpha renaming in most cases. // Aleksey has shown that would reduce GC pressure if substitutions of deeply nested generics are common. NamedTypeSymbol oldConstructedFrom = previous.ConstructedFrom; NamedTypeSymbol newConstructedFrom = SubstituteTypeDeclaration(oldConstructedFrom); ImmutableArray<TypeWithAnnotations> oldTypeArguments = previous.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; bool changed = !ReferenceEquals(oldConstructedFrom, newConstructedFrom); var newTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(oldTypeArguments.Length); for (int i = 0; i < oldTypeArguments.Length; i++) { var oldArgument = oldTypeArguments[i]; var newArgument = oldArgument.SubstituteType(this); if (!changed && !oldArgument.IsSameAs(newArgument)) { changed = true; } newTypeArguments.Add(newArgument); } if (!changed) { newTypeArguments.Free(); return previous; } return newConstructedFrom.ConstructIfGeneric(newTypeArguments.ToImmutableAndFree()).WithTupleDataFrom(previous); } /// <summary> /// Perform the substitution on the given type. Each occurrence of the type parameter is /// replaced with its corresponding type argument from the map. /// </summary> /// <param name="previous">The type to be rewritten.</param> /// <returns>The type with type parameters replaced with the type arguments.</returns> internal TypeWithAnnotations SubstituteType(TypeSymbol previous) { if (ReferenceEquals(previous, null)) return default(TypeWithAnnotations); TypeSymbol result; switch (previous.Kind) { case SymbolKind.NamedType: result = SubstituteNamedType((NamedTypeSymbol)previous); break; case SymbolKind.TypeParameter: return SubstituteTypeParameter((TypeParameterSymbol)previous); case SymbolKind.ArrayType: result = SubstituteArrayType((ArrayTypeSymbol)previous); break; case SymbolKind.PointerType: result = SubstitutePointerType((PointerTypeSymbol)previous); break; case SymbolKind.FunctionPointerType: result = SubstituteFunctionPointerType((FunctionPointerTypeSymbol)previous); break; case SymbolKind.DynamicType: result = SubstituteDynamicType(); break; case SymbolKind.ErrorType: return ((ErrorTypeSymbol)previous).Substitute(this); default: result = previous; break; } return TypeWithAnnotations.Create(result); } internal TypeWithAnnotations SubstituteType(TypeWithAnnotations previous) { return previous.SubstituteType(this); } internal virtual ImmutableArray<CustomModifier> SubstituteCustomModifiers(ImmutableArray<CustomModifier> customModifiers) { if (customModifiers.IsDefaultOrEmpty) { return customModifiers; } for (int i = 0; i < customModifiers.Length; i++) { NamedTypeSymbol modifier = ((CSharpCustomModifier)customModifiers[i]).ModifierSymbol; var substituted = SubstituteNamedType(modifier); if (!TypeSymbol.Equals(modifier, substituted, TypeCompareKind.ConsiderEverything2)) { var builder = ArrayBuilder<CustomModifier>.GetInstance(customModifiers.Length); builder.AddRange(customModifiers, i); builder.Add(customModifiers[i].IsOptional ? CSharpCustomModifier.CreateOptional(substituted) : CSharpCustomModifier.CreateRequired(substituted)); for (i++; i < customModifiers.Length; i++) { modifier = ((CSharpCustomModifier)customModifiers[i]).ModifierSymbol; substituted = SubstituteNamedType(modifier); if (!TypeSymbol.Equals(modifier, substituted, TypeCompareKind.ConsiderEverything2)) { builder.Add(customModifiers[i].IsOptional ? CSharpCustomModifier.CreateOptional(substituted) : CSharpCustomModifier.CreateRequired(substituted)); } else { builder.Add(customModifiers[i]); } } Debug.Assert(builder.Count == customModifiers.Length); return builder.ToImmutableAndFree(); } } return customModifiers; } protected virtual TypeSymbol SubstituteDynamicType() { return DynamicTypeSymbol.Instance; } protected virtual TypeWithAnnotations SubstituteTypeParameter(TypeParameterSymbol typeParameter) { return TypeWithAnnotations.Create(typeParameter); } private ArrayTypeSymbol SubstituteArrayType(ArrayTypeSymbol t) { var oldElement = t.ElementTypeWithAnnotations; TypeWithAnnotations element = oldElement.SubstituteType(this); if (element.IsSameAs(oldElement)) { return t; } if (t.IsSZArray) { ImmutableArray<NamedTypeSymbol> interfaces = t.InterfacesNoUseSiteDiagnostics(); Debug.Assert(0 <= interfaces.Length && interfaces.Length <= 2); if (interfaces.Length == 1) { Debug.Assert(interfaces[0] is NamedTypeSymbol); // IList<T> interfaces = ImmutableArray.Create<NamedTypeSymbol>(SubstituteNamedType(interfaces[0])); } else if (interfaces.Length == 2) { Debug.Assert(interfaces[0] is NamedTypeSymbol); // IList<T> interfaces = ImmutableArray.Create<NamedTypeSymbol>(SubstituteNamedType(interfaces[0]), SubstituteNamedType(interfaces[1])); } else if (interfaces.Length != 0) { throw ExceptionUtilities.Unreachable; } return ArrayTypeSymbol.CreateSZArray( element, t.BaseTypeNoUseSiteDiagnostics, interfaces); } return ArrayTypeSymbol.CreateMDArray( element, t.Rank, t.Sizes, t.LowerBounds, t.BaseTypeNoUseSiteDiagnostics); } private PointerTypeSymbol SubstitutePointerType(PointerTypeSymbol t) { var oldPointedAtType = t.PointedAtTypeWithAnnotations; var pointedAtType = oldPointedAtType.SubstituteType(this); if (pointedAtType.IsSameAs(oldPointedAtType)) { return t; } return new PointerTypeSymbol(pointedAtType); } private FunctionPointerTypeSymbol SubstituteFunctionPointerType(FunctionPointerTypeSymbol f) { var substitutedReturnType = f.Signature.ReturnTypeWithAnnotations.SubstituteType(this); var refCustomModifiers = f.Signature.RefCustomModifiers; var substitutedRefCustomModifiers = SubstituteCustomModifiers(refCustomModifiers); var parameterTypesWithAnnotations = f.Signature.ParameterTypesWithAnnotations; ImmutableArray<TypeWithAnnotations> substitutedParamTypes = SubstituteTypes(parameterTypesWithAnnotations); ImmutableArray<ImmutableArray<CustomModifier>> substitutedParamModifiers = default; var paramCount = f.Signature.Parameters.Length; if (paramCount > 0) { var builder = ArrayBuilder<ImmutableArray<CustomModifier>>.GetInstance(paramCount); bool didSubstitute = false; foreach (var param in f.Signature.Parameters) { var substituted = SubstituteCustomModifiers(param.RefCustomModifiers); builder.Add(substituted); if (substituted != param.RefCustomModifiers) { didSubstitute = true; } } if (didSubstitute) { substitutedParamModifiers = builder.ToImmutableAndFree(); } else { builder.Free(); } } if (substitutedParamTypes != parameterTypesWithAnnotations || !substitutedParamModifiers.IsDefault || !f.Signature.ReturnTypeWithAnnotations.IsSameAs(substitutedReturnType) || substitutedRefCustomModifiers != refCustomModifiers) { f = f.SubstituteTypeSymbol(substitutedReturnType, substitutedParamTypes, refCustomModifiers, substitutedParamModifiers); } return f; } internal ImmutableArray<TypeSymbol> SubstituteTypesWithoutModifiers(ImmutableArray<TypeSymbol> original) { if (original.IsDefault) { return original; } TypeSymbol[] result = null; for (int i = 0; i < original.Length; i++) { var t = original[i]; var substituted = SubstituteType(t).Type; if (!Object.ReferenceEquals(substituted, t)) { if (result == null) { result = new TypeSymbol[original.Length]; for (int j = 0; j < i; j++) { result[j] = original[j]; } } } if (result != null) { result[i] = substituted; } } return result != null ? result.AsImmutableOrNull() : original; } internal ImmutableArray<TypeWithAnnotations> SubstituteTypes(ImmutableArray<TypeWithAnnotations> original) { if (original.IsDefault) { return default(ImmutableArray<TypeWithAnnotations>); } var result = ArrayBuilder<TypeWithAnnotations>.GetInstance(original.Length); foreach (TypeWithAnnotations t in original) { result.Add(SubstituteType(t)); } return result.ToImmutableAndFree(); } /// <summary> /// Substitute types, and return the results without duplicates, preserving the original order. /// Note, all occurrences of 'dynamic' in resulting types will be replaced with 'object'. /// </summary> internal void SubstituteConstraintTypesDistinctWithoutModifiers( TypeParameterSymbol owner, ImmutableArray<TypeWithAnnotations> original, ArrayBuilder<TypeWithAnnotations> result, HashSet<TypeParameterSymbol> ignoreTypesDependentOnTypeParametersOpt) { DynamicTypeEraser dynamicEraser = null; if (original.Length == 0) { return; } else if (original.Length == 1) { var type = original[0]; if (ignoreTypesDependentOnTypeParametersOpt == null || !type.Type.ContainsTypeParameters(ignoreTypesDependentOnTypeParametersOpt)) { result.Add(substituteConstraintType(type)); } } else { var map = PooledDictionary<TypeSymbol, int>.GetInstance(); foreach (var type in original) { if (ignoreTypesDependentOnTypeParametersOpt == null || !type.Type.ContainsTypeParameters(ignoreTypesDependentOnTypeParametersOpt)) { var substituted = substituteConstraintType(type); if (!map.TryGetValue(substituted.Type, out int mergeWith)) { map.Add(substituted.Type, result.Count); result.Add(substituted); } else { result[mergeWith] = ConstraintsHelper.ConstraintWithMostSignificantNullability(result[mergeWith], substituted); } } } map.Free(); } TypeWithAnnotations substituteConstraintType(TypeWithAnnotations type) { if (dynamicEraser == null) { dynamicEraser = new DynamicTypeEraser(owner.ContainingAssembly.CorLibrary.GetSpecialType(SpecialType.System_Object)); } TypeWithAnnotations substituted = SubstituteType(type); return substituted.WithTypeAndModifiers(dynamicEraser.EraseDynamic(substituted.Type), substituted.CustomModifiers); } } internal ImmutableArray<TypeParameterSymbol> SubstituteTypeParameters(ImmutableArray<TypeParameterSymbol> original) { return original.SelectAsArray((tp, m) => (TypeParameterSymbol)m.SubstituteTypeParameter(tp).AsTypeSymbolOnly(), this); } /// <summary> /// Like SubstTypes, but for NamedTypeSymbols. /// </summary> internal ImmutableArray<NamedTypeSymbol> SubstituteNamedTypes(ImmutableArray<NamedTypeSymbol> original) { NamedTypeSymbol[] result = null; for (int i = 0; i < original.Length; i++) { var t = original[i]; var substituted = SubstituteNamedType(t); if (!Object.ReferenceEquals(substituted, t)) { if (result == null) { result = new NamedTypeSymbol[original.Length]; for (int j = 0; j < i; j++) { result[j] = original[j]; } } } if (result != null) { result[i] = substituted; } } return result != null ? result.AsImmutableOrNull() : original; } } }
-1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/ISymbolExtensions_2.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class ISymbolExtensions { public static bool IsImplicitValueParameter([NotNullWhen(returnValue: true)] this ISymbol? symbol) { if (symbol is IParameterSymbol && symbol.IsImplicitlyDeclared) { if (symbol.ContainingSymbol is IMethodSymbol method) { if (method.MethodKind == MethodKind.EventAdd || method.MethodKind == MethodKind.EventRemove || method.MethodKind == MethodKind.PropertySet) { // the name is value in C#, and Value in VB return symbol.Name == "value" || symbol.Name == "Value"; } } } 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.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class ISymbolExtensions { public static bool IsImplicitValueParameter([NotNullWhen(returnValue: true)] this ISymbol? symbol) { if (symbol is IParameterSymbol && symbol.IsImplicitlyDeclared) { if (symbol.ContainingSymbol is IMethodSymbol method) { if (method.MethodKind == MethodKind.EventAdd || method.MethodKind == MethodKind.EventRemove || method.MethodKind == MethodKind.PropertySet) { // the name is value in C#, and Value in VB return symbol.Name == "value" || symbol.Name == "Value"; } } } return false; } } }
-1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/UnifiedSuggestions/UnifiedSuggestedActions/UnifiedSuggestedAction.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.CodeActions; namespace Microsoft.CodeAnalysis.UnifiedSuggestions { /// <summary> /// Similar to SuggestedAction, but in a location that can be used by /// both local Roslyn and LSP. /// </summary> internal class UnifiedSuggestedAction : IUnifiedSuggestedAction { public Workspace Workspace { get; } public CodeAction OriginalCodeAction { get; } public CodeActionPriority CodeActionPriority { get; } public UnifiedSuggestedAction(Workspace workspace, CodeAction codeAction, CodeActionPriority codeActionPriority) { Workspace = workspace; OriginalCodeAction = codeAction; CodeActionPriority = codeActionPriority; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.CodeActions; namespace Microsoft.CodeAnalysis.UnifiedSuggestions { /// <summary> /// Similar to SuggestedAction, but in a location that can be used by /// both local Roslyn and LSP. /// </summary> internal class UnifiedSuggestedAction : IUnifiedSuggestedAction { public Workspace Workspace { get; } public CodeAction OriginalCodeAction { get; } public CodeActionPriority CodeActionPriority { get; } public UnifiedSuggestedAction(Workspace workspace, CodeAction codeAction, CodeActionPriority codeActionPriority) { Workspace = workspace; OriginalCodeAction = codeAction; CodeActionPriority = codeActionPriority; } } }
-1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/SmallConcurrentSetOfInts.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.Threading; namespace Microsoft.CodeAnalysis.Collections { /// <summary> /// A set of ints that is small, thread-safe and lock free. /// Several assumptions have been made that allow it to be small and fast: /// 1. Deletes never happen. /// 2. The size is small. In dogfooding experiments, 89% had 4 or fewer elements and /// 98% had 8 or fewer elements. The largest size was 17. /// 3. As a result of assumption 2, linear look-up is good enough. /// 4. One value, in this case int.MinValue, is used as a sentinel and may never appear in the set. /// </summary> internal class SmallConcurrentSetOfInts { // The set is a singly-linked list of nodes each containing up to 4 values. // Empty slots contain the "unoccupied" sentinel value. private int _v1; private int _v2; private int _v3; private int _v4; private SmallConcurrentSetOfInts? _next; private const int unoccupied = int.MinValue; public SmallConcurrentSetOfInts() { _v1 = _v2 = _v3 = _v4 = unoccupied; } private SmallConcurrentSetOfInts(int initialValue) { _v1 = initialValue; _v2 = _v3 = _v4 = unoccupied; } /// <summary> /// Determine if the given integer appears in the set. /// </summary> /// <param name="i">The value to look up.</param> /// <returns>true if <paramref name="i"/> appears in the set. false otherwise.</returns> public bool Contains(int i) { Debug.Assert(i != unoccupied); return SmallConcurrentSetOfInts.Contains(this, i); } private static bool Contains(SmallConcurrentSetOfInts set, int i) { SmallConcurrentSetOfInts? current = set; do { // PERF: Not testing for unoccupied slots since it adds complexity. The extra comparisons // would slow down this inner loop such that any benefit of an 'early out' would be lost. if (current._v1 == i || current._v2 == i || current._v3 == i || current._v4 == i) { return true; } current = current._next; } while (current != null); return false; } /// <summary> /// Insert the given value into the set. /// </summary> /// <param name="i">The value to insert</param> /// <returns>true if <paramref name="i"/> was added. false if it was already present.</returns> public bool Add(int i) { Debug.Assert(i != unoccupied); return SmallConcurrentSetOfInts.Add(this, i); } private static bool Add(SmallConcurrentSetOfInts set, int i) { bool added = false; while (true) { if (AddHelper(ref set._v1, i, ref added) || AddHelper(ref set._v2, i, ref added) || AddHelper(ref set._v3, i, ref added) || AddHelper(ref set._v4, i, ref added)) { return added; } var nextSet = set._next; if (nextSet == null) { // Need to add a new 'block'. SmallConcurrentSetOfInts tail = new SmallConcurrentSetOfInts(initialValue: i); nextSet = Interlocked.CompareExchange(ref set._next, tail, null); if (nextSet == null) { // Successfully added a new tail return true; } // Lost the race. Another thread added a new tail so resume searching from there. } set = nextSet; } } /// <summary> /// If the given slot is unoccupied, then try to replace it with a new value. /// </summary> /// <param name="slot">The slot to examine.</param> /// <param name="i">The new value to insert if the slot is unoccupied.</param> /// <param name="added">An out param indicating whether the slot was successfully updated.</param> /// <returns>true if the value in the slot either now contains, or already contained <paramref name="i"/>. false otherwise.</returns> private static bool AddHelper(ref int slot, int i, ref bool added) { Debug.Assert(!added); int val = slot; if (val == unoccupied) { val = Interlocked.CompareExchange(ref slot, i, unoccupied); if (val == unoccupied) { // Successfully replaced the value added = true; return true; } // Lost the race with another thread } return (val == i); } } }
// Licensed to the .NET Foundation under one or more 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.Threading; namespace Microsoft.CodeAnalysis.Collections { /// <summary> /// A set of ints that is small, thread-safe and lock free. /// Several assumptions have been made that allow it to be small and fast: /// 1. Deletes never happen. /// 2. The size is small. In dogfooding experiments, 89% had 4 or fewer elements and /// 98% had 8 or fewer elements. The largest size was 17. /// 3. As a result of assumption 2, linear look-up is good enough. /// 4. One value, in this case int.MinValue, is used as a sentinel and may never appear in the set. /// </summary> internal class SmallConcurrentSetOfInts { // The set is a singly-linked list of nodes each containing up to 4 values. // Empty slots contain the "unoccupied" sentinel value. private int _v1; private int _v2; private int _v3; private int _v4; private SmallConcurrentSetOfInts? _next; private const int unoccupied = int.MinValue; public SmallConcurrentSetOfInts() { _v1 = _v2 = _v3 = _v4 = unoccupied; } private SmallConcurrentSetOfInts(int initialValue) { _v1 = initialValue; _v2 = _v3 = _v4 = unoccupied; } /// <summary> /// Determine if the given integer appears in the set. /// </summary> /// <param name="i">The value to look up.</param> /// <returns>true if <paramref name="i"/> appears in the set. false otherwise.</returns> public bool Contains(int i) { Debug.Assert(i != unoccupied); return SmallConcurrentSetOfInts.Contains(this, i); } private static bool Contains(SmallConcurrentSetOfInts set, int i) { SmallConcurrentSetOfInts? current = set; do { // PERF: Not testing for unoccupied slots since it adds complexity. The extra comparisons // would slow down this inner loop such that any benefit of an 'early out' would be lost. if (current._v1 == i || current._v2 == i || current._v3 == i || current._v4 == i) { return true; } current = current._next; } while (current != null); return false; } /// <summary> /// Insert the given value into the set. /// </summary> /// <param name="i">The value to insert</param> /// <returns>true if <paramref name="i"/> was added. false if it was already present.</returns> public bool Add(int i) { Debug.Assert(i != unoccupied); return SmallConcurrentSetOfInts.Add(this, i); } private static bool Add(SmallConcurrentSetOfInts set, int i) { bool added = false; while (true) { if (AddHelper(ref set._v1, i, ref added) || AddHelper(ref set._v2, i, ref added) || AddHelper(ref set._v3, i, ref added) || AddHelper(ref set._v4, i, ref added)) { return added; } var nextSet = set._next; if (nextSet == null) { // Need to add a new 'block'. SmallConcurrentSetOfInts tail = new SmallConcurrentSetOfInts(initialValue: i); nextSet = Interlocked.CompareExchange(ref set._next, tail, null); if (nextSet == null) { // Successfully added a new tail return true; } // Lost the race. Another thread added a new tail so resume searching from there. } set = nextSet; } } /// <summary> /// If the given slot is unoccupied, then try to replace it with a new value. /// </summary> /// <param name="slot">The slot to examine.</param> /// <param name="i">The new value to insert if the slot is unoccupied.</param> /// <param name="added">An out param indicating whether the slot was successfully updated.</param> /// <returns>true if the value in the slot either now contains, or already contained <paramref name="i"/>. false otherwise.</returns> private static bool AddHelper(ref int slot, int i, ref bool added) { Debug.Assert(!added); int val = slot; if (val == unoccupied) { val = Interlocked.CompareExchange(ref slot, i, unoccupied); if (val == unoccupied) { // Successfully replaced the value added = true; return true; } // Lost the race with another thread } return (val == i); } } }
-1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/Completion/KeywordRecommenders/ReferenceKeywordRecommender.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.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ReferenceKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public ReferenceKeywordRecommender() : base(SyntaxKind.ReferenceKeyword, isValidInPreprocessorContext: true) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var syntaxTree = context.SyntaxTree; return context.IsPreProcessorKeywordContext && syntaxTree.IsScript() && syntaxTree.IsBeforeFirstToken(position, cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ReferenceKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public ReferenceKeywordRecommender() : base(SyntaxKind.ReferenceKeyword, isValidInPreprocessorContext: true) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var syntaxTree = context.SyntaxTree; return context.IsPreProcessorKeywordContext && syntaxTree.IsScript() && syntaxTree.IsBeforeFirstToken(position, cancellationToken); } } }
-1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/Implementation/Classification/ClassificationUtilities.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 Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; namespace Microsoft.CodeAnalysis.Editor.Implementation.Classification { internal static class ClassificationUtilities { public static TagSpan<IClassificationTag> Convert(ClassificationTypeMap typeMap, ITextSnapshot snapshot, ClassifiedSpan classifiedSpan) { return new TagSpan<IClassificationTag>( classifiedSpan.TextSpan.ToSnapshotSpan(snapshot), new ClassificationTag(typeMap.GetClassificationType(classifiedSpan.ClassificationType))); } public static List<ITagSpan<IClassificationTag>> Convert(ClassificationTypeMap typeMap, ITextSnapshot snapshot, ArrayBuilder<ClassifiedSpan> classifiedSpans) { var result = new List<ITagSpan<IClassificationTag>>(capacity: classifiedSpans.Count); foreach (var span in classifiedSpans) result.Add(Convert(typeMap, snapshot, span)); return result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; namespace Microsoft.CodeAnalysis.Editor.Implementation.Classification { internal static class ClassificationUtilities { public static TagSpan<IClassificationTag> Convert(ClassificationTypeMap typeMap, ITextSnapshot snapshot, ClassifiedSpan classifiedSpan) { return new TagSpan<IClassificationTag>( classifiedSpan.TextSpan.ToSnapshotSpan(snapshot), new ClassificationTag(typeMap.GetClassificationType(classifiedSpan.ClassificationType))); } public static List<ITagSpan<IClassificationTag>> Convert(ClassificationTypeMap typeMap, ITextSnapshot snapshot, ArrayBuilder<ClassifiedSpan> classifiedSpans) { var result = new List<ITagSpan<IClassificationTag>>(capacity: classifiedSpans.Count); foreach (var span in classifiedSpans) result.Add(Convert(typeMap, snapshot, span)); return result; } } }
-1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/Tools/AnalyzerRunner/Program.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.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Runtime; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.MSBuild; namespace AnalyzerRunner { /// <summary> /// AnalyzerRunner is a tool that will analyze a solution, find diagnostics in it and will print out the number of /// diagnostics it could find. This is useful to easily test performance without having the overhead of visual /// studio running. /// </summary> class Program { public static async Task Main(string[] args) { Options options; try { options = Options.Create(args); } catch (InvalidDataException) { PrintHelp(); return; } var cts = new CancellationTokenSource(); Console.CancelKeyPress += (sender, e) => { e.Cancel = true; cts.Cancel(); }; var cancellationToken = cts.Token; if (!string.IsNullOrEmpty(options.ProfileRoot)) { Directory.CreateDirectory(options.ProfileRoot); ProfileOptimization.SetProfileRoot(options.ProfileRoot); } using var workspace = AnalyzerRunnerHelper.CreateWorkspace(); var incrementalAnalyzerRunner = new IncrementalAnalyzerRunner(workspace, options); var diagnosticAnalyzerRunner = new DiagnosticAnalyzerRunner(workspace, options); var codeRefactoringRunner = new CodeRefactoringRunner(workspace, options); if (!incrementalAnalyzerRunner.HasAnalyzers && !diagnosticAnalyzerRunner.HasAnalyzers && !codeRefactoringRunner.HasRefactorings) { WriteLine("No analyzers found", ConsoleColor.Red); PrintHelp(); return; } var stopwatch = PerformanceTracker.StartNew(); if (!string.IsNullOrEmpty(options.ProfileRoot)) { ProfileOptimization.StartProfile(nameof(MSBuildWorkspace.OpenSolutionAsync)); } await workspace.OpenSolutionAsync(options.SolutionPath, progress: null, cancellationToken).ConfigureAwait(false); foreach (var workspaceDiagnostic in workspace.Diagnostics) { if (workspaceDiagnostic.Kind == WorkspaceDiagnosticKind.Failure) { Console.WriteLine(workspaceDiagnostic.Message); } } Console.WriteLine($"Loaded solution in {stopwatch.GetSummary(preciseMemory: true)}"); if (options.ShowStats) { stopwatch = PerformanceTracker.StartNew(); ShowSolutionStatistics(workspace.CurrentSolution, cancellationToken); Console.WriteLine($"Statistics gathered in {stopwatch.GetSummary(preciseMemory: true)}"); } if (options.ShowCompilerDiagnostics) { await ShowCompilerDiagnosticsAsync(workspace.CurrentSolution, cancellationToken).ConfigureAwait(false); } Console.WriteLine("Pausing 5 seconds before starting analysis..."); await Task.Delay(TimeSpan.FromSeconds(5)).ConfigureAwait(false); if (incrementalAnalyzerRunner.HasAnalyzers) { if (!string.IsNullOrEmpty(options.ProfileRoot)) { ProfileOptimization.StartProfile(nameof(Microsoft.CodeAnalysis.SolutionCrawler.IIncrementalAnalyzer)); } await incrementalAnalyzerRunner.RunAsync(cancellationToken).ConfigureAwait(false); } if (diagnosticAnalyzerRunner.HasAnalyzers) { if (!string.IsNullOrEmpty(options.ProfileRoot)) { ProfileOptimization.StartProfile(nameof(DiagnosticAnalyzerRunner)); } await diagnosticAnalyzerRunner.RunAllAsync(cancellationToken).ConfigureAwait(false); } if (codeRefactoringRunner.HasRefactorings) { if (!string.IsNullOrEmpty(options.ProfileRoot)) { ProfileOptimization.StartProfile(nameof(CodeRefactoringRunner)); } await codeRefactoringRunner.RunAsync(cancellationToken).ConfigureAwait(false); } } private static async Task ShowCompilerDiagnosticsAsync(Solution solution, CancellationToken cancellationToken) { var projectIds = solution.ProjectIds; foreach (var projectId in projectIds) { solution = solution.WithProjectAnalyzerReferences(projectId, ImmutableArray<AnalyzerReference>.Empty); } var projects = solution.Projects.Where(project => project.Language == LanguageNames.CSharp || project.Language == LanguageNames.VisualBasic).ToList(); var diagnosticStatistics = new Dictionary<string, (string description, DiagnosticSeverity severity, int count)>(); foreach (var project in projects) { var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); foreach (var diagnostic in compilation.GetDiagnostics(cancellationToken)) { diagnosticStatistics.TryGetValue(diagnostic.Id, out var existing); var description = existing.description; if (string.IsNullOrEmpty(description)) { description = diagnostic.Descriptor?.Title.ToString(); if (string.IsNullOrEmpty(description)) { description = diagnostic.Descriptor?.MessageFormat.ToString(); } } diagnosticStatistics[diagnostic.Id] = (description, diagnostic.Descriptor.DefaultSeverity, existing.count + 1); } } foreach (var pair in diagnosticStatistics) { Console.WriteLine($" {pair.Value.severity} {pair.Key}: {pair.Value.count} instances ({pair.Value.description})"); } } private static void ShowSolutionStatistics(Solution solution, CancellationToken cancellationToken) { var projects = solution.Projects.Where(project => project.Language == LanguageNames.CSharp || project.Language == LanguageNames.VisualBasic).ToList(); Console.WriteLine("Number of projects:\t\t" + projects.Count); Console.WriteLine("Number of documents:\t\t" + projects.Sum(x => x.DocumentIds.Count)); var statistics = GetSolutionStatistics(projects, cancellationToken); Console.WriteLine("Number of syntax nodes:\t\t" + statistics.NumberofNodes); Console.WriteLine("Number of syntax tokens:\t" + statistics.NumberOfTokens); Console.WriteLine("Number of syntax trivia:\t" + statistics.NumberOfTrivia); } private static Statistic GetSolutionStatistics(IEnumerable<Project> projects, CancellationToken cancellationToken) { var sums = new ConcurrentBag<Statistic>(); Parallel.ForEach(projects.SelectMany(project => project.Documents), document => { var documentStatistics = GetSolutionStatisticsAsync(document, cancellationToken).ConfigureAwait(false).GetAwaiter().GetResult(); sums.Add(documentStatistics); }); var sum = sums.Aggregate(new Statistic(0, 0, 0), (currentResult, value) => currentResult + value); return sum; } // TODO consider removing this and using GetAnalysisResultAsync // https://github.com/dotnet/roslyn/issues/23108 private static async Task<Statistic> GetSolutionStatisticsAsync(Document document, CancellationToken cancellationToken) { var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false); var tokensAndNodes = root.DescendantNodesAndTokensAndSelf(descendIntoTrivia: true); var numberOfNodes = tokensAndNodes.Count(x => x.IsNode); var numberOfTokens = tokensAndNodes.Count(x => x.IsToken); var numberOfTrivia = root.DescendantTrivia(descendIntoTrivia: true).Count(); return new Statistic(numberOfNodes, numberOfTokens, numberOfTrivia); } internal static void WriteLine(string text, ConsoleColor color) { Console.ForegroundColor = color; Console.WriteLine(text); Console.ResetColor(); } internal static void PrintHelp() { Console.WriteLine("Usage: AnalyzerRunner <AnalyzerAssemblyOrFolder> <Solution> [options]"); Console.WriteLine("Options:"); Console.WriteLine("/all Run all analyzers, including ones that are disabled by default"); Console.WriteLine("/stats Display statistics of the solution"); Console.WriteLine("/a <analyzer name> Enable analyzer with <analyzer name> (when this is specified, only analyzers specificed are enabled. Use: /a <name1> /a <name2>, etc."); Console.WriteLine("/concurrent Executes analyzers in concurrent mode"); Console.WriteLine("/suppressed Reports suppressed diagnostics"); Console.WriteLine("/log <logFile> Write logs into the log file specified"); Console.WriteLine("/editperf[:<match>] Test the incremental performance of analyzers to simulate the behavior of editing files. If <match> is specified, only files matching this regular expression are evaluated for editor performance."); Console.WriteLine("/edititer:<iterations> Specifies the number of iterations to use for testing documents with /editperf. When this is not specified, the default value is 10."); Console.WriteLine("/persist Enable persistent storage (e.g. SQLite; only applies to IIncrementalAnalyzer testing)"); Console.WriteLine("/fsa Enable full solution analysis (only applies to IIncrementalAnalyzer testing)"); Console.WriteLine("/ia <analyzer name> Enable incremental analyzer with <analyzer name> (when this is specified, only incremental analyzers specified are enabled. Use: /ia <name1> /ia <name2>, etc."); } } }
// Licensed to the .NET Foundation under one or more 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.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Runtime; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.MSBuild; namespace AnalyzerRunner { /// <summary> /// AnalyzerRunner is a tool that will analyze a solution, find diagnostics in it and will print out the number of /// diagnostics it could find. This is useful to easily test performance without having the overhead of visual /// studio running. /// </summary> class Program { public static async Task Main(string[] args) { Options options; try { options = Options.Create(args); } catch (InvalidDataException) { PrintHelp(); return; } var cts = new CancellationTokenSource(); Console.CancelKeyPress += (sender, e) => { e.Cancel = true; cts.Cancel(); }; var cancellationToken = cts.Token; if (!string.IsNullOrEmpty(options.ProfileRoot)) { Directory.CreateDirectory(options.ProfileRoot); ProfileOptimization.SetProfileRoot(options.ProfileRoot); } using var workspace = AnalyzerRunnerHelper.CreateWorkspace(); var incrementalAnalyzerRunner = new IncrementalAnalyzerRunner(workspace, options); var diagnosticAnalyzerRunner = new DiagnosticAnalyzerRunner(workspace, options); var codeRefactoringRunner = new CodeRefactoringRunner(workspace, options); if (!incrementalAnalyzerRunner.HasAnalyzers && !diagnosticAnalyzerRunner.HasAnalyzers && !codeRefactoringRunner.HasRefactorings) { WriteLine("No analyzers found", ConsoleColor.Red); PrintHelp(); return; } var stopwatch = PerformanceTracker.StartNew(); if (!string.IsNullOrEmpty(options.ProfileRoot)) { ProfileOptimization.StartProfile(nameof(MSBuildWorkspace.OpenSolutionAsync)); } await workspace.OpenSolutionAsync(options.SolutionPath, progress: null, cancellationToken).ConfigureAwait(false); foreach (var workspaceDiagnostic in workspace.Diagnostics) { if (workspaceDiagnostic.Kind == WorkspaceDiagnosticKind.Failure) { Console.WriteLine(workspaceDiagnostic.Message); } } Console.WriteLine($"Loaded solution in {stopwatch.GetSummary(preciseMemory: true)}"); if (options.ShowStats) { stopwatch = PerformanceTracker.StartNew(); ShowSolutionStatistics(workspace.CurrentSolution, cancellationToken); Console.WriteLine($"Statistics gathered in {stopwatch.GetSummary(preciseMemory: true)}"); } if (options.ShowCompilerDiagnostics) { await ShowCompilerDiagnosticsAsync(workspace.CurrentSolution, cancellationToken).ConfigureAwait(false); } Console.WriteLine("Pausing 5 seconds before starting analysis..."); await Task.Delay(TimeSpan.FromSeconds(5)).ConfigureAwait(false); if (incrementalAnalyzerRunner.HasAnalyzers) { if (!string.IsNullOrEmpty(options.ProfileRoot)) { ProfileOptimization.StartProfile(nameof(Microsoft.CodeAnalysis.SolutionCrawler.IIncrementalAnalyzer)); } await incrementalAnalyzerRunner.RunAsync(cancellationToken).ConfigureAwait(false); } if (diagnosticAnalyzerRunner.HasAnalyzers) { if (!string.IsNullOrEmpty(options.ProfileRoot)) { ProfileOptimization.StartProfile(nameof(DiagnosticAnalyzerRunner)); } await diagnosticAnalyzerRunner.RunAllAsync(cancellationToken).ConfigureAwait(false); } if (codeRefactoringRunner.HasRefactorings) { if (!string.IsNullOrEmpty(options.ProfileRoot)) { ProfileOptimization.StartProfile(nameof(CodeRefactoringRunner)); } await codeRefactoringRunner.RunAsync(cancellationToken).ConfigureAwait(false); } } private static async Task ShowCompilerDiagnosticsAsync(Solution solution, CancellationToken cancellationToken) { var projectIds = solution.ProjectIds; foreach (var projectId in projectIds) { solution = solution.WithProjectAnalyzerReferences(projectId, ImmutableArray<AnalyzerReference>.Empty); } var projects = solution.Projects.Where(project => project.Language == LanguageNames.CSharp || project.Language == LanguageNames.VisualBasic).ToList(); var diagnosticStatistics = new Dictionary<string, (string description, DiagnosticSeverity severity, int count)>(); foreach (var project in projects) { var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); foreach (var diagnostic in compilation.GetDiagnostics(cancellationToken)) { diagnosticStatistics.TryGetValue(diagnostic.Id, out var existing); var description = existing.description; if (string.IsNullOrEmpty(description)) { description = diagnostic.Descriptor?.Title.ToString(); if (string.IsNullOrEmpty(description)) { description = diagnostic.Descriptor?.MessageFormat.ToString(); } } diagnosticStatistics[diagnostic.Id] = (description, diagnostic.Descriptor.DefaultSeverity, existing.count + 1); } } foreach (var pair in diagnosticStatistics) { Console.WriteLine($" {pair.Value.severity} {pair.Key}: {pair.Value.count} instances ({pair.Value.description})"); } } private static void ShowSolutionStatistics(Solution solution, CancellationToken cancellationToken) { var projects = solution.Projects.Where(project => project.Language == LanguageNames.CSharp || project.Language == LanguageNames.VisualBasic).ToList(); Console.WriteLine("Number of projects:\t\t" + projects.Count); Console.WriteLine("Number of documents:\t\t" + projects.Sum(x => x.DocumentIds.Count)); var statistics = GetSolutionStatistics(projects, cancellationToken); Console.WriteLine("Number of syntax nodes:\t\t" + statistics.NumberofNodes); Console.WriteLine("Number of syntax tokens:\t" + statistics.NumberOfTokens); Console.WriteLine("Number of syntax trivia:\t" + statistics.NumberOfTrivia); } private static Statistic GetSolutionStatistics(IEnumerable<Project> projects, CancellationToken cancellationToken) { var sums = new ConcurrentBag<Statistic>(); Parallel.ForEach(projects.SelectMany(project => project.Documents), document => { var documentStatistics = GetSolutionStatisticsAsync(document, cancellationToken).ConfigureAwait(false).GetAwaiter().GetResult(); sums.Add(documentStatistics); }); var sum = sums.Aggregate(new Statistic(0, 0, 0), (currentResult, value) => currentResult + value); return sum; } // TODO consider removing this and using GetAnalysisResultAsync // https://github.com/dotnet/roslyn/issues/23108 private static async Task<Statistic> GetSolutionStatisticsAsync(Document document, CancellationToken cancellationToken) { var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false); var tokensAndNodes = root.DescendantNodesAndTokensAndSelf(descendIntoTrivia: true); var numberOfNodes = tokensAndNodes.Count(x => x.IsNode); var numberOfTokens = tokensAndNodes.Count(x => x.IsToken); var numberOfTrivia = root.DescendantTrivia(descendIntoTrivia: true).Count(); return new Statistic(numberOfNodes, numberOfTokens, numberOfTrivia); } internal static void WriteLine(string text, ConsoleColor color) { Console.ForegroundColor = color; Console.WriteLine(text); Console.ResetColor(); } internal static void PrintHelp() { Console.WriteLine("Usage: AnalyzerRunner <AnalyzerAssemblyOrFolder> <Solution> [options]"); Console.WriteLine("Options:"); Console.WriteLine("/all Run all analyzers, including ones that are disabled by default"); Console.WriteLine("/stats Display statistics of the solution"); Console.WriteLine("/a <analyzer name> Enable analyzer with <analyzer name> (when this is specified, only analyzers specificed are enabled. Use: /a <name1> /a <name2>, etc."); Console.WriteLine("/concurrent Executes analyzers in concurrent mode"); Console.WriteLine("/suppressed Reports suppressed diagnostics"); Console.WriteLine("/log <logFile> Write logs into the log file specified"); Console.WriteLine("/editperf[:<match>] Test the incremental performance of analyzers to simulate the behavior of editing files. If <match> is specified, only files matching this regular expression are evaluated for editor performance."); Console.WriteLine("/edititer:<iterations> Specifies the number of iterations to use for testing documents with /editperf. When this is not specified, the default value is 10."); Console.WriteLine("/persist Enable persistent storage (e.g. SQLite; only applies to IIncrementalAnalyzer testing)"); Console.WriteLine("/fsa Enable full solution analysis (only applies to IIncrementalAnalyzer testing)"); Console.WriteLine("/ia <analyzer name> Enable incremental analyzer with <analyzer name> (when this is specified, only incremental analyzers specified are enabled. Use: /ia <name1> /ia <name2>, etc."); } } }
-1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/SyntaxGeneratorInternalExtensions/SyntaxGeneratorInternal.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 Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.Editing { /// <summary> /// Internal extensions to <see cref="SyntaxGenerator"/>. /// /// This interface is available in the shared CodeStyle and Workspaces layer to allow /// sharing internal generator methods between them. Once the methods are ready to be /// made public APIs, they can be moved to <see cref="SyntaxGenerator"/>. /// </summary> internal abstract class SyntaxGeneratorInternal : ILanguageService { internal abstract ISyntaxFacts SyntaxFacts { get; } internal abstract SyntaxTrivia EndOfLine(string text); /// <summary> /// Creates a statement that declares a single local variable with an optional initializer. /// </summary> internal abstract SyntaxNode LocalDeclarationStatement( SyntaxNode type, SyntaxToken identifier, SyntaxNode initializer = null, bool isConst = false); /// <summary> /// Creates a statement that declares a single local variable. /// </summary> internal SyntaxNode LocalDeclarationStatement(SyntaxToken name, SyntaxNode initializer) => LocalDeclarationStatement(null, name, initializer); internal abstract SyntaxNode WithInitializer(SyntaxNode variableDeclarator, SyntaxNode initializer); internal abstract SyntaxNode EqualsValueClause(SyntaxToken operatorToken, SyntaxNode value); internal abstract SyntaxToken Identifier(string identifier); internal abstract SyntaxNode ConditionalAccessExpression(SyntaxNode expression, SyntaxNode whenNotNull); internal abstract SyntaxNode MemberBindingExpression(SyntaxNode name); internal abstract SyntaxNode RefExpression(SyntaxNode expression); /// <summary> /// Wraps with parens. /// </summary> internal abstract SyntaxNode AddParentheses(SyntaxNode expression, bool includeElasticTrivia = true, bool addSimplifierAnnotation = true); /// <summary> /// Creates a statement that can be used to yield a value from an iterator method. /// </summary> /// <param name="expression">An expression that can be yielded.</param> internal abstract SyntaxNode YieldReturnStatement(SyntaxNode expression); /// <summary> /// <see langword="true"/> if the language requires a "TypeExpression" /// (including <see langword="var"/>) to be stated when making a /// <see cref="LocalDeclarationStatement(SyntaxNode, SyntaxToken, SyntaxNode, bool)"/>. /// <see langword="false"/> if the language allows the type node to be entirely elided. /// </summary> internal abstract bool RequiresLocalDeclarationType(); internal abstract SyntaxToken InterpolatedStringTextToken(string content, string value); internal abstract SyntaxNode InterpolatedStringText(SyntaxToken textToken); internal abstract SyntaxNode Interpolation(SyntaxNode syntaxNode); internal abstract SyntaxNode InterpolatedStringExpression(SyntaxToken startToken, IEnumerable<SyntaxNode> content, SyntaxToken endToken); internal abstract SyntaxNode InterpolationAlignmentClause(SyntaxNode alignment); internal abstract SyntaxNode InterpolationFormatClause(string format); internal abstract SyntaxNode TypeParameterList(IEnumerable<string> typeParameterNames); /// <summary> /// Produces an appropriate TypeSyntax for the given <see cref="ITypeSymbol"/>. The <paramref name="typeContext"/> /// flag controls how this should be created depending on if this node is intended for use in a type-only /// context, or an expression-level context. In the former case, both C# and VB will create QualifiedNameSyntax /// nodes for dotted type names, whereas in the latter case both languages will create MemberAccessExpressionSyntax /// nodes. The final stringified result will be the same in both cases. However, the structure of the trees /// will be substantively different, which can impact how the compilation layers analyze the tree and how /// transformational passes affect it. /// </summary> /// <remarks> /// Passing in the right value for <paramref name="typeContext"/> is necessary for correctness and for use /// of compilation (and other) layers in a supported fashion. For example, if a QualifiedTypeSyntax is /// sed in a place the compiler would have parsed out a MemberAccessExpression, then it is undefined behavior /// what will happen if that tree is passed to any other components. /// </remarks> internal abstract SyntaxNode Type(ITypeSymbol typeSymbol, bool typeContext); #region Patterns internal abstract bool SupportsPatterns(ParseOptions options); internal abstract SyntaxNode IsPatternExpression(SyntaxNode expression, SyntaxToken isToken, SyntaxNode pattern); internal abstract SyntaxNode AndPattern(SyntaxNode left, SyntaxNode right); internal abstract SyntaxNode DeclarationPattern(INamedTypeSymbol type, string name); internal abstract SyntaxNode ConstantPattern(SyntaxNode expression); internal abstract SyntaxNode NotPattern(SyntaxNode pattern); internal abstract SyntaxNode OrPattern(SyntaxNode left, SyntaxNode right); internal abstract SyntaxNode ParenthesizedPattern(SyntaxNode pattern); internal abstract SyntaxNode TypePattern(SyntaxNode type); #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 Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.Editing { /// <summary> /// Internal extensions to <see cref="SyntaxGenerator"/>. /// /// This interface is available in the shared CodeStyle and Workspaces layer to allow /// sharing internal generator methods between them. Once the methods are ready to be /// made public APIs, they can be moved to <see cref="SyntaxGenerator"/>. /// </summary> internal abstract class SyntaxGeneratorInternal : ILanguageService { internal abstract ISyntaxFacts SyntaxFacts { get; } internal abstract SyntaxTrivia EndOfLine(string text); /// <summary> /// Creates a statement that declares a single local variable with an optional initializer. /// </summary> internal abstract SyntaxNode LocalDeclarationStatement( SyntaxNode type, SyntaxToken identifier, SyntaxNode initializer = null, bool isConst = false); /// <summary> /// Creates a statement that declares a single local variable. /// </summary> internal SyntaxNode LocalDeclarationStatement(SyntaxToken name, SyntaxNode initializer) => LocalDeclarationStatement(null, name, initializer); internal abstract SyntaxNode WithInitializer(SyntaxNode variableDeclarator, SyntaxNode initializer); internal abstract SyntaxNode EqualsValueClause(SyntaxToken operatorToken, SyntaxNode value); internal abstract SyntaxToken Identifier(string identifier); internal abstract SyntaxNode ConditionalAccessExpression(SyntaxNode expression, SyntaxNode whenNotNull); internal abstract SyntaxNode MemberBindingExpression(SyntaxNode name); internal abstract SyntaxNode RefExpression(SyntaxNode expression); /// <summary> /// Wraps with parens. /// </summary> internal abstract SyntaxNode AddParentheses(SyntaxNode expression, bool includeElasticTrivia = true, bool addSimplifierAnnotation = true); /// <summary> /// Creates a statement that can be used to yield a value from an iterator method. /// </summary> /// <param name="expression">An expression that can be yielded.</param> internal abstract SyntaxNode YieldReturnStatement(SyntaxNode expression); /// <summary> /// <see langword="true"/> if the language requires a "TypeExpression" /// (including <see langword="var"/>) to be stated when making a /// <see cref="LocalDeclarationStatement(SyntaxNode, SyntaxToken, SyntaxNode, bool)"/>. /// <see langword="false"/> if the language allows the type node to be entirely elided. /// </summary> internal abstract bool RequiresLocalDeclarationType(); internal abstract SyntaxToken InterpolatedStringTextToken(string content, string value); internal abstract SyntaxNode InterpolatedStringText(SyntaxToken textToken); internal abstract SyntaxNode Interpolation(SyntaxNode syntaxNode); internal abstract SyntaxNode InterpolatedStringExpression(SyntaxToken startToken, IEnumerable<SyntaxNode> content, SyntaxToken endToken); internal abstract SyntaxNode InterpolationAlignmentClause(SyntaxNode alignment); internal abstract SyntaxNode InterpolationFormatClause(string format); internal abstract SyntaxNode TypeParameterList(IEnumerable<string> typeParameterNames); /// <summary> /// Produces an appropriate TypeSyntax for the given <see cref="ITypeSymbol"/>. The <paramref name="typeContext"/> /// flag controls how this should be created depending on if this node is intended for use in a type-only /// context, or an expression-level context. In the former case, both C# and VB will create QualifiedNameSyntax /// nodes for dotted type names, whereas in the latter case both languages will create MemberAccessExpressionSyntax /// nodes. The final stringified result will be the same in both cases. However, the structure of the trees /// will be substantively different, which can impact how the compilation layers analyze the tree and how /// transformational passes affect it. /// </summary> /// <remarks> /// Passing in the right value for <paramref name="typeContext"/> is necessary for correctness and for use /// of compilation (and other) layers in a supported fashion. For example, if a QualifiedTypeSyntax is /// sed in a place the compiler would have parsed out a MemberAccessExpression, then it is undefined behavior /// what will happen if that tree is passed to any other components. /// </remarks> internal abstract SyntaxNode Type(ITypeSymbol typeSymbol, bool typeContext); #region Patterns internal abstract bool SupportsPatterns(ParseOptions options); internal abstract SyntaxNode IsPatternExpression(SyntaxNode expression, SyntaxToken isToken, SyntaxNode pattern); internal abstract SyntaxNode AndPattern(SyntaxNode left, SyntaxNode right); internal abstract SyntaxNode DeclarationPattern(INamedTypeSymbol type, string name); internal abstract SyntaxNode ConstantPattern(SyntaxNode expression); internal abstract SyntaxNode NotPattern(SyntaxNode pattern); internal abstract SyntaxNode OrPattern(SyntaxNode left, SyntaxNode right); internal abstract SyntaxNode ParenthesizedPattern(SyntaxNode pattern); internal abstract SyntaxNode TypePattern(SyntaxNode type); #endregion } }
-1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/CodeFixes/UseImplicitOrExplicitType/UseImplicitTypeCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.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.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.TypeStyle { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseImplicitType), Shared] internal class UseImplicitTypeCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public UseImplicitTypeCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.UseImplicitTypeDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix( new MyCodeAction(c => FixAsync(context.Document, context.Diagnostics.First(), c)), context.Diagnostics); return Task.CompletedTask; } protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var root = editor.OriginalRoot; foreach (var diagnostic in diagnostics) { var typeSyntax = (TypeSyntax)root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true); ReplaceTypeWithVar(editor, typeSyntax); } return Task.CompletedTask; } internal static void ReplaceTypeWithVar(SyntaxEditor editor, TypeSyntax type) { type = type.StripRefIfNeeded(); var implicitType = SyntaxFactory.IdentifierName("var") .WithTriviaFrom(type); editor.ReplaceNode(type, implicitType); } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpAnalyzersResources.use_var_instead_of_explicit_type, createChangedDocument, CSharpAnalyzersResources.use_var_instead_of_explicit_type) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.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.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.TypeStyle { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseImplicitType), Shared] internal class UseImplicitTypeCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public UseImplicitTypeCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.UseImplicitTypeDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix( new MyCodeAction(c => FixAsync(context.Document, context.Diagnostics.First(), c)), context.Diagnostics); return Task.CompletedTask; } protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var root = editor.OriginalRoot; foreach (var diagnostic in diagnostics) { var typeSyntax = (TypeSyntax)root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true); ReplaceTypeWithVar(editor, typeSyntax); } return Task.CompletedTask; } internal static void ReplaceTypeWithVar(SyntaxEditor editor, TypeSyntax type) { type = type.StripRefIfNeeded(); var implicitType = SyntaxFactory.IdentifierName("var") .WithTriviaFrom(type); editor.ReplaceNode(type, implicitType); } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpAnalyzersResources.use_var_instead_of_explicit_type, createChangedDocument, CSharpAnalyzersResources.use_var_instead_of_explicit_type) { } } } }
-1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/MetadataReference/AssemblyIdentityParts.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 { [Flags] public enum AssemblyIdentityParts { Name = 1, Version = VersionMajor | VersionMinor | VersionBuild | VersionRevision, // version parts are assumed to be in order: VersionMajor = 1 << 1, VersionMinor = 1 << 2, VersionBuild = 1 << 3, VersionRevision = 1 << 4, Culture = 1 << 5, PublicKey = 1 << 6, PublicKeyToken = 1 << 7, PublicKeyOrToken = PublicKey | PublicKeyToken, Retargetability = 1 << 8, ContentType = 1 << 9, Unknown = 1 << 10 } }
// Licensed to the .NET Foundation under one or more 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 { [Flags] public enum AssemblyIdentityParts { Name = 1, Version = VersionMajor | VersionMinor | VersionBuild | VersionRevision, // version parts are assumed to be in order: VersionMajor = 1 << 1, VersionMinor = 1 << 2, VersionBuild = 1 << 3, VersionRevision = 1 << 4, Culture = 1 << 5, PublicKey = 1 << 6, PublicKeyToken = 1 << 7, PublicKeyOrToken = PublicKey | PublicKeyToken, Retargetability = 1 << 8, ContentType = 1 << 9, Unknown = 1 << 10 } }
-1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/Syntax/InternalSyntax/SyntaxList.WithThreeChildren.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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Syntax.InternalSyntax { internal partial class SyntaxList { internal class WithThreeChildren : SyntaxList { static WithThreeChildren() { ObjectBinder.RegisterTypeReader(typeof(WithThreeChildren), r => new WithThreeChildren(r)); } private readonly GreenNode _child0; private readonly GreenNode _child1; private readonly GreenNode _child2; internal WithThreeChildren(GreenNode child0, GreenNode child1, GreenNode child2) { this.SlotCount = 3; this.AdjustFlagsAndWidth(child0); _child0 = child0; this.AdjustFlagsAndWidth(child1); _child1 = child1; this.AdjustFlagsAndWidth(child2); _child2 = child2; } internal WithThreeChildren(DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations, GreenNode child0, GreenNode child1, GreenNode child2) : base(diagnostics, annotations) { this.SlotCount = 3; this.AdjustFlagsAndWidth(child0); _child0 = child0; this.AdjustFlagsAndWidth(child1); _child1 = child1; this.AdjustFlagsAndWidth(child2); _child2 = child2; } internal WithThreeChildren(ObjectReader reader) : base(reader) { this.SlotCount = 3; _child0 = (GreenNode)reader.ReadValue(); this.AdjustFlagsAndWidth(_child0); _child1 = (GreenNode)reader.ReadValue(); this.AdjustFlagsAndWidth(_child1); _child2 = (GreenNode)reader.ReadValue(); this.AdjustFlagsAndWidth(_child2); } internal override void WriteTo(ObjectWriter writer) { base.WriteTo(writer); writer.WriteValue(_child0); writer.WriteValue(_child1); writer.WriteValue(_child2); } internal override GreenNode? GetSlot(int index) { switch (index) { case 0: return _child0; case 1: return _child1; case 2: return _child2; default: return null; } } internal override void CopyTo(ArrayElement<GreenNode>[] array, int offset) { array[offset].Value = _child0; array[offset + 1].Value = _child1; array[offset + 2].Value = _child2; } internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) { return new Syntax.SyntaxList.WithThreeChildren(this, parent, position); } internal override GreenNode SetDiagnostics(DiagnosticInfo[]? errors) { return new WithThreeChildren(errors, this.GetAnnotations(), _child0, _child1, _child2); } internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) { return new WithThreeChildren(GetDiagnostics(), annotations, _child0, _child1, _child2); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Syntax.InternalSyntax { internal partial class SyntaxList { internal class WithThreeChildren : SyntaxList { static WithThreeChildren() { ObjectBinder.RegisterTypeReader(typeof(WithThreeChildren), r => new WithThreeChildren(r)); } private readonly GreenNode _child0; private readonly GreenNode _child1; private readonly GreenNode _child2; internal WithThreeChildren(GreenNode child0, GreenNode child1, GreenNode child2) { this.SlotCount = 3; this.AdjustFlagsAndWidth(child0); _child0 = child0; this.AdjustFlagsAndWidth(child1); _child1 = child1; this.AdjustFlagsAndWidth(child2); _child2 = child2; } internal WithThreeChildren(DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations, GreenNode child0, GreenNode child1, GreenNode child2) : base(diagnostics, annotations) { this.SlotCount = 3; this.AdjustFlagsAndWidth(child0); _child0 = child0; this.AdjustFlagsAndWidth(child1); _child1 = child1; this.AdjustFlagsAndWidth(child2); _child2 = child2; } internal WithThreeChildren(ObjectReader reader) : base(reader) { this.SlotCount = 3; _child0 = (GreenNode)reader.ReadValue(); this.AdjustFlagsAndWidth(_child0); _child1 = (GreenNode)reader.ReadValue(); this.AdjustFlagsAndWidth(_child1); _child2 = (GreenNode)reader.ReadValue(); this.AdjustFlagsAndWidth(_child2); } internal override void WriteTo(ObjectWriter writer) { base.WriteTo(writer); writer.WriteValue(_child0); writer.WriteValue(_child1); writer.WriteValue(_child2); } internal override GreenNode? GetSlot(int index) { switch (index) { case 0: return _child0; case 1: return _child1; case 2: return _child2; default: return null; } } internal override void CopyTo(ArrayElement<GreenNode>[] array, int offset) { array[offset].Value = _child0; array[offset + 1].Value = _child1; array[offset + 2].Value = _child2; } internal override SyntaxNode CreateRed(SyntaxNode? parent, int position) { return new Syntax.SyntaxList.WithThreeChildren(this, parent, position); } internal override GreenNode SetDiagnostics(DiagnosticInfo[]? errors) { return new WithThreeChildren(errors, this.GetAnnotations(), _child0, _child1, _child2); } internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations) { return new WithThreeChildren(GetDiagnostics(), annotations, _child0, _child1, _child2); } } } }
-1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/DocumentationComments/TypeDocumentationCommentTests.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 Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class TypeDocumentationCommentTests : CSharpTestBase { private readonly CSharpCompilation _compilation; private readonly NamespaceSymbol _acmeNamespace; private readonly NamedTypeSymbol _widgetClass; public TypeDocumentationCommentTests() { _compilation = CreateCompilationWithMscorlib40AndDocumentationComments(@"enum Color { Red, Blue, Green } namespace Acme { interface IProcess {...} struct ValueType {...} class Widget: IProcess { /// <summary> /// Hello! Nested Class. /// </summary> public class NestedClass {...} public interface IMenuItem {...} public delegate void Del(int i); public enum Direction { North, South, East, West } } class MyList<T> { class Helper<U,V> {...} } }"); _acmeNamespace = (NamespaceSymbol)_compilation.GlobalNamespace.GetMembers("Acme").Single(); _widgetClass = _acmeNamespace.GetTypeMembers("Widget").Single(); } [Fact] public void TestEnum() { Assert.Equal("T:Color", _compilation.GlobalNamespace.GetTypeMembers("Color").Single().GetDocumentationCommentId()); } [Fact] public void TestInterface() { Assert.Equal("T:Acme.IProcess", _acmeNamespace.GetTypeMembers("IProcess").Single().GetDocumentationCommentId()); } [Fact] public void TestStruct() { Assert.Equal("T:Acme.ValueType", _acmeNamespace.GetTypeMembers("ValueType").Single().GetDocumentationCommentId()); } [Fact] public void TestClass() { Assert.Equal("T:Acme.Widget", _widgetClass.GetDocumentationCommentId()); } [Fact] public void TestNestedClass() { var classSymbol = _widgetClass.GetTypeMembers("NestedClass").Single(); Assert.Equal("T:Acme.Widget.NestedClass", classSymbol.GetDocumentationCommentId()); Assert.Equal( @"<member name=""T:Acme.Widget.NestedClass""> <summary> Hello! Nested Class. </summary> </member> ", classSymbol.GetDocumentationCommentXml()); } [Fact] public void TestNestedInterface() { Assert.Equal("T:Acme.Widget.IMenuItem", _widgetClass.GetMembers("IMenuItem").Single().GetDocumentationCommentId()); } [Fact] public void TestNestedDelegate() { Assert.Equal("T:Acme.Widget.Del", _widgetClass.GetTypeMembers("Del").Single().GetDocumentationCommentId()); } [Fact] public void TestNestedEnum() { Assert.Equal("T:Acme.Widget.Direction", _widgetClass.GetTypeMembers("Direction").Single().GetDocumentationCommentId()); } [Fact] public void TestGenericType() { Assert.Equal("T:Acme.MyList`1", _acmeNamespace.GetTypeMembers("MyList", 1).Single().GetDocumentationCommentId()); } [Fact] public void TestNestedGenericType() { Assert.Equal("T:Acme.MyList`1.Helper`2", _acmeNamespace.GetTypeMembers("MyList", 1).Single() .GetTypeMembers("Helper", 2).Single().GetDocumentationCommentId()); } [Fact] public void TestDynamicType() { Assert.Null(DynamicTypeSymbol.Instance.GetDocumentationCommentId()); } [WorkItem(536957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536957")] [Fact] public void TestCommentsWithQuestionMarks() { var text = @" /// <doc><?pi ?></doc> /// <d><?pi some data ? > <??></d> /// <a></a><?pi data?> /// <do><?pi x /// y?></do> class A { } "; var comp = CreateCompilation(text); Assert.Equal(0, comp.GetDiagnostics().Count()); } } }
// Licensed to the .NET Foundation under one or more 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 Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class TypeDocumentationCommentTests : CSharpTestBase { private readonly CSharpCompilation _compilation; private readonly NamespaceSymbol _acmeNamespace; private readonly NamedTypeSymbol _widgetClass; public TypeDocumentationCommentTests() { _compilation = CreateCompilationWithMscorlib40AndDocumentationComments(@"enum Color { Red, Blue, Green } namespace Acme { interface IProcess {...} struct ValueType {...} class Widget: IProcess { /// <summary> /// Hello! Nested Class. /// </summary> public class NestedClass {...} public interface IMenuItem {...} public delegate void Del(int i); public enum Direction { North, South, East, West } } class MyList<T> { class Helper<U,V> {...} } }"); _acmeNamespace = (NamespaceSymbol)_compilation.GlobalNamespace.GetMembers("Acme").Single(); _widgetClass = _acmeNamespace.GetTypeMembers("Widget").Single(); } [Fact] public void TestEnum() { Assert.Equal("T:Color", _compilation.GlobalNamespace.GetTypeMembers("Color").Single().GetDocumentationCommentId()); } [Fact] public void TestInterface() { Assert.Equal("T:Acme.IProcess", _acmeNamespace.GetTypeMembers("IProcess").Single().GetDocumentationCommentId()); } [Fact] public void TestStruct() { Assert.Equal("T:Acme.ValueType", _acmeNamespace.GetTypeMembers("ValueType").Single().GetDocumentationCommentId()); } [Fact] public void TestClass() { Assert.Equal("T:Acme.Widget", _widgetClass.GetDocumentationCommentId()); } [Fact] public void TestNestedClass() { var classSymbol = _widgetClass.GetTypeMembers("NestedClass").Single(); Assert.Equal("T:Acme.Widget.NestedClass", classSymbol.GetDocumentationCommentId()); Assert.Equal( @"<member name=""T:Acme.Widget.NestedClass""> <summary> Hello! Nested Class. </summary> </member> ", classSymbol.GetDocumentationCommentXml()); } [Fact] public void TestNestedInterface() { Assert.Equal("T:Acme.Widget.IMenuItem", _widgetClass.GetMembers("IMenuItem").Single().GetDocumentationCommentId()); } [Fact] public void TestNestedDelegate() { Assert.Equal("T:Acme.Widget.Del", _widgetClass.GetTypeMembers("Del").Single().GetDocumentationCommentId()); } [Fact] public void TestNestedEnum() { Assert.Equal("T:Acme.Widget.Direction", _widgetClass.GetTypeMembers("Direction").Single().GetDocumentationCommentId()); } [Fact] public void TestGenericType() { Assert.Equal("T:Acme.MyList`1", _acmeNamespace.GetTypeMembers("MyList", 1).Single().GetDocumentationCommentId()); } [Fact] public void TestNestedGenericType() { Assert.Equal("T:Acme.MyList`1.Helper`2", _acmeNamespace.GetTypeMembers("MyList", 1).Single() .GetTypeMembers("Helper", 2).Single().GetDocumentationCommentId()); } [Fact] public void TestDynamicType() { Assert.Null(DynamicTypeSymbol.Instance.GetDocumentationCommentId()); } [WorkItem(536957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536957")] [Fact] public void TestCommentsWithQuestionMarks() { var text = @" /// <doc><?pi ?></doc> /// <d><?pi some data ? > <??></d> /// <a></a><?pi data?> /// <do><?pi x /// y?></do> class A { } "; var comp = CreateCompilation(text); Assert.Equal(0, comp.GetDiagnostics().Count()); } } }
-1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/EditorConfigSettings/Formatting/ViewModel/TabSizeViewModelFactory.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; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Formatting.ViewModel { [Export(typeof(IEnumSettingViewModelFactory)), Shared] internal class TabSizeViewModelFactory : IEnumSettingViewModelFactory { private readonly OptionKey2 _key; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TabSizeViewModelFactory() { _key = new OptionKey2(FormattingOptions2.TabSize, LanguageNames.CSharp); } public IEnumSettingViewModel CreateViewModel(FormattingSetting setting) { return new TabSizeViewModel(setting); } public bool IsSupported(OptionKey2 key) => _key == key; } }
// Licensed to the .NET Foundation under one or more 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; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Formatting.ViewModel { [Export(typeof(IEnumSettingViewModelFactory)), Shared] internal class TabSizeViewModelFactory : IEnumSettingViewModelFactory { private readonly OptionKey2 _key; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TabSizeViewModelFactory() { _key = new OptionKey2(FormattingOptions2.TabSize, LanguageNames.CSharp); } public IEnumSettingViewModel CreateViewModel(FormattingSetting setting) { return new TabSizeViewModel(setting); } public bool IsSupported(OptionKey2 key) => _key == key; } }
-1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/Completion/KeywordRecommenders/NotnullKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class NotNullKeywordRecommender : IKeywordRecommender<CSharpSyntaxContext> { public ImmutableArray<RecommendedKeyword> RecommendKeywords(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.SyntaxTree.IsTypeParameterConstraintContext(position, context.LeftToken) ? ImmutableArray.Create(new RecommendedKeyword("notnull")) : ImmutableArray<RecommendedKeyword>.Empty; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class NotNullKeywordRecommender : IKeywordRecommender<CSharpSyntaxContext> { public ImmutableArray<RecommendedKeyword> RecommendKeywords(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.SyntaxTree.IsTypeParameterConstraintContext(position, context.LeftToken) ? ImmutableArray.Create(new RecommendedKeyword("notnull")) : ImmutableArray<RecommendedKeyword>.Empty; } } }
-1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/GenerateMember/GenerateVariable/AbstractGenerateVariableService.State.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; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateVariable { internal abstract partial class AbstractGenerateVariableService<TService, TSimpleNameSyntax, TExpressionSyntax> { private partial class State { public INamedTypeSymbol ContainingType { get; private set; } public INamedTypeSymbol TypeToGenerateIn { get; private set; } public IMethodSymbol ContainingMethod { get; private set; } public bool IsStatic { get; private set; } public bool IsConstant { get; private set; } public bool IsIndexer { get; private set; } public bool IsContainedInUnsafeType { get; private set; } public ImmutableArray<IParameterSymbol> Parameters { get; private set; } // Just the name of the method. i.e. "Goo" in "Goo" or "X.Goo" public SyntaxToken IdentifierToken { get; private set; } // The entire expression containing the name. i.e. "X.Goo" public TExpressionSyntax SimpleNameOrMemberAccessExpressionOpt { get; private set; } public ITypeSymbol TypeMemberType { get; private set; } public ITypeSymbol LocalType { get; private set; } public bool OfferReadOnlyFieldFirst { get; private set; } public bool IsWrittenTo { get; private set; } public bool IsOnlyWrittenTo { get; private set; } public bool IsInConstructor { get; private set; } public bool IsInRefContext { get; private set; } public bool IsInInContext { get; private set; } public bool IsInOutContext { get; private set; } public bool IsInMemberContext { get; private set; } public bool IsInExecutableBlock { get; private set; } public bool IsInConditionalAccessExpression { get; private set; } public Location AfterThisLocation { get; private set; } public Location BeforeThisLocation { get; private set; } public static async Task<State> GenerateAsync( TService service, SemanticDocument document, SyntaxNode interfaceNode, CancellationToken cancellationToken) { var state = new State(); if (!await state.TryInitializeAsync(service, document, interfaceNode, cancellationToken).ConfigureAwait(false)) { return null; } return state; } private async Task<bool> TryInitializeAsync( TService service, SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) { if (service.IsIdentifierNameGeneration(node)) { // Cases that we deal with currently: // // 1) expr.Goo // 2) expr->Goo // 3) Goo if (!TryInitializeSimpleName(service, document, (TSimpleNameSyntax)node, cancellationToken)) { return false; } } else if (service.IsExplicitInterfaceGeneration(node)) { // 4) bool IGoo.NewProp if (!TryInitializeExplicitInterface(service, document, node, cancellationToken)) { return false; } } else { return false; } // Ok. It either didn't bind to any symbols, or it bound to a symbol but with // errors. In the former case we definitely want to offer to generate a field. In // the latter case, we want to generate a field *unless* there's an existing member // with the same name. Note: it's ok if there's a method with the same name. var existingMembers = TypeToGenerateIn.GetMembers(IdentifierToken.ValueText) .Where(m => m.Kind != SymbolKind.Method); if (existingMembers.Any()) { // TODO: Code coverage // There was an existing method that the new method would clash with. return false; } if (cancellationToken.IsCancellationRequested) { return false; } TypeToGenerateIn = await SymbolFinder.FindSourceDefinitionAsync(TypeToGenerateIn, document.Project.Solution, cancellationToken).ConfigureAwait(false) as INamedTypeSymbol; if (!ValidateTypeToGenerateIn(TypeToGenerateIn, IsStatic, ClassInterfaceModuleStructTypes)) { return false; } IsContainedInUnsafeType = service.ContainingTypesOrSelfHasUnsafeKeyword(TypeToGenerateIn); return CanGenerateLocal() || CodeGenerator.CanAdd(document.Project.Solution, TypeToGenerateIn, cancellationToken); } internal bool CanGeneratePropertyOrField() { return ContainingType is { IsImplicitClass: false, Name: not WellKnownMemberNames.TopLevelStatementsEntryPointTypeName }; } internal bool CanGenerateLocal() { // !this.IsInMemberContext prevents us offering this fix for `x.goo` where `goo` does not exist return !IsInMemberContext && IsInExecutableBlock; } internal bool CanGenerateParameter() { // !this.IsInMemberContext prevents us offering this fix for `x.goo` where `goo` does not exist // Workaround: The compiler returns IsImplicitlyDeclared = false for <Main>$. return ContainingMethod is { IsImplicitlyDeclared: false, Name: not WellKnownMemberNames.TopLevelStatementsEntryPointMethodName } && !IsInMemberContext && !IsConstant; } private bool TryInitializeExplicitInterface( TService service, SemanticDocument document, SyntaxNode propertyDeclaration, CancellationToken cancellationToken) { if (!service.TryInitializeExplicitInterfaceState( document, propertyDeclaration, cancellationToken, out var identifierToken, out var propertySymbol, out var typeToGenerateIn)) { return false; } IdentifierToken = identifierToken; TypeToGenerateIn = typeToGenerateIn; if (propertySymbol.ExplicitInterfaceImplementations.Any()) { return false; } cancellationToken.ThrowIfCancellationRequested(); var semanticModel = document.SemanticModel; ContainingType = semanticModel.GetEnclosingNamedType(IdentifierToken.SpanStart, cancellationToken); if (ContainingType == null) { return false; } if (!ContainingType.Interfaces.OfType<INamedTypeSymbol>().Contains(TypeToGenerateIn)) { return false; } IsIndexer = propertySymbol.IsIndexer; Parameters = propertySymbol.Parameters; TypeMemberType = propertySymbol.Type; // By default, make it readonly, unless there's already an setter defined. IsWrittenTo = propertySymbol.SetMethod != null; return true; } private bool TryInitializeSimpleName( TService service, SemanticDocument semanticDocument, TSimpleNameSyntax simpleName, CancellationToken cancellationToken) { if (!service.TryInitializeIdentifierNameState( semanticDocument, simpleName, cancellationToken, out var identifierToken, out var simpleNameOrMemberAccessExpression, out var isInExecutableBlock, out var isInConditionalAccessExpression)) { return false; } if (string.IsNullOrWhiteSpace(identifierToken.ValueText)) { return false; } IdentifierToken = identifierToken; SimpleNameOrMemberAccessExpressionOpt = simpleNameOrMemberAccessExpression; IsInExecutableBlock = isInExecutableBlock; IsInConditionalAccessExpression = isInConditionalAccessExpression; // If we're in a type context then we shouldn't offer to generate a field or // property. var syntaxFacts = semanticDocument.Document.GetLanguageService<ISyntaxFactsService>(); if (syntaxFacts.IsInNamespaceOrTypeContext(SimpleNameOrMemberAccessExpressionOpt)) { return false; } IsConstant = syntaxFacts.IsInConstantContext(SimpleNameOrMemberAccessExpressionOpt); // If we're not in a type, don't even bother. NOTE(cyrusn): We'll have to rethink this // for C# Script. cancellationToken.ThrowIfCancellationRequested(); var semanticModel = semanticDocument.SemanticModel; ContainingType = semanticModel.GetEnclosingNamedType(IdentifierToken.SpanStart, cancellationToken); if (ContainingType == null) { return false; } // Now, try to bind the invocation and see if it succeeds or not. if it succeeds and // binds uniquely, then we don't need to offer this quick fix. cancellationToken.ThrowIfCancellationRequested(); var semanticInfo = semanticModel.GetSymbolInfo(SimpleNameOrMemberAccessExpressionOpt, cancellationToken); cancellationToken.ThrowIfCancellationRequested(); if (semanticInfo.Symbol != null) { return false; } // Either we found no matches, or this was ambiguous. Either way, we might be able // to generate a method here. Determine where the user wants to generate the method // into, and if it's valid then proceed. cancellationToken.ThrowIfCancellationRequested(); if (!TryDetermineTypeToGenerateIn(semanticDocument, ContainingType, SimpleNameOrMemberAccessExpressionOpt, cancellationToken, out var typeToGenerateIn, out var isStatic)) { return false; } TypeToGenerateIn = typeToGenerateIn; IsStatic = isStatic; DetermineFieldType(semanticDocument, cancellationToken); var semanticFacts = semanticDocument.Document.GetLanguageService<ISemanticFactsService>(); IsInRefContext = semanticFacts.IsInRefContext(semanticModel, SimpleNameOrMemberAccessExpressionOpt, cancellationToken); IsInInContext = semanticFacts.IsInInContext(semanticModel, SimpleNameOrMemberAccessExpressionOpt, cancellationToken); IsInOutContext = semanticFacts.IsInOutContext(semanticModel, SimpleNameOrMemberAccessExpressionOpt, cancellationToken); IsWrittenTo = semanticFacts.IsWrittenTo(semanticModel, SimpleNameOrMemberAccessExpressionOpt, cancellationToken); IsOnlyWrittenTo = semanticFacts.IsOnlyWrittenTo(semanticModel, SimpleNameOrMemberAccessExpressionOpt, cancellationToken); IsInConstructor = DetermineIsInConstructor(semanticDocument, simpleName); IsInMemberContext = simpleName != SimpleNameOrMemberAccessExpressionOpt || syntaxFacts.IsMemberInitializerNamedAssignmentIdentifier(SimpleNameOrMemberAccessExpressionOpt); ContainingMethod = semanticModel.GetEnclosingSymbol<IMethodSymbol>(IdentifierToken.SpanStart, cancellationToken); CheckSurroundingContext(semanticDocument, SymbolKind.Field, cancellationToken); CheckSurroundingContext(semanticDocument, SymbolKind.Property, cancellationToken); return true; } private void CheckSurroundingContext( SemanticDocument semanticDocument, SymbolKind symbolKind, CancellationToken cancellationToken) { // See if we're being assigned to. If so, look at the before/after statements // to see if either is an assignment. If so, we can use that to try to determine // user patterns that can be used when generating the member. For example, // if the sibling assignment is to a readonly field, then we want to offer to // generate a readonly field vs a writable field. // // Also, because users often like to keep members/assignments in the same order // we can pick a good place for the new member based on the surrounding assignments. var syntaxFacts = semanticDocument.Document.GetLanguageService<ISyntaxFactsService>(); var simpleName = SimpleNameOrMemberAccessExpressionOpt; if (syntaxFacts.IsLeftSideOfAssignment(simpleName)) { var assignmentStatement = simpleName.Ancestors().FirstOrDefault(syntaxFacts.IsSimpleAssignmentStatement); if (assignmentStatement != null) { syntaxFacts.GetPartsOfAssignmentStatement( assignmentStatement, out var left, out var right); if (left == simpleName) { var block = assignmentStatement.Parent; var children = block.ChildNodesAndTokens(); var statementindex = GetStatementIndex(children, assignmentStatement); var previousAssignedSymbol = TryGetAssignedSymbol(semanticDocument, symbolKind, children, statementindex - 1, cancellationToken); var nextAssignedSymbol = TryGetAssignedSymbol(semanticDocument, symbolKind, children, statementindex + 1, cancellationToken); if (symbolKind == SymbolKind.Field) { OfferReadOnlyFieldFirst = FieldIsReadOnly(previousAssignedSymbol) || FieldIsReadOnly(nextAssignedSymbol); } AfterThisLocation ??= previousAssignedSymbol?.Locations.FirstOrDefault(); BeforeThisLocation ??= nextAssignedSymbol?.Locations.FirstOrDefault(); } } } } private ISymbol TryGetAssignedSymbol( SemanticDocument semanticDocument, SymbolKind symbolKind, ChildSyntaxList children, int index, CancellationToken cancellationToken) { var syntaxFacts = semanticDocument.Document.GetLanguageService<ISyntaxFactsService>(); if (index >= 0 && index < children.Count) { var sibling = children[index]; if (sibling.IsNode) { var siblingNode = sibling.AsNode(); if (syntaxFacts.IsSimpleAssignmentStatement(siblingNode)) { syntaxFacts.GetPartsOfAssignmentStatement( siblingNode, out var left, out _); var symbol = semanticDocument.SemanticModel.GetSymbolInfo(left, cancellationToken).Symbol; if (symbol?.Kind == symbolKind && symbol.ContainingType.Equals(ContainingType)) { return symbol; } } } } return null; } private static bool FieldIsReadOnly(ISymbol symbol) => symbol is IFieldSymbol field && field.IsReadOnly; private static int GetStatementIndex(ChildSyntaxList children, SyntaxNode statement) { var index = 0; foreach (var child in children) { if (child == statement) { return index; } index++; } throw ExceptionUtilities.Unreachable; } private void DetermineFieldType( SemanticDocument semanticDocument, CancellationToken cancellationToken) { var typeInference = semanticDocument.Document.GetLanguageService<ITypeInferenceService>(); var inferredType = typeInference.InferType( semanticDocument.SemanticModel, SimpleNameOrMemberAccessExpressionOpt, objectAsDefault: true, name: IdentifierToken.ValueText, cancellationToken: cancellationToken); var compilation = semanticDocument.SemanticModel.Compilation; inferredType = inferredType.SpecialType == SpecialType.System_Void ? compilation.ObjectType : inferredType; if (IsInConditionalAccessExpression) { inferredType = inferredType.RemoveNullableIfPresent(); } if (inferredType.IsDelegateType() && !inferredType.CanBeReferencedByName) { var namedDelegateType = inferredType.GetDelegateType(compilation)?.DelegateInvokeMethod?.ConvertToType(compilation); if (namedDelegateType != null) { inferredType = namedDelegateType; } } // Substitute 'object' for all captured method type parameters. Note: we may need to // do this for things like anonymous types, as well as captured type parameters that // aren't in scope in the destination type. var capturedMethodTypeParameters = inferredType.GetReferencedMethodTypeParameters(); var mapping = capturedMethodTypeParameters.ToDictionary(tp => tp, tp => compilation.ObjectType); TypeMemberType = inferredType.SubstituteTypes(mapping, compilation); var availableTypeParameters = TypeToGenerateIn.GetAllTypeParameters(); TypeMemberType = TypeMemberType.RemoveUnavailableTypeParameters( compilation, availableTypeParameters); var enclosingMethodSymbol = semanticDocument.SemanticModel.GetEnclosingSymbol<IMethodSymbol>(SimpleNameOrMemberAccessExpressionOpt.SpanStart, cancellationToken); if (enclosingMethodSymbol != null && enclosingMethodSymbol.TypeParameters != null && enclosingMethodSymbol.TypeParameters.Length != 0) { using var _ = ArrayBuilder<ITypeParameterSymbol>.GetInstance(out var combinedTypeParameters); combinedTypeParameters.AddRange(availableTypeParameters); combinedTypeParameters.AddRange(enclosingMethodSymbol.TypeParameters); LocalType = inferredType.RemoveUnavailableTypeParameters(compilation, combinedTypeParameters); } else { LocalType = TypeMemberType; } } private bool DetermineIsInConstructor(SemanticDocument semanticDocument, SyntaxNode simpleName) { if (!ContainingType.OriginalDefinition.Equals(TypeToGenerateIn.OriginalDefinition)) return false; // If we're in an lambda/local function we're not actually 'in' the constructor. // i.e. we can't actually write to read-only fields here. var syntaxFacts = semanticDocument.Document.GetRequiredLanguageService<ISyntaxFactsService>(); if (simpleName.AncestorsAndSelf().Any(n => syntaxFacts.IsAnonymousOrLocalFunction(n))) return false; return syntaxFacts.IsInConstructor(simpleName); } } } }
// Licensed to the .NET Foundation under one or more 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; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateVariable { internal abstract partial class AbstractGenerateVariableService<TService, TSimpleNameSyntax, TExpressionSyntax> { private partial class State { public INamedTypeSymbol ContainingType { get; private set; } public INamedTypeSymbol TypeToGenerateIn { get; private set; } public IMethodSymbol ContainingMethod { get; private set; } public bool IsStatic { get; private set; } public bool IsConstant { get; private set; } public bool IsIndexer { get; private set; } public bool IsContainedInUnsafeType { get; private set; } public ImmutableArray<IParameterSymbol> Parameters { get; private set; } // Just the name of the method. i.e. "Goo" in "Goo" or "X.Goo" public SyntaxToken IdentifierToken { get; private set; } // The entire expression containing the name. i.e. "X.Goo" public TExpressionSyntax SimpleNameOrMemberAccessExpressionOpt { get; private set; } public ITypeSymbol TypeMemberType { get; private set; } public ITypeSymbol LocalType { get; private set; } public bool OfferReadOnlyFieldFirst { get; private set; } public bool IsWrittenTo { get; private set; } public bool IsOnlyWrittenTo { get; private set; } public bool IsInConstructor { get; private set; } public bool IsInRefContext { get; private set; } public bool IsInInContext { get; private set; } public bool IsInOutContext { get; private set; } public bool IsInMemberContext { get; private set; } public bool IsInExecutableBlock { get; private set; } public bool IsInConditionalAccessExpression { get; private set; } public Location AfterThisLocation { get; private set; } public Location BeforeThisLocation { get; private set; } public static async Task<State> GenerateAsync( TService service, SemanticDocument document, SyntaxNode interfaceNode, CancellationToken cancellationToken) { var state = new State(); if (!await state.TryInitializeAsync(service, document, interfaceNode, cancellationToken).ConfigureAwait(false)) { return null; } return state; } private async Task<bool> TryInitializeAsync( TService service, SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) { if (service.IsIdentifierNameGeneration(node)) { // Cases that we deal with currently: // // 1) expr.Goo // 2) expr->Goo // 3) Goo if (!TryInitializeSimpleName(service, document, (TSimpleNameSyntax)node, cancellationToken)) { return false; } } else if (service.IsExplicitInterfaceGeneration(node)) { // 4) bool IGoo.NewProp if (!TryInitializeExplicitInterface(service, document, node, cancellationToken)) { return false; } } else { return false; } // Ok. It either didn't bind to any symbols, or it bound to a symbol but with // errors. In the former case we definitely want to offer to generate a field. In // the latter case, we want to generate a field *unless* there's an existing member // with the same name. Note: it's ok if there's a method with the same name. var existingMembers = TypeToGenerateIn.GetMembers(IdentifierToken.ValueText) .Where(m => m.Kind != SymbolKind.Method); if (existingMembers.Any()) { // TODO: Code coverage // There was an existing method that the new method would clash with. return false; } if (cancellationToken.IsCancellationRequested) { return false; } TypeToGenerateIn = await SymbolFinder.FindSourceDefinitionAsync(TypeToGenerateIn, document.Project.Solution, cancellationToken).ConfigureAwait(false) as INamedTypeSymbol; if (!ValidateTypeToGenerateIn(TypeToGenerateIn, IsStatic, ClassInterfaceModuleStructTypes)) { return false; } IsContainedInUnsafeType = service.ContainingTypesOrSelfHasUnsafeKeyword(TypeToGenerateIn); return CanGenerateLocal() || CodeGenerator.CanAdd(document.Project.Solution, TypeToGenerateIn, cancellationToken); } internal bool CanGeneratePropertyOrField() { return ContainingType is { IsImplicitClass: false, Name: not WellKnownMemberNames.TopLevelStatementsEntryPointTypeName }; } internal bool CanGenerateLocal() { // !this.IsInMemberContext prevents us offering this fix for `x.goo` where `goo` does not exist return !IsInMemberContext && IsInExecutableBlock; } internal bool CanGenerateParameter() { // !this.IsInMemberContext prevents us offering this fix for `x.goo` where `goo` does not exist // Workaround: The compiler returns IsImplicitlyDeclared = false for <Main>$. return ContainingMethod is { IsImplicitlyDeclared: false, Name: not WellKnownMemberNames.TopLevelStatementsEntryPointMethodName } && !IsInMemberContext && !IsConstant; } private bool TryInitializeExplicitInterface( TService service, SemanticDocument document, SyntaxNode propertyDeclaration, CancellationToken cancellationToken) { if (!service.TryInitializeExplicitInterfaceState( document, propertyDeclaration, cancellationToken, out var identifierToken, out var propertySymbol, out var typeToGenerateIn)) { return false; } IdentifierToken = identifierToken; TypeToGenerateIn = typeToGenerateIn; if (propertySymbol.ExplicitInterfaceImplementations.Any()) { return false; } cancellationToken.ThrowIfCancellationRequested(); var semanticModel = document.SemanticModel; ContainingType = semanticModel.GetEnclosingNamedType(IdentifierToken.SpanStart, cancellationToken); if (ContainingType == null) { return false; } if (!ContainingType.Interfaces.OfType<INamedTypeSymbol>().Contains(TypeToGenerateIn)) { return false; } IsIndexer = propertySymbol.IsIndexer; Parameters = propertySymbol.Parameters; TypeMemberType = propertySymbol.Type; // By default, make it readonly, unless there's already an setter defined. IsWrittenTo = propertySymbol.SetMethod != null; return true; } private bool TryInitializeSimpleName( TService service, SemanticDocument semanticDocument, TSimpleNameSyntax simpleName, CancellationToken cancellationToken) { if (!service.TryInitializeIdentifierNameState( semanticDocument, simpleName, cancellationToken, out var identifierToken, out var simpleNameOrMemberAccessExpression, out var isInExecutableBlock, out var isInConditionalAccessExpression)) { return false; } if (string.IsNullOrWhiteSpace(identifierToken.ValueText)) { return false; } IdentifierToken = identifierToken; SimpleNameOrMemberAccessExpressionOpt = simpleNameOrMemberAccessExpression; IsInExecutableBlock = isInExecutableBlock; IsInConditionalAccessExpression = isInConditionalAccessExpression; // If we're in a type context then we shouldn't offer to generate a field or // property. var syntaxFacts = semanticDocument.Document.GetLanguageService<ISyntaxFactsService>(); if (syntaxFacts.IsInNamespaceOrTypeContext(SimpleNameOrMemberAccessExpressionOpt)) { return false; } IsConstant = syntaxFacts.IsInConstantContext(SimpleNameOrMemberAccessExpressionOpt); // If we're not in a type, don't even bother. NOTE(cyrusn): We'll have to rethink this // for C# Script. cancellationToken.ThrowIfCancellationRequested(); var semanticModel = semanticDocument.SemanticModel; ContainingType = semanticModel.GetEnclosingNamedType(IdentifierToken.SpanStart, cancellationToken); if (ContainingType == null) { return false; } // Now, try to bind the invocation and see if it succeeds or not. if it succeeds and // binds uniquely, then we don't need to offer this quick fix. cancellationToken.ThrowIfCancellationRequested(); var semanticInfo = semanticModel.GetSymbolInfo(SimpleNameOrMemberAccessExpressionOpt, cancellationToken); cancellationToken.ThrowIfCancellationRequested(); if (semanticInfo.Symbol != null) { return false; } // Either we found no matches, or this was ambiguous. Either way, we might be able // to generate a method here. Determine where the user wants to generate the method // into, and if it's valid then proceed. cancellationToken.ThrowIfCancellationRequested(); if (!TryDetermineTypeToGenerateIn(semanticDocument, ContainingType, SimpleNameOrMemberAccessExpressionOpt, cancellationToken, out var typeToGenerateIn, out var isStatic)) { return false; } TypeToGenerateIn = typeToGenerateIn; IsStatic = isStatic; DetermineFieldType(semanticDocument, cancellationToken); var semanticFacts = semanticDocument.Document.GetLanguageService<ISemanticFactsService>(); IsInRefContext = semanticFacts.IsInRefContext(semanticModel, SimpleNameOrMemberAccessExpressionOpt, cancellationToken); IsInInContext = semanticFacts.IsInInContext(semanticModel, SimpleNameOrMemberAccessExpressionOpt, cancellationToken); IsInOutContext = semanticFacts.IsInOutContext(semanticModel, SimpleNameOrMemberAccessExpressionOpt, cancellationToken); IsWrittenTo = semanticFacts.IsWrittenTo(semanticModel, SimpleNameOrMemberAccessExpressionOpt, cancellationToken); IsOnlyWrittenTo = semanticFacts.IsOnlyWrittenTo(semanticModel, SimpleNameOrMemberAccessExpressionOpt, cancellationToken); IsInConstructor = DetermineIsInConstructor(semanticDocument, simpleName); IsInMemberContext = simpleName != SimpleNameOrMemberAccessExpressionOpt || syntaxFacts.IsMemberInitializerNamedAssignmentIdentifier(SimpleNameOrMemberAccessExpressionOpt); ContainingMethod = semanticModel.GetEnclosingSymbol<IMethodSymbol>(IdentifierToken.SpanStart, cancellationToken); CheckSurroundingContext(semanticDocument, SymbolKind.Field, cancellationToken); CheckSurroundingContext(semanticDocument, SymbolKind.Property, cancellationToken); return true; } private void CheckSurroundingContext( SemanticDocument semanticDocument, SymbolKind symbolKind, CancellationToken cancellationToken) { // See if we're being assigned to. If so, look at the before/after statements // to see if either is an assignment. If so, we can use that to try to determine // user patterns that can be used when generating the member. For example, // if the sibling assignment is to a readonly field, then we want to offer to // generate a readonly field vs a writable field. // // Also, because users often like to keep members/assignments in the same order // we can pick a good place for the new member based on the surrounding assignments. var syntaxFacts = semanticDocument.Document.GetLanguageService<ISyntaxFactsService>(); var simpleName = SimpleNameOrMemberAccessExpressionOpt; if (syntaxFacts.IsLeftSideOfAssignment(simpleName)) { var assignmentStatement = simpleName.Ancestors().FirstOrDefault(syntaxFacts.IsSimpleAssignmentStatement); if (assignmentStatement != null) { syntaxFacts.GetPartsOfAssignmentStatement( assignmentStatement, out var left, out var right); if (left == simpleName) { var block = assignmentStatement.Parent; var children = block.ChildNodesAndTokens(); var statementindex = GetStatementIndex(children, assignmentStatement); var previousAssignedSymbol = TryGetAssignedSymbol(semanticDocument, symbolKind, children, statementindex - 1, cancellationToken); var nextAssignedSymbol = TryGetAssignedSymbol(semanticDocument, symbolKind, children, statementindex + 1, cancellationToken); if (symbolKind == SymbolKind.Field) { OfferReadOnlyFieldFirst = FieldIsReadOnly(previousAssignedSymbol) || FieldIsReadOnly(nextAssignedSymbol); } AfterThisLocation ??= previousAssignedSymbol?.Locations.FirstOrDefault(); BeforeThisLocation ??= nextAssignedSymbol?.Locations.FirstOrDefault(); } } } } private ISymbol TryGetAssignedSymbol( SemanticDocument semanticDocument, SymbolKind symbolKind, ChildSyntaxList children, int index, CancellationToken cancellationToken) { var syntaxFacts = semanticDocument.Document.GetLanguageService<ISyntaxFactsService>(); if (index >= 0 && index < children.Count) { var sibling = children[index]; if (sibling.IsNode) { var siblingNode = sibling.AsNode(); if (syntaxFacts.IsSimpleAssignmentStatement(siblingNode)) { syntaxFacts.GetPartsOfAssignmentStatement( siblingNode, out var left, out _); var symbol = semanticDocument.SemanticModel.GetSymbolInfo(left, cancellationToken).Symbol; if (symbol?.Kind == symbolKind && symbol.ContainingType.Equals(ContainingType)) { return symbol; } } } } return null; } private static bool FieldIsReadOnly(ISymbol symbol) => symbol is IFieldSymbol field && field.IsReadOnly; private static int GetStatementIndex(ChildSyntaxList children, SyntaxNode statement) { var index = 0; foreach (var child in children) { if (child == statement) { return index; } index++; } throw ExceptionUtilities.Unreachable; } private void DetermineFieldType( SemanticDocument semanticDocument, CancellationToken cancellationToken) { var typeInference = semanticDocument.Document.GetLanguageService<ITypeInferenceService>(); var inferredType = typeInference.InferType( semanticDocument.SemanticModel, SimpleNameOrMemberAccessExpressionOpt, objectAsDefault: true, name: IdentifierToken.ValueText, cancellationToken: cancellationToken); var compilation = semanticDocument.SemanticModel.Compilation; inferredType = inferredType.SpecialType == SpecialType.System_Void ? compilation.ObjectType : inferredType; if (IsInConditionalAccessExpression) { inferredType = inferredType.RemoveNullableIfPresent(); } if (inferredType.IsDelegateType() && !inferredType.CanBeReferencedByName) { var namedDelegateType = inferredType.GetDelegateType(compilation)?.DelegateInvokeMethod?.ConvertToType(compilation); if (namedDelegateType != null) { inferredType = namedDelegateType; } } // Substitute 'object' for all captured method type parameters. Note: we may need to // do this for things like anonymous types, as well as captured type parameters that // aren't in scope in the destination type. var capturedMethodTypeParameters = inferredType.GetReferencedMethodTypeParameters(); var mapping = capturedMethodTypeParameters.ToDictionary(tp => tp, tp => compilation.ObjectType); TypeMemberType = inferredType.SubstituteTypes(mapping, compilation); var availableTypeParameters = TypeToGenerateIn.GetAllTypeParameters(); TypeMemberType = TypeMemberType.RemoveUnavailableTypeParameters( compilation, availableTypeParameters); var enclosingMethodSymbol = semanticDocument.SemanticModel.GetEnclosingSymbol<IMethodSymbol>(SimpleNameOrMemberAccessExpressionOpt.SpanStart, cancellationToken); if (enclosingMethodSymbol != null && enclosingMethodSymbol.TypeParameters != null && enclosingMethodSymbol.TypeParameters.Length != 0) { using var _ = ArrayBuilder<ITypeParameterSymbol>.GetInstance(out var combinedTypeParameters); combinedTypeParameters.AddRange(availableTypeParameters); combinedTypeParameters.AddRange(enclosingMethodSymbol.TypeParameters); LocalType = inferredType.RemoveUnavailableTypeParameters(compilation, combinedTypeParameters); } else { LocalType = TypeMemberType; } } private bool DetermineIsInConstructor(SemanticDocument semanticDocument, SyntaxNode simpleName) { if (!ContainingType.OriginalDefinition.Equals(TypeToGenerateIn.OriginalDefinition)) return false; // If we're in an lambda/local function we're not actually 'in' the constructor. // i.e. we can't actually write to read-only fields here. var syntaxFacts = semanticDocument.Document.GetRequiredLanguageService<ISyntaxFactsService>(); if (simpleName.AncestorsAndSelf().Any(n => syntaxFacts.IsAnonymousOrLocalFunction(n))) return false; return syntaxFacts.IsInConstructor(simpleName); } } } }
-1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/Implementation/CommentSelection/AbstractCommentSelectionBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommentSelection; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; 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.Operations; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.CommentSelection { internal enum Operation { /// <summary> /// The operation is a comment action. /// </summary> Comment, /// <summary> /// The operation is an uncomment action. /// </summary> Uncomment } internal abstract class AbstractCommentSelectionBase<TCommand> { protected const string LanguageNameString = "languagename"; protected const string LengthString = "length"; private readonly ITextUndoHistoryRegistry _undoHistoryRegistry; private readonly IEditorOperationsFactoryService _editorOperationsFactoryService; internal AbstractCommentSelectionBase( ITextUndoHistoryRegistry undoHistoryRegistry, IEditorOperationsFactoryService editorOperationsFactoryService) { Contract.ThrowIfNull(undoHistoryRegistry); Contract.ThrowIfNull(editorOperationsFactoryService); _undoHistoryRegistry = undoHistoryRegistry; _editorOperationsFactoryService = editorOperationsFactoryService; } public abstract string DisplayName { get; } protected abstract string GetTitle(TCommand command); protected abstract string GetMessage(TCommand command); // Internal as tests currently rely on this method. internal abstract Task<CommentSelectionResult> CollectEditsAsync( Document document, ICommentSelectionService service, ITextBuffer textBuffer, NormalizedSnapshotSpanCollection selectedSpans, TCommand command, CancellationToken cancellationToken); protected static CommandState GetCommandState(ITextBuffer buffer) { return buffer.CanApplyChangeDocumentToWorkspace() ? CommandState.Available : CommandState.Unspecified; } protected static void InsertText(ArrayBuilder<TextChange> textChanges, int position, string text) => textChanges.Add(new TextChange(new TextSpan(position, 0), text)); protected static void DeleteText(ArrayBuilder<TextChange> textChanges, TextSpan span) => textChanges.Add(new TextChange(span, string.Empty)); internal bool ExecuteCommand(ITextView textView, ITextBuffer subjectBuffer, TCommand command, CommandExecutionContext context) { var title = GetTitle(command); var message = GetMessage(command); using (context.OperationContext.AddScope(allowCancellation: true, message)) { var cancellationToken = context.OperationContext.UserCancellationToken; var selectedSpans = textView.Selection.GetSnapshotSpansOnBuffer(subjectBuffer); if (selectedSpans.IsEmpty()) { return true; } var document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return true; } var service = document.GetLanguageService<ICommentSelectionService>(); if (service == null) { return true; } var edits = CollectEditsAsync(document, service, subjectBuffer, selectedSpans, command, cancellationToken).WaitAndGetResult(cancellationToken); ApplyEdits(document, textView, subjectBuffer, service, title, edits); } return true; } /// <summary> /// Applies the requested edits and sets the selection. /// This operation is not cancellable. /// </summary> private void ApplyEdits(Document document, ITextView textView, ITextBuffer subjectBuffer, ICommentSelectionService service, string title, CommentSelectionResult edits) { // Create tracking spans to track the text changes. var currentSnapshot = subjectBuffer.CurrentSnapshot; var trackingSpans = edits.TrackingSpans .SelectAsArray(textSpan => (originalSpan: textSpan, trackingSpan: CreateTrackingSpan(edits.ResultOperation, currentSnapshot, textSpan.TrackingTextSpan))); // Apply the text changes. using (var transaction = new CaretPreservingEditTransaction(title, textView, _undoHistoryRegistry, _editorOperationsFactoryService)) { document.Project.Solution.Workspace.ApplyTextChanges(document.Id, edits.TextChanges.Distinct(), CancellationToken.None); transaction.Complete(); } // Convert the tracking spans into snapshot spans for formatting and selection. var trackingSnapshotSpans = trackingSpans.Select(s => CreateSnapshotSpan(subjectBuffer.CurrentSnapshot, s.trackingSpan, s.originalSpan)); if (trackingSnapshotSpans.Any()) { if (edits.ResultOperation == Operation.Uncomment) { // Format the document only during uncomment operations. Use second transaction so it can be undone. using var transaction = new CaretPreservingEditTransaction(title, textView, _undoHistoryRegistry, _editorOperationsFactoryService); var formattedDocument = Format(service, subjectBuffer.CurrentSnapshot, trackingSnapshotSpans, CancellationToken.None); if (formattedDocument != null) { formattedDocument.Project.Solution.Workspace.ApplyDocumentChanges(formattedDocument, CancellationToken.None); transaction.Complete(); } } // Set the multi selection after edits have been applied. textView.SetMultiSelection(trackingSnapshotSpans); } } /// <summary> /// Creates a tracking span for the operation. /// Internal for tests. /// </summary> internal static ITrackingSpan CreateTrackingSpan(Operation operation, ITextSnapshot snapshot, TextSpan textSpan) { // If a comment is being added, the tracking span must include changes at the edge. var spanTrackingMode = operation == Operation.Comment ? SpanTrackingMode.EdgeInclusive : SpanTrackingMode.EdgeExclusive; return snapshot.CreateTrackingSpan(Span.FromBounds(textSpan.Start, textSpan.End), spanTrackingMode); } /// <summary> /// Retrieves the snapshot span from a post edited tracking span. /// Additionally applies any extra modifications to the tracking span post edit. /// </summary> private static SnapshotSpan CreateSnapshotSpan(ITextSnapshot snapshot, ITrackingSpan trackingSpan, CommentTrackingSpan originalSpan) { var snapshotSpan = trackingSpan.GetSpan(snapshot); if (originalSpan.HasPostApplyChanges()) { var updatedStart = snapshotSpan.Start.Position + originalSpan.AmountToAddToTrackingSpanStart; var updatedEnd = snapshotSpan.End.Position + originalSpan.AmountToAddToTrackingSpanEnd; if (updatedStart >= snapshotSpan.Start.Position && updatedEnd <= snapshotSpan.End.Position) { snapshotSpan = new SnapshotSpan(snapshot, Span.FromBounds(updatedStart, updatedEnd)); } } return snapshotSpan; } private static Document Format(ICommentSelectionService service, ITextSnapshot snapshot, IEnumerable<SnapshotSpan> changes, CancellationToken cancellationToken) { var document = snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return null; } var textSpans = changes.SelectAsArray(change => change.Span.ToTextSpan()); return service.FormatAsync(document, textSpans, cancellationToken).WaitAndGetResult(cancellationToken); } /// <summary> /// Given a set of lines, find the minimum indent of all of the non-blank, non-whitespace lines. /// </summary> protected static int DetermineSmallestIndent( SnapshotSpan span, ITextSnapshotLine firstLine, ITextSnapshotLine lastLine) { // TODO: This breaks if you have mixed tabs/spaces, and/or tabsize != indentsize. var indentToCommentAt = int.MaxValue; for (var lineNumber = firstLine.LineNumber; lineNumber <= lastLine.LineNumber; ++lineNumber) { var line = span.Snapshot.GetLineFromLineNumber(lineNumber); var firstNonWhitespacePosition = line.GetFirstNonWhitespacePosition(); var firstNonWhitespaceOnLine = firstNonWhitespacePosition.HasValue ? firstNonWhitespacePosition.Value - line.Start : int.MaxValue; indentToCommentAt = Math.Min(indentToCommentAt, firstNonWhitespaceOnLine); } return indentToCommentAt; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommentSelection; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; 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.Operations; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.CommentSelection { internal enum Operation { /// <summary> /// The operation is a comment action. /// </summary> Comment, /// <summary> /// The operation is an uncomment action. /// </summary> Uncomment } internal abstract class AbstractCommentSelectionBase<TCommand> { protected const string LanguageNameString = "languagename"; protected const string LengthString = "length"; private readonly ITextUndoHistoryRegistry _undoHistoryRegistry; private readonly IEditorOperationsFactoryService _editorOperationsFactoryService; internal AbstractCommentSelectionBase( ITextUndoHistoryRegistry undoHistoryRegistry, IEditorOperationsFactoryService editorOperationsFactoryService) { Contract.ThrowIfNull(undoHistoryRegistry); Contract.ThrowIfNull(editorOperationsFactoryService); _undoHistoryRegistry = undoHistoryRegistry; _editorOperationsFactoryService = editorOperationsFactoryService; } public abstract string DisplayName { get; } protected abstract string GetTitle(TCommand command); protected abstract string GetMessage(TCommand command); // Internal as tests currently rely on this method. internal abstract Task<CommentSelectionResult> CollectEditsAsync( Document document, ICommentSelectionService service, ITextBuffer textBuffer, NormalizedSnapshotSpanCollection selectedSpans, TCommand command, CancellationToken cancellationToken); protected static CommandState GetCommandState(ITextBuffer buffer) { return buffer.CanApplyChangeDocumentToWorkspace() ? CommandState.Available : CommandState.Unspecified; } protected static void InsertText(ArrayBuilder<TextChange> textChanges, int position, string text) => textChanges.Add(new TextChange(new TextSpan(position, 0), text)); protected static void DeleteText(ArrayBuilder<TextChange> textChanges, TextSpan span) => textChanges.Add(new TextChange(span, string.Empty)); internal bool ExecuteCommand(ITextView textView, ITextBuffer subjectBuffer, TCommand command, CommandExecutionContext context) { var title = GetTitle(command); var message = GetMessage(command); using (context.OperationContext.AddScope(allowCancellation: true, message)) { var cancellationToken = context.OperationContext.UserCancellationToken; var selectedSpans = textView.Selection.GetSnapshotSpansOnBuffer(subjectBuffer); if (selectedSpans.IsEmpty()) { return true; } var document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return true; } var service = document.GetLanguageService<ICommentSelectionService>(); if (service == null) { return true; } var edits = CollectEditsAsync(document, service, subjectBuffer, selectedSpans, command, cancellationToken).WaitAndGetResult(cancellationToken); ApplyEdits(document, textView, subjectBuffer, service, title, edits); } return true; } /// <summary> /// Applies the requested edits and sets the selection. /// This operation is not cancellable. /// </summary> private void ApplyEdits(Document document, ITextView textView, ITextBuffer subjectBuffer, ICommentSelectionService service, string title, CommentSelectionResult edits) { // Create tracking spans to track the text changes. var currentSnapshot = subjectBuffer.CurrentSnapshot; var trackingSpans = edits.TrackingSpans .SelectAsArray(textSpan => (originalSpan: textSpan, trackingSpan: CreateTrackingSpan(edits.ResultOperation, currentSnapshot, textSpan.TrackingTextSpan))); // Apply the text changes. using (var transaction = new CaretPreservingEditTransaction(title, textView, _undoHistoryRegistry, _editorOperationsFactoryService)) { document.Project.Solution.Workspace.ApplyTextChanges(document.Id, edits.TextChanges.Distinct(), CancellationToken.None); transaction.Complete(); } // Convert the tracking spans into snapshot spans for formatting and selection. var trackingSnapshotSpans = trackingSpans.Select(s => CreateSnapshotSpan(subjectBuffer.CurrentSnapshot, s.trackingSpan, s.originalSpan)); if (trackingSnapshotSpans.Any()) { if (edits.ResultOperation == Operation.Uncomment) { // Format the document only during uncomment operations. Use second transaction so it can be undone. using var transaction = new CaretPreservingEditTransaction(title, textView, _undoHistoryRegistry, _editorOperationsFactoryService); var formattedDocument = Format(service, subjectBuffer.CurrentSnapshot, trackingSnapshotSpans, CancellationToken.None); if (formattedDocument != null) { formattedDocument.Project.Solution.Workspace.ApplyDocumentChanges(formattedDocument, CancellationToken.None); transaction.Complete(); } } // Set the multi selection after edits have been applied. textView.SetMultiSelection(trackingSnapshotSpans); } } /// <summary> /// Creates a tracking span for the operation. /// Internal for tests. /// </summary> internal static ITrackingSpan CreateTrackingSpan(Operation operation, ITextSnapshot snapshot, TextSpan textSpan) { // If a comment is being added, the tracking span must include changes at the edge. var spanTrackingMode = operation == Operation.Comment ? SpanTrackingMode.EdgeInclusive : SpanTrackingMode.EdgeExclusive; return snapshot.CreateTrackingSpan(Span.FromBounds(textSpan.Start, textSpan.End), spanTrackingMode); } /// <summary> /// Retrieves the snapshot span from a post edited tracking span. /// Additionally applies any extra modifications to the tracking span post edit. /// </summary> private static SnapshotSpan CreateSnapshotSpan(ITextSnapshot snapshot, ITrackingSpan trackingSpan, CommentTrackingSpan originalSpan) { var snapshotSpan = trackingSpan.GetSpan(snapshot); if (originalSpan.HasPostApplyChanges()) { var updatedStart = snapshotSpan.Start.Position + originalSpan.AmountToAddToTrackingSpanStart; var updatedEnd = snapshotSpan.End.Position + originalSpan.AmountToAddToTrackingSpanEnd; if (updatedStart >= snapshotSpan.Start.Position && updatedEnd <= snapshotSpan.End.Position) { snapshotSpan = new SnapshotSpan(snapshot, Span.FromBounds(updatedStart, updatedEnd)); } } return snapshotSpan; } private static Document Format(ICommentSelectionService service, ITextSnapshot snapshot, IEnumerable<SnapshotSpan> changes, CancellationToken cancellationToken) { var document = snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return null; } var textSpans = changes.SelectAsArray(change => change.Span.ToTextSpan()); return service.FormatAsync(document, textSpans, cancellationToken).WaitAndGetResult(cancellationToken); } /// <summary> /// Given a set of lines, find the minimum indent of all of the non-blank, non-whitespace lines. /// </summary> protected static int DetermineSmallestIndent( SnapshotSpan span, ITextSnapshotLine firstLine, ITextSnapshotLine lastLine) { // TODO: This breaks if you have mixed tabs/spaces, and/or tabsize != indentsize. var indentToCommentAt = int.MaxValue; for (var lineNumber = firstLine.LineNumber; lineNumber <= lastLine.LineNumber; ++lineNumber) { var line = span.Snapshot.GetLineFromLineNumber(lineNumber); var firstNonWhitespacePosition = line.GetFirstNonWhitespacePosition(); var firstNonWhitespaceOnLine = firstNonWhitespacePosition.HasValue ? firstNonWhitespacePosition.Value - line.Start : int.MaxValue; indentToCommentAt = Math.Min(indentToCommentAt, firstNonWhitespaceOnLine); } return indentToCommentAt; } } }
-1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/IndexerCompletionProviderTests.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.Tasks; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders { public class IndexerCompletionProviderTests : AbstractCSharpCompletionProviderTests { internal override Type GetCompletionProviderType() => typeof(UnnamedSymbolCompletionProvider); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47511, "https://github.com/dotnet/roslyn/issues/47511")] public async Task IndexerIsSuggestedAfterDot() { await VerifyItemExistsAsync(@" public class C { public int this[int i] => i; } public class Program { public static void Main() { var c = new C(); c.$$ } } ", "this", displayTextSuffix: "[]", matchingFilters: new List<CompletionFilter> { FilterSet.PropertyFilter }); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47511, "https://github.com/dotnet/roslyn/issues/47511")] public async Task IndexerIsSuggestedAfterDotForString() { await VerifyItemExistsAsync(@" public class Program { public static void Main(string s) { s.$$ } } ", "this", displayTextSuffix: "[]", matchingFilters: new List<CompletionFilter> { FilterSet.PropertyFilter }); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47511, "https://github.com/dotnet/roslyn/issues/47511")] public async Task IndexerIsNotSuggestedOnStaticAccess() { await VerifyNoItemsExistAsync(@" public class C { public int this[int i] => i; } public class Program { public static void Main() { C.$$ } } "); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47511, "https://github.com/dotnet/roslyn/issues/47511")] public async Task IndexerIsNotSuggestedInNameOfContext() { await VerifyNoItemsExistAsync(@" public class C { public int this[int i] => i; } public class Program { public static void Main() { var c = new C(); var name = nameof(c.$$ } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47511, "https://github.com/dotnet/roslyn/issues/47511")] public async Task IndexerSuggestionCommitsOpenAndClosingBraces() { await VerifyCustomCommitProviderAsync(@" public class C { public int this[int i] => i; } public class Program { public static void Main() { var c = new C(); c.$$ } } ", "this", @" public class C { public int this[int i] => i; } public class Program { public static void Main() { var c = new C(); c[$$] } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47511, "https://github.com/dotnet/roslyn/issues/47511")] public async Task IndexerWithTwoParametersSuggestionCommitsOpenAndClosingBraces() { await VerifyCustomCommitProviderAsync(@" public class C { public int this[int x, int y] => i; } public class Program { public static void Main() { var c = new C(); c.$$ } } ", "this", @" public class C { public int this[int x, int y] => i; } public class Program { public static void Main() { var c = new C(); c[$$] } } "); } [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47511, "https://github.com/dotnet/roslyn/issues/47511")] [InlineData("c.$$", "c[$$]")] [InlineData("c. $$", "c[$$] ")] [InlineData("c.$$;", "c[$$];")] [InlineData("c.th$$", "c[$$]")] [InlineData("c.this$$", "c[$$]")] [InlineData("c.th$$;", "c[$$];")] [InlineData("var f = c.$$;", "var f = c[$$];")] [InlineData("var f = c.th$$;", "var f = c[$$];")] [InlineData("c?.$$", "c?[$$]")] [InlineData("c?.this$$", "c?[$$]")] [InlineData("((C)c).$$", "((C)c)[$$]")] [InlineData("(true ? c : c).$$", "(true ? c : c)[$$]")] public async Task IndexerCompletionForDifferentExpressions(string expression, string fixedCode) { await VerifyCustomCommitProviderAsync($@" public class C {{ public int this[int i] => i; }} public class Program {{ public static void Main() {{ var c = new C(); {expression} }} }} ", "this", @$" public class C {{ public int this[int i] => i; }} public class Program {{ public static void Main() {{ var c = new C(); {fixedCode} }} }} "); } [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47511, "https://github.com/dotnet/roslyn/issues/47511")] [InlineData("/* Leading trivia */c.$$", "/* Leading trivia */c[$$]")] [InlineData("c. $$ /* Trailing trivia */", "c[$$] /* Trailing trivia */")] [InlineData("c./* Trivia in between */$$", "c[$$]/* Trivia in between */")] public async Task IndexerCompletionTriviaTest(string expression, string fixedCode) { await VerifyCustomCommitProviderAsync($@" public class C {{ public int this[int i] => i; }} public class Program {{ public static void Main() {{ var c = new C(); {expression} }} }} ", "this", @$" public class C {{ public int this[int i] => i; }} public class Program {{ public static void Main() {{ var c = new C(); {fixedCode} }} }} "); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47511, "https://github.com/dotnet/roslyn/issues/47511")] public async Task IndexerDescriptionIncludesDocCommentsAndOverloadsHint() { await VerifyItemExistsAsync(@" public class C { /// <summary> /// Returns the index <paramref name=""i""/> /// </summary> /// <param name=""i"">The index</param> /// <returns>Returns the index <paramref name=""i""/></returns> public int this[int i] => i; /// <summary> /// Returns 1 /// </summary> /// <param name=""i"">The index</param> /// <returns>Returns 1</returns> public int this[string s] => 1; } public class Program { public static void Main() { var c = new C(); c.$$ } } ", "this", displayTextSuffix: "[]", expectedDescriptionOrNull: @$"int C.this[int i] {{ get; }} (+ 1 {FeaturesResources.overload}) Returns the index i"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47511, "https://github.com/dotnet/roslyn/issues/47511")] public async Task IndexerOfBaseTypeIsSuggestedAfterDot() { await VerifyItemExistsAsync(@" public class Base { public int this[int i] => i; } public class Derived : Base { } public class Program { public static void Main() { var d = new Derived(); d.$$ } } ", "this", displayTextSuffix: "[]"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47511, "https://github.com/dotnet/roslyn/issues/47511")] public async Task IndexerOfBaseTypeIsNotSuggestedIfNotAccessible() { await VerifyNoItemsExistAsync(@" public class Base { protected int this[int i] => i; } public class Derived : Base { } public class Program { public static void Main() { var d = new Derived(); d.$$ } } "); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47511, "https://github.com/dotnet/roslyn/issues/47511")] public async Task IndexerIsSuggestedOnString() { await VerifyItemExistsAsync(@" public class Program { public static void Main() { var s = ""Test""; s.$$ } } ", "this", displayTextSuffix: "[]"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47511, "https://github.com/dotnet/roslyn/issues/47511")] public async Task TestEditorBrowsableOnIndexerIsRespected_EditorBrowsableStateNever() { var markup = @" namespace N { public class Program { public static void Main() { var c = new C(); c.$$ } } } "; var referencedCode = @" using System.ComponentModel; namespace N { public class C { [EditorBrowsable(EditorBrowsableState.Never)] public int this[int i] => i; } } "; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "this", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47511, "https://github.com/dotnet/roslyn/issues/47511")] public async Task TestEditorBrowsableOnIndexerIsRespected_EditorBrowsableStateAdvanced() { var markup = @" namespace N { public class Program { public static void Main() { var c = new C(); c.$$ } } } "; var referencedCode = @" using System.ComponentModel; namespace N { public class C { [EditorBrowsable(EditorBrowsableState.Advanced)] public int this[int i] => i; } } "; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "this", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "this", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47511, "https://github.com/dotnet/roslyn/issues/47511")] public async Task TestEditorBrowsableOnIndexerIsRespected_EditorBrowsableStateNever_InheritedMember() { var markup = @" namespace N { public class Program { public static void Main() { var d = new Derived(); d.$$ } } } "; var referencedCode = @" using System.ComponentModel; namespace N { public class Base { [EditorBrowsable(EditorBrowsableState.Never)] public int this[int i] => i; } public class Derived: Base { } } "; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "this", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47511, "https://github.com/dotnet/roslyn/issues/47511")] public async Task IndexerNullForgivingOperatorHandling() { await VerifyCustomCommitProviderAsync(@" #nullable enable public class C { public int this[int i] => i; } public class Program { public static void Main() { C? c = null; var i = c!.$$ } } ", "this", @" #nullable enable public class C { public int this[int i] => i; } public class Program { public static void Main() { C? c = null; var i = c![$$] } } "); } } }
// Licensed to the .NET Foundation under one or more 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.Tasks; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders { public class IndexerCompletionProviderTests : AbstractCSharpCompletionProviderTests { internal override Type GetCompletionProviderType() => typeof(UnnamedSymbolCompletionProvider); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47511, "https://github.com/dotnet/roslyn/issues/47511")] public async Task IndexerIsSuggestedAfterDot() { await VerifyItemExistsAsync(@" public class C { public int this[int i] => i; } public class Program { public static void Main() { var c = new C(); c.$$ } } ", "this", displayTextSuffix: "[]", matchingFilters: new List<CompletionFilter> { FilterSet.PropertyFilter }); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47511, "https://github.com/dotnet/roslyn/issues/47511")] public async Task IndexerIsSuggestedAfterDotForString() { await VerifyItemExistsAsync(@" public class Program { public static void Main(string s) { s.$$ } } ", "this", displayTextSuffix: "[]", matchingFilters: new List<CompletionFilter> { FilterSet.PropertyFilter }); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47511, "https://github.com/dotnet/roslyn/issues/47511")] public async Task IndexerIsNotSuggestedOnStaticAccess() { await VerifyNoItemsExistAsync(@" public class C { public int this[int i] => i; } public class Program { public static void Main() { C.$$ } } "); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47511, "https://github.com/dotnet/roslyn/issues/47511")] public async Task IndexerIsNotSuggestedInNameOfContext() { await VerifyNoItemsExistAsync(@" public class C { public int this[int i] => i; } public class Program { public static void Main() { var c = new C(); var name = nameof(c.$$ } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47511, "https://github.com/dotnet/roslyn/issues/47511")] public async Task IndexerSuggestionCommitsOpenAndClosingBraces() { await VerifyCustomCommitProviderAsync(@" public class C { public int this[int i] => i; } public class Program { public static void Main() { var c = new C(); c.$$ } } ", "this", @" public class C { public int this[int i] => i; } public class Program { public static void Main() { var c = new C(); c[$$] } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47511, "https://github.com/dotnet/roslyn/issues/47511")] public async Task IndexerWithTwoParametersSuggestionCommitsOpenAndClosingBraces() { await VerifyCustomCommitProviderAsync(@" public class C { public int this[int x, int y] => i; } public class Program { public static void Main() { var c = new C(); c.$$ } } ", "this", @" public class C { public int this[int x, int y] => i; } public class Program { public static void Main() { var c = new C(); c[$$] } } "); } [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47511, "https://github.com/dotnet/roslyn/issues/47511")] [InlineData("c.$$", "c[$$]")] [InlineData("c. $$", "c[$$] ")] [InlineData("c.$$;", "c[$$];")] [InlineData("c.th$$", "c[$$]")] [InlineData("c.this$$", "c[$$]")] [InlineData("c.th$$;", "c[$$];")] [InlineData("var f = c.$$;", "var f = c[$$];")] [InlineData("var f = c.th$$;", "var f = c[$$];")] [InlineData("c?.$$", "c?[$$]")] [InlineData("c?.this$$", "c?[$$]")] [InlineData("((C)c).$$", "((C)c)[$$]")] [InlineData("(true ? c : c).$$", "(true ? c : c)[$$]")] public async Task IndexerCompletionForDifferentExpressions(string expression, string fixedCode) { await VerifyCustomCommitProviderAsync($@" public class C {{ public int this[int i] => i; }} public class Program {{ public static void Main() {{ var c = new C(); {expression} }} }} ", "this", @$" public class C {{ public int this[int i] => i; }} public class Program {{ public static void Main() {{ var c = new C(); {fixedCode} }} }} "); } [WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47511, "https://github.com/dotnet/roslyn/issues/47511")] [InlineData("/* Leading trivia */c.$$", "/* Leading trivia */c[$$]")] [InlineData("c. $$ /* Trailing trivia */", "c[$$] /* Trailing trivia */")] [InlineData("c./* Trivia in between */$$", "c[$$]/* Trivia in between */")] public async Task IndexerCompletionTriviaTest(string expression, string fixedCode) { await VerifyCustomCommitProviderAsync($@" public class C {{ public int this[int i] => i; }} public class Program {{ public static void Main() {{ var c = new C(); {expression} }} }} ", "this", @$" public class C {{ public int this[int i] => i; }} public class Program {{ public static void Main() {{ var c = new C(); {fixedCode} }} }} "); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47511, "https://github.com/dotnet/roslyn/issues/47511")] public async Task IndexerDescriptionIncludesDocCommentsAndOverloadsHint() { await VerifyItemExistsAsync(@" public class C { /// <summary> /// Returns the index <paramref name=""i""/> /// </summary> /// <param name=""i"">The index</param> /// <returns>Returns the index <paramref name=""i""/></returns> public int this[int i] => i; /// <summary> /// Returns 1 /// </summary> /// <param name=""i"">The index</param> /// <returns>Returns 1</returns> public int this[string s] => 1; } public class Program { public static void Main() { var c = new C(); c.$$ } } ", "this", displayTextSuffix: "[]", expectedDescriptionOrNull: @$"int C.this[int i] {{ get; }} (+ 1 {FeaturesResources.overload}) Returns the index i"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47511, "https://github.com/dotnet/roslyn/issues/47511")] public async Task IndexerOfBaseTypeIsSuggestedAfterDot() { await VerifyItemExistsAsync(@" public class Base { public int this[int i] => i; } public class Derived : Base { } public class Program { public static void Main() { var d = new Derived(); d.$$ } } ", "this", displayTextSuffix: "[]"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47511, "https://github.com/dotnet/roslyn/issues/47511")] public async Task IndexerOfBaseTypeIsNotSuggestedIfNotAccessible() { await VerifyNoItemsExistAsync(@" public class Base { protected int this[int i] => i; } public class Derived : Base { } public class Program { public static void Main() { var d = new Derived(); d.$$ } } "); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47511, "https://github.com/dotnet/roslyn/issues/47511")] public async Task IndexerIsSuggestedOnString() { await VerifyItemExistsAsync(@" public class Program { public static void Main() { var s = ""Test""; s.$$ } } ", "this", displayTextSuffix: "[]"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47511, "https://github.com/dotnet/roslyn/issues/47511")] public async Task TestEditorBrowsableOnIndexerIsRespected_EditorBrowsableStateNever() { var markup = @" namespace N { public class Program { public static void Main() { var c = new C(); c.$$ } } } "; var referencedCode = @" using System.ComponentModel; namespace N { public class C { [EditorBrowsable(EditorBrowsableState.Never)] public int this[int i] => i; } } "; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "this", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47511, "https://github.com/dotnet/roslyn/issues/47511")] public async Task TestEditorBrowsableOnIndexerIsRespected_EditorBrowsableStateAdvanced() { var markup = @" namespace N { public class Program { public static void Main() { var c = new C(); c.$$ } } } "; var referencedCode = @" using System.ComponentModel; namespace N { public class C { [EditorBrowsable(EditorBrowsableState.Advanced)] public int this[int i] => i; } } "; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "this", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "this", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47511, "https://github.com/dotnet/roslyn/issues/47511")] public async Task TestEditorBrowsableOnIndexerIsRespected_EditorBrowsableStateNever_InheritedMember() { var markup = @" namespace N { public class Program { public static void Main() { var d = new Derived(); d.$$ } } } "; var referencedCode = @" using System.ComponentModel; namespace N { public class Base { [EditorBrowsable(EditorBrowsableState.Never)] public int this[int i] => i; } public class Derived: Base { } } "; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "this", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47511, "https://github.com/dotnet/roslyn/issues/47511")] public async Task IndexerNullForgivingOperatorHandling() { await VerifyCustomCommitProviderAsync(@" #nullable enable public class C { public int this[int i] => i; } public class Program { public static void Main() { C? c = null; var i = c!.$$ } } ", "this", @" #nullable enable public class C { public int this[int i] => i; } public class Program { public static void Main() { C? c = null; var i = c![$$] } } "); } } }
-1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/Syntax/Diagnostics/LineSpanDirectiveTests.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.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class LineSpanDirectiveTests : CSharpTestBase { [Fact] public void LineSpanDirective_SingleLine() { string sourceA = @" A1(); A2(); A3(); //123 //4567890 ".NormalizeLineEndings(); var textA = SourceText.From(sourceA); string sourceB = @"class Program { static void Main() { #line (1, 16) - (1, 26) 15 ""a.cs"" B1(); A2(); A3(); B4(); B5(); } } ".NormalizeLineEndings(); var treeB = SyntaxFactory.ParseSyntaxTree(sourceB, path: "b.cs"); treeB.GetDiagnostics().Verify(); var actualLineMappings = GetLineMappings(treeB); var expectedLineMappings = new[] { "(0,0)-(3,7) -> : (0,0)-(3,7)", "(5,0)-(9,0),14 -> a.cs: (0,15)-(0,26)", }; AssertEx.Equal(expectedLineMappings, actualLineMappings); var statements = GetStatementsAndExpressionBodies(treeB); var actualTextSpans = statements.SelectAsArray(s => GetTextMapping(textA, treeB, s)); var expectedTextSpans = new[] { (@"B1();", @"[|A2(); A3();|]"), (@"A2();", @"[|A2(); A3();|]"), (@"A3();", @"[|A3();|]"), (@"B4();", @"[|//123|]"), (@"B5();", @"[|0|]"), }; AssertEx.Equal(expectedTextSpans, actualTextSpans); } [Fact] public void LineSpanDirective_MultiLine() { string sourceA = @" A1(); A2(); A3(); //123 //4567890 //ABCDEF ".NormalizeLineEndings(); var textA = SourceText.From(sourceA); string sourceB = @"class Program { static void Main() { #line (1, 16) - (5, 26) 15 ""a.cs"" B1(); A2(); A3(); B4(); B5(); } } ".NormalizeLineEndings(); var treeB = SyntaxFactory.ParseSyntaxTree(sourceB, path: "b.cs"); treeB.GetDiagnostics().Verify(); var actualLineMappings = GetLineMappings(treeB); var expectedLineMappings = new[] { "(0,0)-(3,7) -> : (0,0)-(3,7)", "(5,0)-(9,0),14 -> a.cs: (0,15)-(4,26)", }; AssertEx.Equal(expectedLineMappings, actualLineMappings); var statements = GetStatementsAndExpressionBodies(treeB); var actualTextSpans = statements.SelectAsArray(s => GetTextMapping(textA, treeB, s)); var expectedTextSpans = new[] { (@"B1();", @"[|A2(); A3(); //123 //4567890 //ABCDEF |]".NormalizeLineEndings()), (@"A2();", @"[|A2(); A3(); //123 //4567890 //ABCDEF |]".NormalizeLineEndings()), (@"A3();", @"[|A3();|]"), (@"B4();", @"[|//123|]"), (@"B5();", @"[|0|]"), }; AssertEx.Equal(expectedTextSpans, actualTextSpans); } [Fact] public void InvalidSpans() { string source = @"class Program { static void Main() { #line (10, 20) - (10, 20) ""A"" F(); #line (10, 20) - (10, 19) ""B"" F(); #line (10, 20) - (9, 20) ""C"" F(); #line (10, 20) - (11, 19) ""D"" F(); } static void F() { } }".NormalizeLineEndings(); var tree = SyntaxFactory.ParseSyntaxTree(source); var comp = CreateCompilation(tree); comp.VerifyDiagnostics( // (9,18): error CS8939: The #line directive end position must be greater than or equal to the start position // #line (10, 20) - (9, 20) "C" Diagnostic(ErrorCode.ERR_LineSpanDirectiveEndLessThanStart, "(9, 20)").WithLocation(9, 18), // A(11,18): error CS8939: The #line directive end position must be greater than or equal to the start position // #line (10, 20) - (10, 19) "B" Diagnostic(ErrorCode.ERR_LineSpanDirectiveEndLessThanStart, "(10, 19)").WithLocation(11, 18)); var actualLineMappings = GetLineMappings(tree); var expectedLineMappings = new[] { "(0,0)-(3,7) -> : (0,0)-(3,7)", "(5,0)-(5,14) -> A: (9,19)-(9,20)", "(7,0)-(7,14) -> : (7,0)-(7,14)", "(9,0)-(9,14) -> : (9,0)-(9,14)", "(11,0)-(14,1) -> D: (9,19)-(10,19)", }; AssertEx.Equal(expectedLineMappings, actualLineMappings); } // 1. First and subsequent spans [WorkItem(4747, "https://github.com/dotnet/csharplang/issues/4747")] [Fact] public void LineSpanDirective_Example1() { string sourceA = @" A();B( );C(); D(); ".NormalizeLineEndings(); var textA = SourceText.From(sourceA); string sourceB = @"class Program { static void Main() { #line (1,10)-(1,15) 3 ""a"" // 3 A();B( // 4 );C(); // 5 D(); // 6 } static void A() { } static void B() { } static void C() { } static void D() { } }".NormalizeLineEndings(); var treeB = SyntaxFactory.ParseSyntaxTree(sourceB, path: "b.cs"); treeB.GetDiagnostics().Verify(); var actualLineMappings = GetLineMappings(treeB); var expectedLineMappings = new[] { "(0,0)-(2,23) -> : (0,0)-(2,23)", "(4,0)-(12,1),2 -> a: (0,9)-(0,15)", }; AssertEx.Equal(expectedLineMappings, actualLineMappings); var statements = GetStatementsAndExpressionBodies(treeB); var actualTextSpans = statements.SelectAsArray(s => GetTextMapping(textA, treeB, s)); var expectedTextSpans = new[] { (@"A();", @"[|A();B(|]"), (@"B( // 4...", @"[|B( );|]".NormalizeLineEndings()), (@"C();", @"[|C();|]"), (@"D();", @"[|D();|]"), }; AssertEx.Equal(expectedTextSpans, actualTextSpans); } // 2. Character offset [WorkItem(4747, "https://github.com/dotnet/csharplang/issues/4747")] [Fact] public void LineSpanDirective_Example2() { string sourceA = @"@page ""/"" @F(() => 1+1, () => 2+2 )".NormalizeLineEndings(); var textA = SourceText.From(sourceA); string sourceB = @"#line hidden class Page { void Render() { #line (2,2)-(4,1) 16 ""page.razor"" // spanof('F(...)') _builder.Add(F(() => 1+1, // 5 () => 2+2 // 6 )); // 7 #line hidden } }".NormalizeLineEndings(); var treeB = SyntaxFactory.ParseSyntaxTree(sourceB, path: "page.razor.g.cs"); treeB.GetDiagnostics().Verify(); var actualLineMappings = GetLineMappings(treeB); var expectedLineMappings = new[] { "(1,0)-(4,3) -> : (0,0)-(0,0)", "(6,0)-(8,40),15 -> page.razor: (1,1)-(3,1)", "(10,0)-(11,1) -> : (0,0)-(0,0)", }; AssertEx.Equal(expectedLineMappings, actualLineMappings); var textB = SourceText.From(sourceB); var actualVisibility = textB.Lines.Select(line => treeB.GetLineVisibility(line.Start)).ToImmutableArray(); var expectedVisibility = new[] { LineVisibility.BeforeFirstLineDirective, LineVisibility.Hidden, LineVisibility.Hidden, LineVisibility.Hidden, LineVisibility.Hidden, LineVisibility.Hidden, LineVisibility.Visible, LineVisibility.Visible, LineVisibility.Visible, LineVisibility.Visible, LineVisibility.Hidden, LineVisibility.Hidden, }; AssertEx.Equal(expectedVisibility, actualVisibility); var statements = GetStatementsAndExpressionBodies(treeB); var actualTextSpans = statements.SelectAsArray(s => GetTextMapping(textA, treeB, s)); var expectedTextSpans = new[] { (@"_builder.Add(F(() => 1+1, // 5...", @"[|F(() => 1+1, () => 2+2 )|]".NormalizeLineEndings()), (@"1+1", @"[|1+1|]"), (@"2+2", @"[|2+2|]"), }; AssertEx.Equal(expectedTextSpans, actualTextSpans); } // 3. Razor: Single-line span [WorkItem(4747, "https://github.com/dotnet/csharplang/issues/4747")] [Fact] public void LineSpanDirective_Example3() { string sourceA = @"@page ""/"" Time: @DateTime.Now ".NormalizeLineEndings(); var textA = SourceText.From(sourceA); string sourceB = @"#line hidden class Page { void Render() { _builder.Add(""Time:""); #line (2,8)-(2,19) 15 ""page.razor"" // spanof('DateTime.Now') _builder.Add(DateTime.Now); #line hidden } }".NormalizeLineEndings(); var treeB = SyntaxFactory.ParseSyntaxTree(sourceB, path: "page.razor.g.cs"); treeB.GetDiagnostics().Verify(); var actualLineMappings = GetLineMappings(treeB); var expectedLineMappings = new[] { "(1,0)-(5,26) -> : (0,0)-(0,0)", "(7,0)-(7,31),14 -> page.razor: (1,7)-(1,19)", "(9,0)-(10,1) -> : (0,0)-(0,0)", }; AssertEx.Equal(expectedLineMappings, actualLineMappings); var statements = GetStatementsAndExpressionBodies(treeB); var actualTextSpans = statements.SelectAsArray(s => GetTextMapping(textA, treeB, s)); var expectedTextSpans = new[] { (@"_builder.Add(""Time:"");", @"[||]"), (@"_builder.Add(DateTime.Now);", @"[|DateTime.Now|]"), }; AssertEx.Equal(expectedTextSpans, actualTextSpans); } // 4. Razor: Multi-line span [WorkItem(4747, "https://github.com/dotnet/csharplang/issues/4747")] [Fact] public void LineSpanDirective_Example4() { string sourceA = @"@page ""/"" @JsonToHtml(@"" { """"key1"""": """"value1"""", """"key2"""": """"value2"""" }"")".NormalizeLineEndings(); var textA = SourceText.From(sourceA); string sourceB = @"#line hidden class Page { void Render() { #line (2,2)-(6,3) 16 ""page.razor"" // spanof('JsonToHtml(...)') _builder.Add(JsonToHtml(@"" { """"key1"""": """"value1"""", """"key2"""": """"value2"""" }"")); #line hidden } }".NormalizeLineEndings(); var treeB = SyntaxFactory.ParseSyntaxTree(sourceB, path: "page.razor.g.cs"); treeB.GetDiagnostics().Verify(); var actualLineMappings = GetLineMappings(treeB); var expectedLineMappings = new[] { "(1,0)-(4,3) -> : (0,0)-(0,0)", "(6,0)-(10,7),15 -> page.razor: (1,1)-(5,3)", "(12,0)-(13,1) -> : (0,0)-(0,0)", }; AssertEx.Equal(expectedLineMappings, actualLineMappings); var statements = GetStatementsAndExpressionBodies(treeB); var actualTextSpans = statements.SelectAsArray(s => GetTextMapping(textA, treeB, s)); var expectedTextSpans = new[] { (@"_builder.Add(JsonToHtml(@""...", @"[|JsonToHtml(@"" { """"key1"""": """"value1"""", """"key2"""": """"value2"""" }"")|]".NormalizeLineEndings()), }; AssertEx.Equal(expectedTextSpans, actualTextSpans); } // 5i. Razor: block constructs [WorkItem(4747, "https://github.com/dotnet/csharplang/issues/4747")] [Fact] public void LineSpanDirective_Example5i() { string sourceA = @"@Html.Helper(() => { <p>Hello World</p> @DateTime.Now })".NormalizeLineEndings(); var textA = SourceText.From(sourceA); string sourceB = @"using System; class Page { Builder _builder; void Execute() { #line (1, 2) - (5, 2) 22 ""a.razor"" // spanof('HtmlHelper(() => { ... })') _builder.Add(Html.Helper(() => #line 2 ""a.razor"" // lineof('{') { #line (4, 6) - (4, 17) 26 ""a.razor"" // spanof('DateTime.Now') _builder.Add(DateTime.Now); #line 5 ""a.razor"" // lineof('})') }) #line hidden ); } }".NormalizeLineEndings(); var treeB = SyntaxFactory.ParseSyntaxTree(sourceB, path: "a.razor.g.cs"); treeB.GetDiagnostics().Verify(); var actualLineMappings = GetLineMappings(treeB); var expectedLineMappings = new[] { "(0,0)-(5,7) -> : (0,0)-(5,7)", "(7,0)-(7,40),21 -> a.razor: (0,1)-(4,2)", "(9,0)-(9,11) -> a.razor: (1,0)-(1,11)", "(11,0)-(11,41),25 -> a.razor: (3,5)-(3,17)", "(13,0)-(13,12) -> a.razor: (4,0)-(4,12)", "(15,0)-(17,1) -> : (0,0)-(0,0)", }; AssertEx.Equal(expectedLineMappings, actualLineMappings); var statements = GetStatementsAndExpressionBodies(treeB); var actualTextSpans = statements.SelectAsArray(s => GetTextMapping(textA, treeB, s)); var expectedTextSpans = new[] { (@"_builder.Add(Html.Helper(() =>...", @"[|Html.Helper(() => { <p>Hello World</p> @DateTime.Now })|]".NormalizeLineEndings()), (@"_builder.Add(DateTime.Now);", @"[|DateTime.Now|]"), }; AssertEx.Equal(expectedTextSpans, actualTextSpans); } private static ImmutableArray<SyntaxNode> GetStatementsAndExpressionBodies(SyntaxTree tree) { var builder = ArrayBuilder<SyntaxNode>.GetInstance(); foreach (var syntax in tree.GetRoot().DescendantNodesAndSelf()) { switch (syntax) { case ExpressionStatementSyntax: builder.Add(syntax); break; case ParenthesizedLambdaExpressionSyntax lambda: builder.AddIfNotNull(lambda.ExpressionBody); break; case SimpleLambdaExpressionSyntax lambda: builder.AddIfNotNull(lambda.ExpressionBody); break; } } return builder.ToImmutableAndFree(); } private static ImmutableArray<string> GetLineMappings(SyntaxTree tree) { var directives = tree.GetRoot().DescendantNodesAndSelf(descendIntoTrivia: true).OfType<DirectiveTriviaSyntax>(); foreach (var directive in directives) { Assert.NotEqual(SyntaxKind.None, directive.DirectiveNameToken.Kind()); } return tree.GetLineMappings().Select(mapping => mapping.ToString()!).ToImmutableArray(); } private static (string, string) GetTextMapping(SourceText mappedText, SyntaxTree unmappedText, SyntaxNode syntax) { return (getDescription(syntax), getMapping(mappedText, unmappedText, syntax)); static string getDescription(SyntaxNode syntax) { var description = syntax.ToString(); int index = description.IndexOfAny(new[] { '\r', '\n' }); return index < 0 ? description : description.Substring(0, index) + "..."; } static string getMapping(SourceText mappedText, SyntaxTree unmappedText, SyntaxNode syntax) { var mappedLineAndPositionSpan = unmappedText.GetMappedLineSpanAndVisibility(syntax.Span, out _); var span = getTextSpan(mappedText.Lines, mappedLineAndPositionSpan.Span); return $"[|{mappedText.GetSubText(span)}|]"; } static TextSpan getTextSpan(TextLineCollection lines, LinePositionSpan span) { return TextSpan.FromBounds(getTextPosition(lines, span.Start), getTextPosition(lines, span.End)); } static int getTextPosition(TextLineCollection lines, LinePosition position) { if (position.Line < lines.Count) { var line = lines[position.Line]; return Math.Min(line.Start + position.Character, line.End); } return (lines.Count == 0) ? 0 : lines[^1].End; } } [Fact] public void Diagnostics() { var source = @"class Program { static void Main() { #line (3, 3) - (6, 6) 8 ""a.txt"" A(); #line default B(); #line (1, 1) - (1, 100) ""b.txt"" C(); } }".NormalizeLineEndings(); var comp = CreateCompilation(source); comp.VerifyDiagnostics( // b.txt(1,9): error CS0103: The name 'C' does not exist in the current context // C(); Diagnostic(ErrorCode.ERR_NameNotInContext, "C").WithArguments("C").WithLocation(1, 9), // a.txt(3,4): error CS0103: The name 'A' does not exist in the current context // A(); Diagnostic(ErrorCode.ERR_NameNotInContext, "A").WithArguments("A").WithLocation(3, 4), // (8,9): error CS0103: The name 'B' does not exist in the current context // B(); Diagnostic(ErrorCode.ERR_NameNotInContext, "B").WithArguments("B").WithLocation(8, 9)); } [Fact] public void SequencePoints() { var source = @"class Program { static void Main() { #line (3, 3) - (6, 6) 8 ""a.txt"" A(); #line default B(); #line (1, 1) - (1, 100) ""b.txt"" C(); #line (2, 3) - (2, 4) 9 ""a.txt"" D(); } static void A() { } static void B() { } static void C() { } static void D() { } }".NormalizeLineEndings(); var verifier = CompileAndVerify(source, options: TestOptions.DebugDll); verifier.VerifyIL("Program.Main", sequencePoints: "Program.Main", expectedIL: @"{ // Code size 26 (0x1a) .maxstack 0 -IL_0000: nop -IL_0001: call ""void Program.A()"" IL_0006: nop -IL_0007: call ""void Program.B()"" IL_000c: nop -IL_000d: call ""void Program.C()"" IL_0012: nop -IL_0013: call ""void Program.D()"" IL_0018: nop -IL_0019: ret }"); verifier.VerifyPdb("Program.Main", expectedPdb: @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> <file id=""2"" name=""a.txt"" language=""C#"" /> <file id=""3"" name=""b.txt"" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""3"" startColumn=""4"" endLine=""3"" endColumn=""8"" document=""2"" /> <entry offset=""0x7"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""13"" document=""1"" /> <entry offset=""0xd"" startLine=""1"" startColumn=""9"" endLine=""1"" endColumn=""13"" document=""3"" /> <entry offset=""0x13"" startLine=""2"" startColumn=""3"" endLine=""2"" endColumn=""5"" document=""2"" /> <entry offset=""0x19"" startLine=""3"" startColumn=""5"" endLine=""3"" endColumn=""6"" document=""2"" /> </sequencePoints> </method> </methods> </symbols> "); } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class LineSpanDirectiveTests : CSharpTestBase { [Fact] public void LineSpanDirective_SingleLine() { string sourceA = @" A1(); A2(); A3(); //123 //4567890 ".NormalizeLineEndings(); var textA = SourceText.From(sourceA); string sourceB = @"class Program { static void Main() { #line (1, 16) - (1, 26) 15 ""a.cs"" B1(); A2(); A3(); B4(); B5(); } } ".NormalizeLineEndings(); var treeB = SyntaxFactory.ParseSyntaxTree(sourceB, path: "b.cs"); treeB.GetDiagnostics().Verify(); var actualLineMappings = GetLineMappings(treeB); var expectedLineMappings = new[] { "(0,0)-(3,7) -> : (0,0)-(3,7)", "(5,0)-(9,0),14 -> a.cs: (0,15)-(0,26)", }; AssertEx.Equal(expectedLineMappings, actualLineMappings); var statements = GetStatementsAndExpressionBodies(treeB); var actualTextSpans = statements.SelectAsArray(s => GetTextMapping(textA, treeB, s)); var expectedTextSpans = new[] { (@"B1();", @"[|A2(); A3();|]"), (@"A2();", @"[|A2(); A3();|]"), (@"A3();", @"[|A3();|]"), (@"B4();", @"[|//123|]"), (@"B5();", @"[|0|]"), }; AssertEx.Equal(expectedTextSpans, actualTextSpans); } [Fact] public void LineSpanDirective_MultiLine() { string sourceA = @" A1(); A2(); A3(); //123 //4567890 //ABCDEF ".NormalizeLineEndings(); var textA = SourceText.From(sourceA); string sourceB = @"class Program { static void Main() { #line (1, 16) - (5, 26) 15 ""a.cs"" B1(); A2(); A3(); B4(); B5(); } } ".NormalizeLineEndings(); var treeB = SyntaxFactory.ParseSyntaxTree(sourceB, path: "b.cs"); treeB.GetDiagnostics().Verify(); var actualLineMappings = GetLineMappings(treeB); var expectedLineMappings = new[] { "(0,0)-(3,7) -> : (0,0)-(3,7)", "(5,0)-(9,0),14 -> a.cs: (0,15)-(4,26)", }; AssertEx.Equal(expectedLineMappings, actualLineMappings); var statements = GetStatementsAndExpressionBodies(treeB); var actualTextSpans = statements.SelectAsArray(s => GetTextMapping(textA, treeB, s)); var expectedTextSpans = new[] { (@"B1();", @"[|A2(); A3(); //123 //4567890 //ABCDEF |]".NormalizeLineEndings()), (@"A2();", @"[|A2(); A3(); //123 //4567890 //ABCDEF |]".NormalizeLineEndings()), (@"A3();", @"[|A3();|]"), (@"B4();", @"[|//123|]"), (@"B5();", @"[|0|]"), }; AssertEx.Equal(expectedTextSpans, actualTextSpans); } [Fact] public void InvalidSpans() { string source = @"class Program { static void Main() { #line (10, 20) - (10, 20) ""A"" F(); #line (10, 20) - (10, 19) ""B"" F(); #line (10, 20) - (9, 20) ""C"" F(); #line (10, 20) - (11, 19) ""D"" F(); } static void F() { } }".NormalizeLineEndings(); var tree = SyntaxFactory.ParseSyntaxTree(source); var comp = CreateCompilation(tree); comp.VerifyDiagnostics( // (9,18): error CS8939: The #line directive end position must be greater than or equal to the start position // #line (10, 20) - (9, 20) "C" Diagnostic(ErrorCode.ERR_LineSpanDirectiveEndLessThanStart, "(9, 20)").WithLocation(9, 18), // A(11,18): error CS8939: The #line directive end position must be greater than or equal to the start position // #line (10, 20) - (10, 19) "B" Diagnostic(ErrorCode.ERR_LineSpanDirectiveEndLessThanStart, "(10, 19)").WithLocation(11, 18)); var actualLineMappings = GetLineMappings(tree); var expectedLineMappings = new[] { "(0,0)-(3,7) -> : (0,0)-(3,7)", "(5,0)-(5,14) -> A: (9,19)-(9,20)", "(7,0)-(7,14) -> : (7,0)-(7,14)", "(9,0)-(9,14) -> : (9,0)-(9,14)", "(11,0)-(14,1) -> D: (9,19)-(10,19)", }; AssertEx.Equal(expectedLineMappings, actualLineMappings); } // 1. First and subsequent spans [WorkItem(4747, "https://github.com/dotnet/csharplang/issues/4747")] [Fact] public void LineSpanDirective_Example1() { string sourceA = @" A();B( );C(); D(); ".NormalizeLineEndings(); var textA = SourceText.From(sourceA); string sourceB = @"class Program { static void Main() { #line (1,10)-(1,15) 3 ""a"" // 3 A();B( // 4 );C(); // 5 D(); // 6 } static void A() { } static void B() { } static void C() { } static void D() { } }".NormalizeLineEndings(); var treeB = SyntaxFactory.ParseSyntaxTree(sourceB, path: "b.cs"); treeB.GetDiagnostics().Verify(); var actualLineMappings = GetLineMappings(treeB); var expectedLineMappings = new[] { "(0,0)-(2,23) -> : (0,0)-(2,23)", "(4,0)-(12,1),2 -> a: (0,9)-(0,15)", }; AssertEx.Equal(expectedLineMappings, actualLineMappings); var statements = GetStatementsAndExpressionBodies(treeB); var actualTextSpans = statements.SelectAsArray(s => GetTextMapping(textA, treeB, s)); var expectedTextSpans = new[] { (@"A();", @"[|A();B(|]"), (@"B( // 4...", @"[|B( );|]".NormalizeLineEndings()), (@"C();", @"[|C();|]"), (@"D();", @"[|D();|]"), }; AssertEx.Equal(expectedTextSpans, actualTextSpans); } // 2. Character offset [WorkItem(4747, "https://github.com/dotnet/csharplang/issues/4747")] [Fact] public void LineSpanDirective_Example2() { string sourceA = @"@page ""/"" @F(() => 1+1, () => 2+2 )".NormalizeLineEndings(); var textA = SourceText.From(sourceA); string sourceB = @"#line hidden class Page { void Render() { #line (2,2)-(4,1) 16 ""page.razor"" // spanof('F(...)') _builder.Add(F(() => 1+1, // 5 () => 2+2 // 6 )); // 7 #line hidden } }".NormalizeLineEndings(); var treeB = SyntaxFactory.ParseSyntaxTree(sourceB, path: "page.razor.g.cs"); treeB.GetDiagnostics().Verify(); var actualLineMappings = GetLineMappings(treeB); var expectedLineMappings = new[] { "(1,0)-(4,3) -> : (0,0)-(0,0)", "(6,0)-(8,40),15 -> page.razor: (1,1)-(3,1)", "(10,0)-(11,1) -> : (0,0)-(0,0)", }; AssertEx.Equal(expectedLineMappings, actualLineMappings); var textB = SourceText.From(sourceB); var actualVisibility = textB.Lines.Select(line => treeB.GetLineVisibility(line.Start)).ToImmutableArray(); var expectedVisibility = new[] { LineVisibility.BeforeFirstLineDirective, LineVisibility.Hidden, LineVisibility.Hidden, LineVisibility.Hidden, LineVisibility.Hidden, LineVisibility.Hidden, LineVisibility.Visible, LineVisibility.Visible, LineVisibility.Visible, LineVisibility.Visible, LineVisibility.Hidden, LineVisibility.Hidden, }; AssertEx.Equal(expectedVisibility, actualVisibility); var statements = GetStatementsAndExpressionBodies(treeB); var actualTextSpans = statements.SelectAsArray(s => GetTextMapping(textA, treeB, s)); var expectedTextSpans = new[] { (@"_builder.Add(F(() => 1+1, // 5...", @"[|F(() => 1+1, () => 2+2 )|]".NormalizeLineEndings()), (@"1+1", @"[|1+1|]"), (@"2+2", @"[|2+2|]"), }; AssertEx.Equal(expectedTextSpans, actualTextSpans); } // 3. Razor: Single-line span [WorkItem(4747, "https://github.com/dotnet/csharplang/issues/4747")] [Fact] public void LineSpanDirective_Example3() { string sourceA = @"@page ""/"" Time: @DateTime.Now ".NormalizeLineEndings(); var textA = SourceText.From(sourceA); string sourceB = @"#line hidden class Page { void Render() { _builder.Add(""Time:""); #line (2,8)-(2,19) 15 ""page.razor"" // spanof('DateTime.Now') _builder.Add(DateTime.Now); #line hidden } }".NormalizeLineEndings(); var treeB = SyntaxFactory.ParseSyntaxTree(sourceB, path: "page.razor.g.cs"); treeB.GetDiagnostics().Verify(); var actualLineMappings = GetLineMappings(treeB); var expectedLineMappings = new[] { "(1,0)-(5,26) -> : (0,0)-(0,0)", "(7,0)-(7,31),14 -> page.razor: (1,7)-(1,19)", "(9,0)-(10,1) -> : (0,0)-(0,0)", }; AssertEx.Equal(expectedLineMappings, actualLineMappings); var statements = GetStatementsAndExpressionBodies(treeB); var actualTextSpans = statements.SelectAsArray(s => GetTextMapping(textA, treeB, s)); var expectedTextSpans = new[] { (@"_builder.Add(""Time:"");", @"[||]"), (@"_builder.Add(DateTime.Now);", @"[|DateTime.Now|]"), }; AssertEx.Equal(expectedTextSpans, actualTextSpans); } // 4. Razor: Multi-line span [WorkItem(4747, "https://github.com/dotnet/csharplang/issues/4747")] [Fact] public void LineSpanDirective_Example4() { string sourceA = @"@page ""/"" @JsonToHtml(@"" { """"key1"""": """"value1"""", """"key2"""": """"value2"""" }"")".NormalizeLineEndings(); var textA = SourceText.From(sourceA); string sourceB = @"#line hidden class Page { void Render() { #line (2,2)-(6,3) 16 ""page.razor"" // spanof('JsonToHtml(...)') _builder.Add(JsonToHtml(@"" { """"key1"""": """"value1"""", """"key2"""": """"value2"""" }"")); #line hidden } }".NormalizeLineEndings(); var treeB = SyntaxFactory.ParseSyntaxTree(sourceB, path: "page.razor.g.cs"); treeB.GetDiagnostics().Verify(); var actualLineMappings = GetLineMappings(treeB); var expectedLineMappings = new[] { "(1,0)-(4,3) -> : (0,0)-(0,0)", "(6,0)-(10,7),15 -> page.razor: (1,1)-(5,3)", "(12,0)-(13,1) -> : (0,0)-(0,0)", }; AssertEx.Equal(expectedLineMappings, actualLineMappings); var statements = GetStatementsAndExpressionBodies(treeB); var actualTextSpans = statements.SelectAsArray(s => GetTextMapping(textA, treeB, s)); var expectedTextSpans = new[] { (@"_builder.Add(JsonToHtml(@""...", @"[|JsonToHtml(@"" { """"key1"""": """"value1"""", """"key2"""": """"value2"""" }"")|]".NormalizeLineEndings()), }; AssertEx.Equal(expectedTextSpans, actualTextSpans); } // 5i. Razor: block constructs [WorkItem(4747, "https://github.com/dotnet/csharplang/issues/4747")] [Fact] public void LineSpanDirective_Example5i() { string sourceA = @"@Html.Helper(() => { <p>Hello World</p> @DateTime.Now })".NormalizeLineEndings(); var textA = SourceText.From(sourceA); string sourceB = @"using System; class Page { Builder _builder; void Execute() { #line (1, 2) - (5, 2) 22 ""a.razor"" // spanof('HtmlHelper(() => { ... })') _builder.Add(Html.Helper(() => #line 2 ""a.razor"" // lineof('{') { #line (4, 6) - (4, 17) 26 ""a.razor"" // spanof('DateTime.Now') _builder.Add(DateTime.Now); #line 5 ""a.razor"" // lineof('})') }) #line hidden ); } }".NormalizeLineEndings(); var treeB = SyntaxFactory.ParseSyntaxTree(sourceB, path: "a.razor.g.cs"); treeB.GetDiagnostics().Verify(); var actualLineMappings = GetLineMappings(treeB); var expectedLineMappings = new[] { "(0,0)-(5,7) -> : (0,0)-(5,7)", "(7,0)-(7,40),21 -> a.razor: (0,1)-(4,2)", "(9,0)-(9,11) -> a.razor: (1,0)-(1,11)", "(11,0)-(11,41),25 -> a.razor: (3,5)-(3,17)", "(13,0)-(13,12) -> a.razor: (4,0)-(4,12)", "(15,0)-(17,1) -> : (0,0)-(0,0)", }; AssertEx.Equal(expectedLineMappings, actualLineMappings); var statements = GetStatementsAndExpressionBodies(treeB); var actualTextSpans = statements.SelectAsArray(s => GetTextMapping(textA, treeB, s)); var expectedTextSpans = new[] { (@"_builder.Add(Html.Helper(() =>...", @"[|Html.Helper(() => { <p>Hello World</p> @DateTime.Now })|]".NormalizeLineEndings()), (@"_builder.Add(DateTime.Now);", @"[|DateTime.Now|]"), }; AssertEx.Equal(expectedTextSpans, actualTextSpans); } private static ImmutableArray<SyntaxNode> GetStatementsAndExpressionBodies(SyntaxTree tree) { var builder = ArrayBuilder<SyntaxNode>.GetInstance(); foreach (var syntax in tree.GetRoot().DescendantNodesAndSelf()) { switch (syntax) { case ExpressionStatementSyntax: builder.Add(syntax); break; case ParenthesizedLambdaExpressionSyntax lambda: builder.AddIfNotNull(lambda.ExpressionBody); break; case SimpleLambdaExpressionSyntax lambda: builder.AddIfNotNull(lambda.ExpressionBody); break; } } return builder.ToImmutableAndFree(); } private static ImmutableArray<string> GetLineMappings(SyntaxTree tree) { var directives = tree.GetRoot().DescendantNodesAndSelf(descendIntoTrivia: true).OfType<DirectiveTriviaSyntax>(); foreach (var directive in directives) { Assert.NotEqual(SyntaxKind.None, directive.DirectiveNameToken.Kind()); } return tree.GetLineMappings().Select(mapping => mapping.ToString()!).ToImmutableArray(); } private static (string, string) GetTextMapping(SourceText mappedText, SyntaxTree unmappedText, SyntaxNode syntax) { return (getDescription(syntax), getMapping(mappedText, unmappedText, syntax)); static string getDescription(SyntaxNode syntax) { var description = syntax.ToString(); int index = description.IndexOfAny(new[] { '\r', '\n' }); return index < 0 ? description : description.Substring(0, index) + "..."; } static string getMapping(SourceText mappedText, SyntaxTree unmappedText, SyntaxNode syntax) { var mappedLineAndPositionSpan = unmappedText.GetMappedLineSpanAndVisibility(syntax.Span, out _); var span = getTextSpan(mappedText.Lines, mappedLineAndPositionSpan.Span); return $"[|{mappedText.GetSubText(span)}|]"; } static TextSpan getTextSpan(TextLineCollection lines, LinePositionSpan span) { return TextSpan.FromBounds(getTextPosition(lines, span.Start), getTextPosition(lines, span.End)); } static int getTextPosition(TextLineCollection lines, LinePosition position) { if (position.Line < lines.Count) { var line = lines[position.Line]; return Math.Min(line.Start + position.Character, line.End); } return (lines.Count == 0) ? 0 : lines[^1].End; } } [Fact] public void Diagnostics() { var source = @"class Program { static void Main() { #line (3, 3) - (6, 6) 8 ""a.txt"" A(); #line default B(); #line (1, 1) - (1, 100) ""b.txt"" C(); } }".NormalizeLineEndings(); var comp = CreateCompilation(source); comp.VerifyDiagnostics( // b.txt(1,9): error CS0103: The name 'C' does not exist in the current context // C(); Diagnostic(ErrorCode.ERR_NameNotInContext, "C").WithArguments("C").WithLocation(1, 9), // a.txt(3,4): error CS0103: The name 'A' does not exist in the current context // A(); Diagnostic(ErrorCode.ERR_NameNotInContext, "A").WithArguments("A").WithLocation(3, 4), // (8,9): error CS0103: The name 'B' does not exist in the current context // B(); Diagnostic(ErrorCode.ERR_NameNotInContext, "B").WithArguments("B").WithLocation(8, 9)); } [Fact] public void SequencePoints() { var source = @"class Program { static void Main() { #line (3, 3) - (6, 6) 8 ""a.txt"" A(); #line default B(); #line (1, 1) - (1, 100) ""b.txt"" C(); #line (2, 3) - (2, 4) 9 ""a.txt"" D(); } static void A() { } static void B() { } static void C() { } static void D() { } }".NormalizeLineEndings(); var verifier = CompileAndVerify(source, options: TestOptions.DebugDll); verifier.VerifyIL("Program.Main", sequencePoints: "Program.Main", expectedIL: @"{ // Code size 26 (0x1a) .maxstack 0 -IL_0000: nop -IL_0001: call ""void Program.A()"" IL_0006: nop -IL_0007: call ""void Program.B()"" IL_000c: nop -IL_000d: call ""void Program.C()"" IL_0012: nop -IL_0013: call ""void Program.D()"" IL_0018: nop -IL_0019: ret }"); verifier.VerifyPdb("Program.Main", expectedPdb: @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> <file id=""2"" name=""a.txt"" language=""C#"" /> <file id=""3"" name=""b.txt"" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""3"" startColumn=""4"" endLine=""3"" endColumn=""8"" document=""2"" /> <entry offset=""0x7"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""13"" document=""1"" /> <entry offset=""0xd"" startLine=""1"" startColumn=""9"" endLine=""1"" endColumn=""13"" document=""3"" /> <entry offset=""0x13"" startLine=""2"" startColumn=""3"" endLine=""2"" endColumn=""5"" document=""2"" /> <entry offset=""0x19"" startLine=""3"" startColumn=""5"" endLine=""3"" endColumn=""6"" document=""2"" /> </sequencePoints> </method> </methods> </symbols> "); } } }
-1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/CSharp/Portable/Simplification/Reducers/CSharpDefaultExpressionReducer.Rewriter.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.Threading; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Simplification { internal partial class CSharpDefaultExpressionReducer { private class Rewriter : AbstractReductionRewriter { public Rewriter(ObjectPool<IReductionRewriter> pool) : base(pool) { _simplifyDefaultExpression = SimplifyDefaultExpression; } private readonly Func<DefaultExpressionSyntax, SemanticModel, OptionSet, CancellationToken, SyntaxNode> _simplifyDefaultExpression; private SyntaxNode SimplifyDefaultExpression( DefaultExpressionSyntax node, SemanticModel semanticModel, OptionSet optionSet, CancellationToken cancellationToken) { var preferSimpleDefaultExpression = optionSet.GetOption(CSharpCodeStyleOptions.PreferSimpleDefaultExpression).Value; if (node.CanReplaceWithDefaultLiteral(ParseOptions, preferSimpleDefaultExpression, semanticModel, cancellationToken)) { return SyntaxFactory.LiteralExpression(SyntaxKind.DefaultLiteralExpression) .WithTriviaFrom(node); } return node; } public override SyntaxNode VisitDefaultExpression(DefaultExpressionSyntax node) { return SimplifyNode( node, newNode: base.VisitDefaultExpression(node), parentNode: node.Parent, simplifier: _simplifyDefaultExpression); } } } }
// Licensed to the .NET Foundation under one or more 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.Threading; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Simplification { internal partial class CSharpDefaultExpressionReducer { private class Rewriter : AbstractReductionRewriter { public Rewriter(ObjectPool<IReductionRewriter> pool) : base(pool) { _simplifyDefaultExpression = SimplifyDefaultExpression; } private readonly Func<DefaultExpressionSyntax, SemanticModel, OptionSet, CancellationToken, SyntaxNode> _simplifyDefaultExpression; private SyntaxNode SimplifyDefaultExpression( DefaultExpressionSyntax node, SemanticModel semanticModel, OptionSet optionSet, CancellationToken cancellationToken) { var preferSimpleDefaultExpression = optionSet.GetOption(CSharpCodeStyleOptions.PreferSimpleDefaultExpression).Value; if (node.CanReplaceWithDefaultLiteral(ParseOptions, preferSimpleDefaultExpression, semanticModel, cancellationToken)) { return SyntaxFactory.LiteralExpression(SyntaxKind.DefaultLiteralExpression) .WithTriviaFrom(node); } return node; } public override SyntaxNode VisitDefaultExpression(DefaultExpressionSyntax node) { return SimplifyNode( node, newNode: base.VisitDefaultExpression(node), parentNode: node.Parent, simplifier: _simplifyDefaultExpression); } } } }
-1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/Emit/CodeGen/CodeGenAsyncEHTests.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 Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class CodeGenAsyncEHTests : EmitMetadataTestBase { private static readonly MetadataReference[] s_asyncRefs = new[] { MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929 }; public CodeGenAsyncEHTests() { } private CompilationVerifier CompileAndVerify(string source, string expectedOutput = null, IEnumerable<MetadataReference> references = null, CSharpCompilationOptions options = null) { references = (references != null) ? references.Concat(s_asyncRefs) : s_asyncRefs; return base.CompileAndVerify(source, targetFramework: TargetFramework.Empty, expectedOutput: expectedOutput, references: references, options: options); } [Fact] [WorkItem(624970, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624970")] public void AsyncWithEH() { var source = @" using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; class Test { static int awaitCount = 0; static int finallyCount = 0; static void LogAwait() { Interlocked.Increment(ref awaitCount); } static void LogException() { Interlocked.Increment(ref finallyCount); } public static async void F(AutoResetEvent handle) { try { await Task.Factory.StartNew(LogAwait); try { await Task.Factory.StartNew(LogAwait); try { await Task.Factory.StartNew(LogAwait); try { await Task.Factory.StartNew(LogAwait); throw new Exception(); } catch (Exception) { } finally { LogException(); } await Task.Factory.StartNew(LogAwait); throw new Exception(); } catch (Exception) { } finally { LogException(); } await Task.Factory.StartNew(LogAwait); throw new Exception(); } catch (Exception) { } finally { LogException(); } await Task.Factory.StartNew(LogAwait); } finally { handle.Set(); } } public static void Main2(int i) { try { awaitCount = 0; finallyCount = 0; var handle = new AutoResetEvent(false); F(handle); var completed = handle.WaitOne(1000 * 60); if (completed) { if (awaitCount != 7 || finallyCount != 3) { throw new Exception(""failed at i="" + i); } } else { Console.WriteLine(""Test did not complete in time.""); } } catch (Exception ex) { Console.WriteLine(""unexpected exception thrown:""); Console.WriteLine(ex.ToString()); } } public static void Main() { for (int i = 0; i < 1500; i++) { Main2(i); } } }"; var expected = @""; CompileAndVerify(source, expectedOutput: expected); } [WorkItem(14878, "https://github.com/dotnet/roslyn/issues/14878")] [Fact] public void AsyncWithEHCodeQuality() { var source = @" using System; using System.Threading.Tasks; class Test { static async Task<int> G() { int x = 1; try { try { try { await Task.Yield(); x += 1; await Task.Yield(); x += 1; await Task.Yield(); x += 1; await Task.Yield(); x += 1; await Task.Yield(); x += 1; await Task.Yield(); x += 1; } finally { x += 1; } } finally { x += 1; } } finally { x += 1; } return x; } public static void Main() { Task<int> t2 = G(); t2.Wait(1000 * 60); Console.WriteLine(t2.Result); } }"; var expected = @" 10 "; CompileAndVerify(source, expectedOutput: expected). VerifyIL("Test.<G>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 819 (0x333) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_2, System.Runtime.CompilerServices.YieldAwaitable V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int Test.<G>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: ldc.i4.5 IL_0009: ble.un.s IL_0012 IL_000b: ldarg.0 IL_000c: ldc.i4.1 IL_000d: stfld ""int Test.<G>d__0.<x>5__2"" IL_0012: nop .try { IL_0013: ldloc.0 IL_0014: ldc.i4.5 IL_0015: pop IL_0016: pop IL_0017: nop .try { IL_0018: ldloc.0 IL_0019: ldc.i4.5 IL_001a: pop IL_001b: pop IL_001c: nop .try { IL_001d: ldloc.0 IL_001e: switch ( IL_0075, IL_00e0, IL_014b, IL_01b6, IL_0221, IL_028c) IL_003b: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()"" IL_0040: stloc.3 IL_0041: ldloca.s V_3 IL_0043: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()"" IL_0048: stloc.2 IL_0049: ldloca.s V_2 IL_004b: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get"" IL_0050: brtrue.s IL_0091 IL_0052: ldarg.0 IL_0053: ldc.i4.0 IL_0054: dup IL_0055: stloc.0 IL_0056: stfld ""int Test.<G>d__0.<>1__state"" IL_005b: ldarg.0 IL_005c: ldloc.2 IL_005d: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<G>d__0.<>u__1"" IL_0062: ldarg.0 IL_0063: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<G>d__0.<>t__builder"" IL_0068: ldloca.s V_2 IL_006a: ldarg.0 IL_006b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Test.<G>d__0>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Test.<G>d__0)"" IL_0070: leave IL_0332 IL_0075: ldarg.0 IL_0076: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<G>d__0.<>u__1"" IL_007b: stloc.2 IL_007c: ldarg.0 IL_007d: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<G>d__0.<>u__1"" IL_0082: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"" IL_0088: ldarg.0 IL_0089: ldc.i4.m1 IL_008a: dup IL_008b: stloc.0 IL_008c: stfld ""int Test.<G>d__0.<>1__state"" IL_0091: ldloca.s V_2 IL_0093: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()"" IL_0098: ldarg.0 IL_0099: ldarg.0 IL_009a: ldfld ""int Test.<G>d__0.<x>5__2"" IL_009f: ldc.i4.1 IL_00a0: add IL_00a1: stfld ""int Test.<G>d__0.<x>5__2"" IL_00a6: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()"" IL_00ab: stloc.3 IL_00ac: ldloca.s V_3 IL_00ae: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()"" IL_00b3: stloc.2 IL_00b4: ldloca.s V_2 IL_00b6: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get"" IL_00bb: brtrue.s IL_00fc IL_00bd: ldarg.0 IL_00be: ldc.i4.1 IL_00bf: dup IL_00c0: stloc.0 IL_00c1: stfld ""int Test.<G>d__0.<>1__state"" IL_00c6: ldarg.0 IL_00c7: ldloc.2 IL_00c8: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<G>d__0.<>u__1"" IL_00cd: ldarg.0 IL_00ce: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<G>d__0.<>t__builder"" IL_00d3: ldloca.s V_2 IL_00d5: ldarg.0 IL_00d6: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Test.<G>d__0>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Test.<G>d__0)"" IL_00db: leave IL_0332 IL_00e0: ldarg.0 IL_00e1: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<G>d__0.<>u__1"" IL_00e6: stloc.2 IL_00e7: ldarg.0 IL_00e8: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<G>d__0.<>u__1"" IL_00ed: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"" IL_00f3: ldarg.0 IL_00f4: ldc.i4.m1 IL_00f5: dup IL_00f6: stloc.0 IL_00f7: stfld ""int Test.<G>d__0.<>1__state"" IL_00fc: ldloca.s V_2 IL_00fe: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()"" IL_0103: ldarg.0 IL_0104: ldarg.0 IL_0105: ldfld ""int Test.<G>d__0.<x>5__2"" IL_010a: ldc.i4.1 IL_010b: add IL_010c: stfld ""int Test.<G>d__0.<x>5__2"" IL_0111: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()"" IL_0116: stloc.3 IL_0117: ldloca.s V_3 IL_0119: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()"" IL_011e: stloc.2 IL_011f: ldloca.s V_2 IL_0121: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get"" IL_0126: brtrue.s IL_0167 IL_0128: ldarg.0 IL_0129: ldc.i4.2 IL_012a: dup IL_012b: stloc.0 IL_012c: stfld ""int Test.<G>d__0.<>1__state"" IL_0131: ldarg.0 IL_0132: ldloc.2 IL_0133: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<G>d__0.<>u__1"" IL_0138: ldarg.0 IL_0139: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<G>d__0.<>t__builder"" IL_013e: ldloca.s V_2 IL_0140: ldarg.0 IL_0141: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Test.<G>d__0>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Test.<G>d__0)"" IL_0146: leave IL_0332 IL_014b: ldarg.0 IL_014c: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<G>d__0.<>u__1"" IL_0151: stloc.2 IL_0152: ldarg.0 IL_0153: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<G>d__0.<>u__1"" IL_0158: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"" IL_015e: ldarg.0 IL_015f: ldc.i4.m1 IL_0160: dup IL_0161: stloc.0 IL_0162: stfld ""int Test.<G>d__0.<>1__state"" IL_0167: ldloca.s V_2 IL_0169: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()"" IL_016e: ldarg.0 IL_016f: ldarg.0 IL_0170: ldfld ""int Test.<G>d__0.<x>5__2"" IL_0175: ldc.i4.1 IL_0176: add IL_0177: stfld ""int Test.<G>d__0.<x>5__2"" IL_017c: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()"" IL_0181: stloc.3 IL_0182: ldloca.s V_3 IL_0184: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()"" IL_0189: stloc.2 IL_018a: ldloca.s V_2 IL_018c: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get"" IL_0191: brtrue.s IL_01d2 IL_0193: ldarg.0 IL_0194: ldc.i4.3 IL_0195: dup IL_0196: stloc.0 IL_0197: stfld ""int Test.<G>d__0.<>1__state"" IL_019c: ldarg.0 IL_019d: ldloc.2 IL_019e: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<G>d__0.<>u__1"" IL_01a3: ldarg.0 IL_01a4: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<G>d__0.<>t__builder"" IL_01a9: ldloca.s V_2 IL_01ab: ldarg.0 IL_01ac: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Test.<G>d__0>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Test.<G>d__0)"" IL_01b1: leave IL_0332 IL_01b6: ldarg.0 IL_01b7: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<G>d__0.<>u__1"" IL_01bc: stloc.2 IL_01bd: ldarg.0 IL_01be: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<G>d__0.<>u__1"" IL_01c3: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"" IL_01c9: ldarg.0 IL_01ca: ldc.i4.m1 IL_01cb: dup IL_01cc: stloc.0 IL_01cd: stfld ""int Test.<G>d__0.<>1__state"" IL_01d2: ldloca.s V_2 IL_01d4: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()"" IL_01d9: ldarg.0 IL_01da: ldarg.0 IL_01db: ldfld ""int Test.<G>d__0.<x>5__2"" IL_01e0: ldc.i4.1 IL_01e1: add IL_01e2: stfld ""int Test.<G>d__0.<x>5__2"" IL_01e7: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()"" IL_01ec: stloc.3 IL_01ed: ldloca.s V_3 IL_01ef: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()"" IL_01f4: stloc.2 IL_01f5: ldloca.s V_2 IL_01f7: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get"" IL_01fc: brtrue.s IL_023d IL_01fe: ldarg.0 IL_01ff: ldc.i4.4 IL_0200: dup IL_0201: stloc.0 IL_0202: stfld ""int Test.<G>d__0.<>1__state"" IL_0207: ldarg.0 IL_0208: ldloc.2 IL_0209: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<G>d__0.<>u__1"" IL_020e: ldarg.0 IL_020f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<G>d__0.<>t__builder"" IL_0214: ldloca.s V_2 IL_0216: ldarg.0 IL_0217: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Test.<G>d__0>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Test.<G>d__0)"" IL_021c: leave IL_0332 IL_0221: ldarg.0 IL_0222: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<G>d__0.<>u__1"" IL_0227: stloc.2 IL_0228: ldarg.0 IL_0229: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<G>d__0.<>u__1"" IL_022e: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"" IL_0234: ldarg.0 IL_0235: ldc.i4.m1 IL_0236: dup IL_0237: stloc.0 IL_0238: stfld ""int Test.<G>d__0.<>1__state"" IL_023d: ldloca.s V_2 IL_023f: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()"" IL_0244: ldarg.0 IL_0245: ldarg.0 IL_0246: ldfld ""int Test.<G>d__0.<x>5__2"" IL_024b: ldc.i4.1 IL_024c: add IL_024d: stfld ""int Test.<G>d__0.<x>5__2"" IL_0252: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()"" IL_0257: stloc.3 IL_0258: ldloca.s V_3 IL_025a: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()"" IL_025f: stloc.2 IL_0260: ldloca.s V_2 IL_0262: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get"" IL_0267: brtrue.s IL_02a8 IL_0269: ldarg.0 IL_026a: ldc.i4.5 IL_026b: dup IL_026c: stloc.0 IL_026d: stfld ""int Test.<G>d__0.<>1__state"" IL_0272: ldarg.0 IL_0273: ldloc.2 IL_0274: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<G>d__0.<>u__1"" IL_0279: ldarg.0 IL_027a: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<G>d__0.<>t__builder"" IL_027f: ldloca.s V_2 IL_0281: ldarg.0 IL_0282: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Test.<G>d__0>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Test.<G>d__0)"" IL_0287: leave IL_0332 IL_028c: ldarg.0 IL_028d: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<G>d__0.<>u__1"" IL_0292: stloc.2 IL_0293: ldarg.0 IL_0294: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<G>d__0.<>u__1"" IL_0299: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"" IL_029f: ldarg.0 IL_02a0: ldc.i4.m1 IL_02a1: dup IL_02a2: stloc.0 IL_02a3: stfld ""int Test.<G>d__0.<>1__state"" IL_02a8: ldloca.s V_2 IL_02aa: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()"" IL_02af: ldarg.0 IL_02b0: ldarg.0 IL_02b1: ldfld ""int Test.<G>d__0.<x>5__2"" IL_02b6: ldc.i4.1 IL_02b7: add IL_02b8: stfld ""int Test.<G>d__0.<x>5__2"" IL_02bd: leave.s IL_02d2 } finally { IL_02bf: ldloc.0 IL_02c0: ldc.i4.0 IL_02c1: bge.s IL_02d1 IL_02c3: ldarg.0 IL_02c4: ldarg.0 IL_02c5: ldfld ""int Test.<G>d__0.<x>5__2"" IL_02ca: ldc.i4.1 IL_02cb: add IL_02cc: stfld ""int Test.<G>d__0.<x>5__2"" IL_02d1: endfinally } IL_02d2: leave.s IL_02e7 } finally { IL_02d4: ldloc.0 IL_02d5: ldc.i4.0 IL_02d6: bge.s IL_02e6 IL_02d8: ldarg.0 IL_02d9: ldarg.0 IL_02da: ldfld ""int Test.<G>d__0.<x>5__2"" IL_02df: ldc.i4.1 IL_02e0: add IL_02e1: stfld ""int Test.<G>d__0.<x>5__2"" IL_02e6: endfinally } IL_02e7: leave.s IL_02fc } finally { IL_02e9: ldloc.0 IL_02ea: ldc.i4.0 IL_02eb: bge.s IL_02fb IL_02ed: ldarg.0 IL_02ee: ldarg.0 IL_02ef: ldfld ""int Test.<G>d__0.<x>5__2"" IL_02f4: ldc.i4.1 IL_02f5: add IL_02f6: stfld ""int Test.<G>d__0.<x>5__2"" IL_02fb: endfinally } IL_02fc: ldarg.0 IL_02fd: ldfld ""int Test.<G>d__0.<x>5__2"" IL_0302: stloc.1 IL_0303: leave.s IL_031e } catch System.Exception { IL_0305: stloc.s V_4 IL_0307: ldarg.0 IL_0308: ldc.i4.s -2 IL_030a: stfld ""int Test.<G>d__0.<>1__state"" IL_030f: ldarg.0 IL_0310: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<G>d__0.<>t__builder"" IL_0315: ldloc.s V_4 IL_0317: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_031c: leave.s IL_0332 } IL_031e: ldarg.0 IL_031f: ldc.i4.s -2 IL_0321: stfld ""int Test.<G>d__0.<>1__state"" IL_0326: ldarg.0 IL_0327: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<G>d__0.<>t__builder"" IL_032c: ldloc.1 IL_032d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_0332: ret } "); } [Fact, WorkItem(855080, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/855080")] public void GenericCatchVariableInAsyncMethod() { var source = @" using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Console.WriteLine(Bar().Result); } static async Task<int> Bar() { NotImplementedException ex = await Goo<NotImplementedException>(); return 3; } public static async Task<T> Goo<T>() where T : Exception { Task<int> task = null; if (task != null) await task; T result = null; try { } catch (T ex) { result = ex; } return result; } } } "; CompileAndVerify(source, expectedOutput: "3"); } [Fact] public void AsyncWithException1() { var source = @" using System; using System.Threading.Tasks; class Test { static async Task<int> F() { throw new Exception(); } static async Task<int> G() { try { return await F(); } catch(Exception) { return -1; } } public static void Main() { Task<int> t2 = G(); t2.Wait(1000 * 60); Console.WriteLine(t2.Result); } }"; var expected = @" -1 "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void AsyncWithException2() { var source = @" using System; using System.Threading.Tasks; class Test { static async Task<int> F() { throw new Exception(); } static async Task<int> H() { return await F(); } public static void Main() { Task<int> t1 = H(); try { t1.Wait(1000 * 60); } catch (AggregateException) { Console.WriteLine(""exception""); } } }"; var expected = @" exception "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void AsyncInFinally001() { var source = @" using System; using System.Threading.Tasks; class Test { static async Task<int> F() { return 2; } static async Task<int> G() { int x = 42; try { } finally { x = await F(); } return x; } public static void Main() { Task<int> t2 = G(); t2.Wait(1000 * 60); Console.WriteLine(t2.Result); } }"; var expected = @" 2 "; CompileAndVerify(source, expectedOutput: expected). VerifyIL("Test.<G>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 210 (0xd2) .maxstack 3 .locals init (int V_0, int V_1, object V_2, System.Runtime.CompilerServices.TaskAwaiter<int> V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int Test.<G>d__1.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0058 IL_000a: ldarg.0 IL_000b: ldnull IL_000c: stfld ""object Test.<G>d__1.<>7__wrap1"" IL_0011: ldarg.0 IL_0012: ldc.i4.0 IL_0013: stfld ""int Test.<G>d__1.<>7__wrap2"" .try { IL_0018: leave.s IL_0024 } catch object { IL_001a: stloc.2 IL_001b: ldarg.0 IL_001c: ldloc.2 IL_001d: stfld ""object Test.<G>d__1.<>7__wrap1"" IL_0022: leave.s IL_0024 } IL_0024: call ""System.Threading.Tasks.Task<int> Test.F()"" IL_0029: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_002e: stloc.3 IL_002f: ldloca.s V_3 IL_0031: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_0036: brtrue.s IL_0074 IL_0038: ldarg.0 IL_0039: ldc.i4.0 IL_003a: dup IL_003b: stloc.0 IL_003c: stfld ""int Test.<G>d__1.<>1__state"" IL_0041: ldarg.0 IL_0042: ldloc.3 IL_0043: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<G>d__1.<>u__1"" IL_0048: ldarg.0 IL_0049: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<G>d__1.<>t__builder"" IL_004e: ldloca.s V_3 IL_0050: ldarg.0 IL_0051: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Test.<G>d__1>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Test.<G>d__1)"" IL_0056: leave.s IL_00d1 IL_0058: ldarg.0 IL_0059: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<G>d__1.<>u__1"" IL_005e: stloc.3 IL_005f: ldarg.0 IL_0060: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<G>d__1.<>u__1"" IL_0065: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_006b: ldarg.0 IL_006c: ldc.i4.m1 IL_006d: dup IL_006e: stloc.0 IL_006f: stfld ""int Test.<G>d__1.<>1__state"" IL_0074: ldloca.s V_3 IL_0076: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_007b: ldarg.0 IL_007c: ldfld ""object Test.<G>d__1.<>7__wrap1"" IL_0081: stloc.2 IL_0082: ldloc.2 IL_0083: brfalse.s IL_009a IL_0085: ldloc.2 IL_0086: isinst ""System.Exception"" IL_008b: dup IL_008c: brtrue.s IL_0090 IL_008e: ldloc.2 IL_008f: throw IL_0090: call ""System.Runtime.ExceptionServices.ExceptionDispatchInfo System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(System.Exception)"" IL_0095: callvirt ""void System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()"" IL_009a: ldarg.0 IL_009b: ldnull IL_009c: stfld ""object Test.<G>d__1.<>7__wrap1"" IL_00a1: stloc.1 IL_00a2: leave.s IL_00bd } catch System.Exception { IL_00a4: stloc.s V_4 IL_00a6: ldarg.0 IL_00a7: ldc.i4.s -2 IL_00a9: stfld ""int Test.<G>d__1.<>1__state"" IL_00ae: ldarg.0 IL_00af: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<G>d__1.<>t__builder"" IL_00b4: ldloc.s V_4 IL_00b6: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_00bb: leave.s IL_00d1 } IL_00bd: ldarg.0 IL_00be: ldc.i4.s -2 IL_00c0: stfld ""int Test.<G>d__1.<>1__state"" IL_00c5: ldarg.0 IL_00c6: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<G>d__1.<>t__builder"" IL_00cb: ldloc.1 IL_00cc: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_00d1: ret } "); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] public void AsyncInFinally002() { var source = @" using System; using System.Threading.Tasks; class Test { static async Task<int> F() { System.Console.Write(""F""); return 2; } static async Task G() { int x = 0; try { throw new Exception(""hello""); } finally { x += await F(); } } public static void Main() { System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture; System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture; try { Task t2 = G(); try { t2.Wait(1000 * 60); } catch (Exception ex) { Console.WriteLine(ex.Message); } } finally { System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture; } } }"; var expected = @"FOne or more errors occurred. "; CompileAndVerify(source, expectedOutput: expected); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void AsyncInFinally003() { var source = @" using System; using System.Threading.Tasks; class Test { static async Task<int> F() { return 2; } static async Task<int> G() { int x = 0; try { x = await F(); return x; } finally { x += await F(); } } public static void Main() { Task<int> t2 = G(); t2.Wait(1000 * 60); Console.WriteLine(t2.Result); } }"; var expected = @" 2 "; var v = CompileAndVerify(source, s_asyncRefs, targetFramework: TargetFramework.Empty, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), expectedOutput: expected, symbolValidator: module => { Assert.Equal(new[] { "<>1__state", "<>t__builder", "<x>5__1", "<>s__2", // pending exception "<>s__3", // pending branch "<>s__4", // return value "<>s__5", // spill "<>s__6", // spill "<>s__7", // spill "<>u__1", // awaiter }, module.GetFieldNames("Test.<G>d__1")); }); v.VerifyPdb("Test.G", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""Test"" methodName=""Main"" /> <methods> <method containingType=""Test"" name=""G""> <customDebugInfo> <forwardIterator name=""&lt;G&gt;d__1"" /> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> <slot kind=""22"" offset=""33"" /> <slot kind=""23"" offset=""33"" /> <slot kind=""20"" offset=""33"" /> <slot kind=""28"" offset=""65"" /> <slot kind=""28"" offset=""156"" /> <slot kind=""28"" offset=""156"" ordinal=""1"" /> </encLocalSlotMap> </customDebugInfo> </method> </methods> </symbols> "); v.VerifyIL("Test.<G>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @"{ // Code size 461 (0x1cd) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, Test.<G>d__1 V_3, object V_4, System.Runtime.CompilerServices.TaskAwaiter<int> V_5, System.Exception V_6, int V_7) ~IL_0000: ldarg.0 IL_0001: ldfld ""int Test.<G>d__1.<>1__state"" IL_0006: stloc.0 .try { ~IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0019 IL_0012: br.s IL_002f IL_0014: br IL_0115 -IL_0019: nop -IL_001a: ldarg.0 IL_001b: ldc.i4.0 IL_001c: stfld ""int Test.<G>d__1.<x>5__1"" ~IL_0021: ldarg.0 IL_0022: ldnull IL_0023: stfld ""object Test.<G>d__1.<>s__2"" IL_0028: ldarg.0 IL_0029: ldc.i4.0 IL_002a: stfld ""int Test.<G>d__1.<>s__3"" ~IL_002f: nop .try { ~IL_0030: ldloc.0 IL_0031: brfalse.s IL_0035 IL_0033: br.s IL_0037 IL_0035: br.s IL_0073 -IL_0037: nop -IL_0038: call ""System.Threading.Tasks.Task<int> Test.F()"" IL_003d: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0042: stloc.2 ~IL_0043: ldloca.s V_2 IL_0045: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_004a: brtrue.s IL_008f IL_004c: ldarg.0 IL_004d: ldc.i4.0 IL_004e: dup IL_004f: stloc.0 IL_0050: stfld ""int Test.<G>d__1.<>1__state"" <IL_0055: ldarg.0 IL_0056: ldloc.2 IL_0057: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<G>d__1.<>u__1"" IL_005c: ldarg.0 IL_005d: stloc.3 IL_005e: ldarg.0 IL_005f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<G>d__1.<>t__builder"" IL_0064: ldloca.s V_2 IL_0066: ldloca.s V_3 IL_0068: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Test.<G>d__1>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Test.<G>d__1)"" IL_006d: nop IL_006e: leave IL_01cc >IL_0073: ldarg.0 IL_0074: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<G>d__1.<>u__1"" IL_0079: stloc.2 IL_007a: ldarg.0 IL_007b: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<G>d__1.<>u__1"" IL_0080: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0086: ldarg.0 IL_0087: ldc.i4.m1 IL_0088: dup IL_0089: stloc.0 IL_008a: stfld ""int Test.<G>d__1.<>1__state"" IL_008f: ldarg.0 IL_0090: ldloca.s V_2 IL_0092: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0097: stfld ""int Test.<G>d__1.<>s__5"" IL_009c: ldarg.0 IL_009d: ldarg.0 IL_009e: ldfld ""int Test.<G>d__1.<>s__5"" IL_00a3: stfld ""int Test.<G>d__1.<x>5__1"" -IL_00a8: ldarg.0 IL_00a9: ldarg.0 IL_00aa: ldfld ""int Test.<G>d__1.<x>5__1"" IL_00af: stfld ""int Test.<G>d__1.<>s__4"" IL_00b4: br.s IL_00b6 IL_00b6: ldarg.0 IL_00b7: ldc.i4.1 IL_00b8: stfld ""int Test.<G>d__1.<>s__3"" IL_00bd: leave.s IL_00cb } catch object { ~IL_00bf: stloc.s V_4 IL_00c1: ldarg.0 IL_00c2: ldloc.s V_4 IL_00c4: stfld ""object Test.<G>d__1.<>s__2"" IL_00c9: leave.s IL_00cb } -IL_00cb: nop -IL_00cc: ldarg.0 IL_00cd: ldarg.0 IL_00ce: ldfld ""int Test.<G>d__1.<x>5__1"" IL_00d3: stfld ""int Test.<G>d__1.<>s__6"" IL_00d8: call ""System.Threading.Tasks.Task<int> Test.F()"" IL_00dd: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_00e2: stloc.s V_5 ~IL_00e4: ldloca.s V_5 IL_00e6: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_00eb: brtrue.s IL_0132 IL_00ed: ldarg.0 IL_00ee: ldc.i4.1 IL_00ef: dup IL_00f0: stloc.0 IL_00f1: stfld ""int Test.<G>d__1.<>1__state"" <IL_00f6: ldarg.0 IL_00f7: ldloc.s V_5 IL_00f9: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<G>d__1.<>u__1"" IL_00fe: ldarg.0 IL_00ff: stloc.3 IL_0100: ldarg.0 IL_0101: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<G>d__1.<>t__builder"" IL_0106: ldloca.s V_5 IL_0108: ldloca.s V_3 IL_010a: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Test.<G>d__1>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Test.<G>d__1)"" IL_010f: nop IL_0110: leave IL_01cc >IL_0115: ldarg.0 IL_0116: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<G>d__1.<>u__1"" IL_011b: stloc.s V_5 IL_011d: ldarg.0 IL_011e: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<G>d__1.<>u__1"" IL_0123: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0129: ldarg.0 IL_012a: ldc.i4.m1 IL_012b: dup IL_012c: stloc.0 IL_012d: stfld ""int Test.<G>d__1.<>1__state"" IL_0132: ldarg.0 IL_0133: ldloca.s V_5 IL_0135: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_013a: stfld ""int Test.<G>d__1.<>s__7"" IL_013f: ldarg.0 IL_0140: ldarg.0 IL_0141: ldfld ""int Test.<G>d__1.<>s__6"" IL_0146: ldarg.0 IL_0147: ldfld ""int Test.<G>d__1.<>s__7"" IL_014c: add IL_014d: stfld ""int Test.<G>d__1.<x>5__1"" -IL_0152: nop ~IL_0153: ldarg.0 IL_0154: ldfld ""object Test.<G>d__1.<>s__2"" IL_0159: stloc.s V_4 IL_015b: ldloc.s V_4 IL_015d: brfalse.s IL_017c IL_015f: ldloc.s V_4 IL_0161: isinst ""System.Exception"" IL_0166: stloc.s V_6 IL_0168: ldloc.s V_6 IL_016a: brtrue.s IL_016f IL_016c: ldloc.s V_4 IL_016e: throw IL_016f: ldloc.s V_6 IL_0171: call ""System.Runtime.ExceptionServices.ExceptionDispatchInfo System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(System.Exception)"" IL_0176: callvirt ""void System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()"" IL_017b: nop IL_017c: ldarg.0 IL_017d: ldfld ""int Test.<G>d__1.<>s__3"" IL_0182: stloc.s V_7 IL_0184: ldloc.s V_7 IL_0186: ldc.i4.1 IL_0187: beq.s IL_018b IL_0189: br.s IL_0194 IL_018b: ldarg.0 IL_018c: ldfld ""int Test.<G>d__1.<>s__4"" IL_0191: stloc.1 IL_0192: leave.s IL_01b7 IL_0194: ldarg.0 IL_0195: ldnull IL_0196: stfld ""object Test.<G>d__1.<>s__2"" IL_019b: leave.s IL_01b7 } catch System.Exception { ~IL_019d: stloc.s V_6 IL_019f: ldarg.0 IL_01a0: ldc.i4.s -2 IL_01a2: stfld ""int Test.<G>d__1.<>1__state"" IL_01a7: ldarg.0 IL_01a8: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<G>d__1.<>t__builder"" IL_01ad: ldloc.s V_6 IL_01af: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_01b4: nop IL_01b5: leave.s IL_01cc } -IL_01b7: ldarg.0 IL_01b8: ldc.i4.s -2 IL_01ba: stfld ""int Test.<G>d__1.<>1__state"" ~IL_01bf: ldarg.0 IL_01c0: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<G>d__1.<>t__builder"" IL_01c5: ldloc.1 IL_01c6: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_01cb: nop IL_01cc: ret }", sequencePoints: "Test+<G>d__1.MoveNext"); } [Fact] public void AsyncInFinally004() { var source = @" using System; using System.Threading.Tasks; class Test { static async Task<int> F() { return 2; } static async Task<int> G() { int x = 0; try { try { throw new Exception(); } finally { x += await F(); } } catch { return x; } } public static void Main() { Task<int> t2 = G(); t2.Wait(1000 * 60); Console.WriteLine(t2.Result); } }"; var expected = @" 2 "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void AsyncInFinallyNested001() { var source = @" using System; using System.Threading.Tasks; class Test { static async Task<int> F(int a) { await Task.Yield(); return a; } static async Task<int> G() { int x = 0; try { try { x = await F(1); goto L1; System.Console.WriteLine(""FAIL""); } finally { x += await F(2); } } finally { try { x += await F(4); } finally { x += await F(8); } } System.Console.WriteLine(""FAIL""); L1: return x; } public static void Main() { Task<int> t2 = G(); t2.Wait(1000 * 60); Console.WriteLine(t2.Result); } }"; var expected = @"15"; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void AsyncInFinallyNested002() { var source = @" using System; using System.Threading.Tasks; class Test { static async Task<int> F(int a) { await Task.Yield(); return a; } static async Task<int> G() { int x = 0; try { try { try { x = await F(1); throw new Exception(""hello""); System.Console.WriteLine(""FAIL""); } finally { x += await F(2); } System.Console.WriteLine(""FAIL""); } finally { try { x += await F(4); } finally { x += await F(8); } } System.Console.WriteLine(""FAIL""); } catch(Exception ex) { System.Console.WriteLine(ex.Message); } return x; } public static void Main() { Task<int> t2 = G(); t2.Wait(1000 * 60); Console.WriteLine(t2.Result); } }"; var expected = @"hello 15"; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void AsyncInFinallyNested003() { var source = @" using System; using System.Threading.Tasks; class Test { static async Task<int> F(int a) { await Task.Yield(); return a; } static async Task<int> G() { int x = 0; try { try { try { x = await F(1); throw new Exception(""hello""); System.Console.WriteLine(""FAIL""); } finally { x += await F(2); } System.Console.WriteLine(""FAIL""); } finally { try { x += await F(4); } finally { x += await F(8); throw new Exception(""bye""); } } System.Console.WriteLine(""FAIL""); } catch(Exception ex) { System.Console.WriteLine(ex.Message); } return x; } public static void Main() { Task<int> t2 = G(); t2.Wait(1000 * 60); Console.WriteLine(t2.Result); } }"; var expected = @"bye 15"; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void AsyncInCatch001() { var source = @" using System; using System.Threading.Tasks; class Test { static async Task<int> F() { return 2; } static async Task<int> G() { int x = 0; try { x = x / x; } catch { x = await F(); } return x; } public static void Main() { Task<int> t2 = G(); t2.Wait(1000 * 60); Console.WriteLine(t2.Result); } }"; var expected = @" 2 "; CompileAndVerify(source, expectedOutput: expected). VerifyIL("Test.<G>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 170 (0xaa) .maxstack 3 .locals init (int V_0, int V_1, int V_2, //x int V_3, System.Runtime.CompilerServices.TaskAwaiter<int> V_4, System.Exception V_5) IL_0000: ldarg.0 IL_0001: ldfld ""int Test.<G>d__1.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0053 IL_000a: ldc.i4.0 IL_000b: stloc.2 IL_000c: ldc.i4.0 IL_000d: stloc.3 .try { IL_000e: ldloc.2 IL_000f: ldloc.2 IL_0010: div IL_0011: stloc.2 IL_0012: leave.s IL_0019 } catch object { IL_0014: pop IL_0015: ldc.i4.1 IL_0016: stloc.3 IL_0017: leave.s IL_0019 } IL_0019: ldloc.3 IL_001a: ldc.i4.1 IL_001b: bne.un.s IL_0078 IL_001d: call ""System.Threading.Tasks.Task<int> Test.F()"" IL_0022: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0027: stloc.s V_4 IL_0029: ldloca.s V_4 IL_002b: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_0030: brtrue.s IL_0070 IL_0032: ldarg.0 IL_0033: ldc.i4.0 IL_0034: dup IL_0035: stloc.0 IL_0036: stfld ""int Test.<G>d__1.<>1__state"" IL_003b: ldarg.0 IL_003c: ldloc.s V_4 IL_003e: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<G>d__1.<>u__1"" IL_0043: ldarg.0 IL_0044: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<G>d__1.<>t__builder"" IL_0049: ldloca.s V_4 IL_004b: ldarg.0 IL_004c: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Test.<G>d__1>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Test.<G>d__1)"" IL_0051: leave.s IL_00a9 IL_0053: ldarg.0 IL_0054: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<G>d__1.<>u__1"" IL_0059: stloc.s V_4 IL_005b: ldarg.0 IL_005c: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<G>d__1.<>u__1"" IL_0061: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0067: ldarg.0 IL_0068: ldc.i4.m1 IL_0069: dup IL_006a: stloc.0 IL_006b: stfld ""int Test.<G>d__1.<>1__state"" IL_0070: ldloca.s V_4 IL_0072: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0077: stloc.2 IL_0078: ldloc.2 IL_0079: stloc.1 IL_007a: leave.s IL_0095 } catch System.Exception { IL_007c: stloc.s V_5 IL_007e: ldarg.0 IL_007f: ldc.i4.s -2 IL_0081: stfld ""int Test.<G>d__1.<>1__state"" IL_0086: ldarg.0 IL_0087: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<G>d__1.<>t__builder"" IL_008c: ldloc.s V_5 IL_008e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_0093: leave.s IL_00a9 } IL_0095: ldarg.0 IL_0096: ldc.i4.s -2 IL_0098: stfld ""int Test.<G>d__1.<>1__state"" IL_009d: ldarg.0 IL_009e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<G>d__1.<>t__builder"" IL_00a3: ldloc.1 IL_00a4: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_00a9: ret } "); } [Fact] public void AsyncInCatchRethrow() { var source = @" using System; using System.Threading.Tasks; class Test { static async Task<int> F() { await Task.Yield(); return 2; } static async Task<int> G() { int x = 0; try { try { x = x / x; } catch { x = await F(); throw; } } catch(DivideByZeroException ex) { x = await F(); System.Console.WriteLine(ex.Message); } return x; } public static void Main() { System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture; System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture; try { Task<int> t2 = G(); t2.Wait(1000 * 60); Console.WriteLine(t2.Result); } finally { System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture; } } }"; var expected = @" Attempted to divide by zero. 2 "; CompileAndVerify(source, expectedOutput: expected); } [WorkItem(74, "https://github.com/dotnet/roslyn/issues/1334")] [Fact] public void AsyncInCatchRethrow01() { var source = @" using System; using System.Threading.Tasks; class Test { static async Task<int> F() { await Task.Yield(); return 2; } static async Task<int> G() { int x = 0; try { try { x = x / x; } catch (ArgumentNullException) { x = await F(); } catch { Console.WriteLine(""rethrowing""); throw; } } catch(DivideByZeroException ex) { x += await F(); System.Console.WriteLine(ex.Message); } return x; } public static void Main() { System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture; System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture; try { Task<int> t2 = G(); t2.Wait(1000 * 60); Console.WriteLine(t2.Result); } finally { System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture; } } }"; var expected = @"rethrowing Attempted to divide by zero. 2 "; CompileAndVerify(source, expectedOutput: expected); } [WorkItem(74, "https://github.com/dotnet/roslyn/issues/1334")] [Fact] public void AsyncInCatchRethrow02() { var source = @" using System; using System.Threading.Tasks; class Test { static async Task<int> F() { await Task.Yield(); return 2; } static async Task<int> G() { int x = 0; try { try { x = x / x; } catch (ArgumentNullException) { Console.WriteLine(""should not get here""); } catch (Exception ex) when (ex == null) { Console.WriteLine(""should not get here""); } catch { x = await F(); Console.WriteLine(""rethrowing""); throw; } } catch(DivideByZeroException ex) { x += await F(); System.Console.WriteLine(ex.Message); } return x; } public static void Main() { System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture; System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture; try { Task<int> t2 = G(); t2.Wait(1000 * 60); Console.WriteLine(t2.Result); } finally { System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture; } } }"; var expected = @"rethrowing Attempted to divide by zero. 4 "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void AsyncInCatchFilter() { var source = @" using System; using System.Threading.Tasks; class Test { static async Task<int> F() { await Task.Yield(); return 2; } static async Task<int> G() { int x = 0; try { try { x = x / x; } catch when(x != 0) { x = await F(); throw; } } catch(Exception ex) when(x == 0 && ((ex = new Exception(""hello"")) != null)) { x = await F(); System.Console.WriteLine(ex.Message); } return x; } public static void Main() { Task<int> t2 = G(); t2.Wait(1000 * 60); Console.WriteLine(t2.Result); } }"; var expected = @" hello 2 "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void AsyncInCatchFilterLifted() { var source = @" using System; using System.Threading.Tasks; class Test { static async Task<int> F() { await Task.Yield(); return 2; } static bool T(Func<bool> f, ref Exception ex) { var result = f(); ex = new Exception(result.ToString()); return result; } static async Task<int> G() { int x = 0; try { x = x / x; } catch(Exception ex) when(T(()=>ex.Message == null, ref ex)) { x = await F(); System.Console.WriteLine(ex.Message); } catch(Exception ex) when(T(()=>ex.Message != null, ref ex)) { x = await F(); System.Console.WriteLine(ex.Message); } return x; } public static void Main() { Task<int> t2 = G(); t2.Wait(1000 * 60); Console.WriteLine(t2.Result); } }"; var expected = @"True 2 "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void AsyncInCatchFinallyMixed() { var source = @" using System; using System.Threading.Tasks; class Test { static async Task<int> F(int x) { await Task.Yield(); return x; } static async Task<int> G() { int x = 0; try { try { for (int i = 0; i < 5; i++) { try { try { x = x / await F(0); } catch (DivideByZeroException) when (i < 3) { await Task.Yield(); continue; } catch (DivideByZeroException) { x = 2 + await F(x); throw; } System.Console.WriteLine(""FAIL""); } finally { x = await F(x) + 3; if (i >= 3) { throw new Exception(""hello""); } } } } finally { x = 11 + await F(x); } } catch (Exception ex) { x = await F(x) + 17; System.Console.WriteLine(ex.Message); } return x; } public static void Main() { Task<int> t2 = G(); t2.Wait(1000 * 60); Console.WriteLine(t2.Result); } }"; var expected = @" hello 42 "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void AsyncInCatchFinallyMixed_InAsyncLambda() { var source = @" using System; using System.Threading.Tasks; class Test { static async Task<int> F(int x) { await Task.Yield(); return x; } static Func<Task<int>> G() { int x = 0; return async () => { try { try { for (int i = 0; i < 5; i++) { try { try { x = x / await F(0); } catch (DivideByZeroException) when (i < 3) { await Task.Yield(); continue; } catch (DivideByZeroException) { x = 2 + await F(x); throw; } System.Console.WriteLine(""FAIL""); } finally { x = await F(x) + 3; if (i >= 3) { throw new Exception(""hello""); } } } } finally { x = 11 + await F(x); } } catch (Exception ex) { x = await F(x) + 17; System.Console.WriteLine(ex.Message); } return x; }; } public static void Main() { Task<int> t2 = G()(); t2.Wait(1000 * 60); Console.WriteLine(t2.Result); } }"; var expected = @" hello 42 "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void DoFinallyBodies() { var source = @" using System.Threading.Tasks; using System; class Driver { public static int finally_count = 0; static async Task F() { try { await Task.Factory.StartNew(() => { }); } finally { Driver.finally_count++; } } static void Main() { var t = F(); t.Wait(); Console.WriteLine(Driver.finally_count); } }"; var expected = @" 1 "; CompileAndVerify(source, expected); } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class CodeGenAsyncEHTests : EmitMetadataTestBase { private static readonly MetadataReference[] s_asyncRefs = new[] { MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929 }; public CodeGenAsyncEHTests() { } private CompilationVerifier CompileAndVerify(string source, string expectedOutput = null, IEnumerable<MetadataReference> references = null, CSharpCompilationOptions options = null) { references = (references != null) ? references.Concat(s_asyncRefs) : s_asyncRefs; return base.CompileAndVerify(source, targetFramework: TargetFramework.Empty, expectedOutput: expectedOutput, references: references, options: options); } [Fact] [WorkItem(624970, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624970")] public void AsyncWithEH() { var source = @" using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; class Test { static int awaitCount = 0; static int finallyCount = 0; static void LogAwait() { Interlocked.Increment(ref awaitCount); } static void LogException() { Interlocked.Increment(ref finallyCount); } public static async void F(AutoResetEvent handle) { try { await Task.Factory.StartNew(LogAwait); try { await Task.Factory.StartNew(LogAwait); try { await Task.Factory.StartNew(LogAwait); try { await Task.Factory.StartNew(LogAwait); throw new Exception(); } catch (Exception) { } finally { LogException(); } await Task.Factory.StartNew(LogAwait); throw new Exception(); } catch (Exception) { } finally { LogException(); } await Task.Factory.StartNew(LogAwait); throw new Exception(); } catch (Exception) { } finally { LogException(); } await Task.Factory.StartNew(LogAwait); } finally { handle.Set(); } } public static void Main2(int i) { try { awaitCount = 0; finallyCount = 0; var handle = new AutoResetEvent(false); F(handle); var completed = handle.WaitOne(1000 * 60); if (completed) { if (awaitCount != 7 || finallyCount != 3) { throw new Exception(""failed at i="" + i); } } else { Console.WriteLine(""Test did not complete in time.""); } } catch (Exception ex) { Console.WriteLine(""unexpected exception thrown:""); Console.WriteLine(ex.ToString()); } } public static void Main() { for (int i = 0; i < 1500; i++) { Main2(i); } } }"; var expected = @""; CompileAndVerify(source, expectedOutput: expected); } [WorkItem(14878, "https://github.com/dotnet/roslyn/issues/14878")] [Fact] public void AsyncWithEHCodeQuality() { var source = @" using System; using System.Threading.Tasks; class Test { static async Task<int> G() { int x = 1; try { try { try { await Task.Yield(); x += 1; await Task.Yield(); x += 1; await Task.Yield(); x += 1; await Task.Yield(); x += 1; await Task.Yield(); x += 1; await Task.Yield(); x += 1; } finally { x += 1; } } finally { x += 1; } } finally { x += 1; } return x; } public static void Main() { Task<int> t2 = G(); t2.Wait(1000 * 60); Console.WriteLine(t2.Result); } }"; var expected = @" 10 "; CompileAndVerify(source, expectedOutput: expected). VerifyIL("Test.<G>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 819 (0x333) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_2, System.Runtime.CompilerServices.YieldAwaitable V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int Test.<G>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: ldc.i4.5 IL_0009: ble.un.s IL_0012 IL_000b: ldarg.0 IL_000c: ldc.i4.1 IL_000d: stfld ""int Test.<G>d__0.<x>5__2"" IL_0012: nop .try { IL_0013: ldloc.0 IL_0014: ldc.i4.5 IL_0015: pop IL_0016: pop IL_0017: nop .try { IL_0018: ldloc.0 IL_0019: ldc.i4.5 IL_001a: pop IL_001b: pop IL_001c: nop .try { IL_001d: ldloc.0 IL_001e: switch ( IL_0075, IL_00e0, IL_014b, IL_01b6, IL_0221, IL_028c) IL_003b: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()"" IL_0040: stloc.3 IL_0041: ldloca.s V_3 IL_0043: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()"" IL_0048: stloc.2 IL_0049: ldloca.s V_2 IL_004b: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get"" IL_0050: brtrue.s IL_0091 IL_0052: ldarg.0 IL_0053: ldc.i4.0 IL_0054: dup IL_0055: stloc.0 IL_0056: stfld ""int Test.<G>d__0.<>1__state"" IL_005b: ldarg.0 IL_005c: ldloc.2 IL_005d: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<G>d__0.<>u__1"" IL_0062: ldarg.0 IL_0063: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<G>d__0.<>t__builder"" IL_0068: ldloca.s V_2 IL_006a: ldarg.0 IL_006b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Test.<G>d__0>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Test.<G>d__0)"" IL_0070: leave IL_0332 IL_0075: ldarg.0 IL_0076: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<G>d__0.<>u__1"" IL_007b: stloc.2 IL_007c: ldarg.0 IL_007d: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<G>d__0.<>u__1"" IL_0082: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"" IL_0088: ldarg.0 IL_0089: ldc.i4.m1 IL_008a: dup IL_008b: stloc.0 IL_008c: stfld ""int Test.<G>d__0.<>1__state"" IL_0091: ldloca.s V_2 IL_0093: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()"" IL_0098: ldarg.0 IL_0099: ldarg.0 IL_009a: ldfld ""int Test.<G>d__0.<x>5__2"" IL_009f: ldc.i4.1 IL_00a0: add IL_00a1: stfld ""int Test.<G>d__0.<x>5__2"" IL_00a6: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()"" IL_00ab: stloc.3 IL_00ac: ldloca.s V_3 IL_00ae: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()"" IL_00b3: stloc.2 IL_00b4: ldloca.s V_2 IL_00b6: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get"" IL_00bb: brtrue.s IL_00fc IL_00bd: ldarg.0 IL_00be: ldc.i4.1 IL_00bf: dup IL_00c0: stloc.0 IL_00c1: stfld ""int Test.<G>d__0.<>1__state"" IL_00c6: ldarg.0 IL_00c7: ldloc.2 IL_00c8: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<G>d__0.<>u__1"" IL_00cd: ldarg.0 IL_00ce: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<G>d__0.<>t__builder"" IL_00d3: ldloca.s V_2 IL_00d5: ldarg.0 IL_00d6: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Test.<G>d__0>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Test.<G>d__0)"" IL_00db: leave IL_0332 IL_00e0: ldarg.0 IL_00e1: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<G>d__0.<>u__1"" IL_00e6: stloc.2 IL_00e7: ldarg.0 IL_00e8: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<G>d__0.<>u__1"" IL_00ed: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"" IL_00f3: ldarg.0 IL_00f4: ldc.i4.m1 IL_00f5: dup IL_00f6: stloc.0 IL_00f7: stfld ""int Test.<G>d__0.<>1__state"" IL_00fc: ldloca.s V_2 IL_00fe: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()"" IL_0103: ldarg.0 IL_0104: ldarg.0 IL_0105: ldfld ""int Test.<G>d__0.<x>5__2"" IL_010a: ldc.i4.1 IL_010b: add IL_010c: stfld ""int Test.<G>d__0.<x>5__2"" IL_0111: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()"" IL_0116: stloc.3 IL_0117: ldloca.s V_3 IL_0119: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()"" IL_011e: stloc.2 IL_011f: ldloca.s V_2 IL_0121: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get"" IL_0126: brtrue.s IL_0167 IL_0128: ldarg.0 IL_0129: ldc.i4.2 IL_012a: dup IL_012b: stloc.0 IL_012c: stfld ""int Test.<G>d__0.<>1__state"" IL_0131: ldarg.0 IL_0132: ldloc.2 IL_0133: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<G>d__0.<>u__1"" IL_0138: ldarg.0 IL_0139: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<G>d__0.<>t__builder"" IL_013e: ldloca.s V_2 IL_0140: ldarg.0 IL_0141: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Test.<G>d__0>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Test.<G>d__0)"" IL_0146: leave IL_0332 IL_014b: ldarg.0 IL_014c: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<G>d__0.<>u__1"" IL_0151: stloc.2 IL_0152: ldarg.0 IL_0153: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<G>d__0.<>u__1"" IL_0158: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"" IL_015e: ldarg.0 IL_015f: ldc.i4.m1 IL_0160: dup IL_0161: stloc.0 IL_0162: stfld ""int Test.<G>d__0.<>1__state"" IL_0167: ldloca.s V_2 IL_0169: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()"" IL_016e: ldarg.0 IL_016f: ldarg.0 IL_0170: ldfld ""int Test.<G>d__0.<x>5__2"" IL_0175: ldc.i4.1 IL_0176: add IL_0177: stfld ""int Test.<G>d__0.<x>5__2"" IL_017c: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()"" IL_0181: stloc.3 IL_0182: ldloca.s V_3 IL_0184: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()"" IL_0189: stloc.2 IL_018a: ldloca.s V_2 IL_018c: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get"" IL_0191: brtrue.s IL_01d2 IL_0193: ldarg.0 IL_0194: ldc.i4.3 IL_0195: dup IL_0196: stloc.0 IL_0197: stfld ""int Test.<G>d__0.<>1__state"" IL_019c: ldarg.0 IL_019d: ldloc.2 IL_019e: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<G>d__0.<>u__1"" IL_01a3: ldarg.0 IL_01a4: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<G>d__0.<>t__builder"" IL_01a9: ldloca.s V_2 IL_01ab: ldarg.0 IL_01ac: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Test.<G>d__0>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Test.<G>d__0)"" IL_01b1: leave IL_0332 IL_01b6: ldarg.0 IL_01b7: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<G>d__0.<>u__1"" IL_01bc: stloc.2 IL_01bd: ldarg.0 IL_01be: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<G>d__0.<>u__1"" IL_01c3: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"" IL_01c9: ldarg.0 IL_01ca: ldc.i4.m1 IL_01cb: dup IL_01cc: stloc.0 IL_01cd: stfld ""int Test.<G>d__0.<>1__state"" IL_01d2: ldloca.s V_2 IL_01d4: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()"" IL_01d9: ldarg.0 IL_01da: ldarg.0 IL_01db: ldfld ""int Test.<G>d__0.<x>5__2"" IL_01e0: ldc.i4.1 IL_01e1: add IL_01e2: stfld ""int Test.<G>d__0.<x>5__2"" IL_01e7: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()"" IL_01ec: stloc.3 IL_01ed: ldloca.s V_3 IL_01ef: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()"" IL_01f4: stloc.2 IL_01f5: ldloca.s V_2 IL_01f7: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get"" IL_01fc: brtrue.s IL_023d IL_01fe: ldarg.0 IL_01ff: ldc.i4.4 IL_0200: dup IL_0201: stloc.0 IL_0202: stfld ""int Test.<G>d__0.<>1__state"" IL_0207: ldarg.0 IL_0208: ldloc.2 IL_0209: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<G>d__0.<>u__1"" IL_020e: ldarg.0 IL_020f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<G>d__0.<>t__builder"" IL_0214: ldloca.s V_2 IL_0216: ldarg.0 IL_0217: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Test.<G>d__0>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Test.<G>d__0)"" IL_021c: leave IL_0332 IL_0221: ldarg.0 IL_0222: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<G>d__0.<>u__1"" IL_0227: stloc.2 IL_0228: ldarg.0 IL_0229: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<G>d__0.<>u__1"" IL_022e: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"" IL_0234: ldarg.0 IL_0235: ldc.i4.m1 IL_0236: dup IL_0237: stloc.0 IL_0238: stfld ""int Test.<G>d__0.<>1__state"" IL_023d: ldloca.s V_2 IL_023f: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()"" IL_0244: ldarg.0 IL_0245: ldarg.0 IL_0246: ldfld ""int Test.<G>d__0.<x>5__2"" IL_024b: ldc.i4.1 IL_024c: add IL_024d: stfld ""int Test.<G>d__0.<x>5__2"" IL_0252: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()"" IL_0257: stloc.3 IL_0258: ldloca.s V_3 IL_025a: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()"" IL_025f: stloc.2 IL_0260: ldloca.s V_2 IL_0262: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get"" IL_0267: brtrue.s IL_02a8 IL_0269: ldarg.0 IL_026a: ldc.i4.5 IL_026b: dup IL_026c: stloc.0 IL_026d: stfld ""int Test.<G>d__0.<>1__state"" IL_0272: ldarg.0 IL_0273: ldloc.2 IL_0274: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<G>d__0.<>u__1"" IL_0279: ldarg.0 IL_027a: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<G>d__0.<>t__builder"" IL_027f: ldloca.s V_2 IL_0281: ldarg.0 IL_0282: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Test.<G>d__0>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Test.<G>d__0)"" IL_0287: leave IL_0332 IL_028c: ldarg.0 IL_028d: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<G>d__0.<>u__1"" IL_0292: stloc.2 IL_0293: ldarg.0 IL_0294: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<G>d__0.<>u__1"" IL_0299: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"" IL_029f: ldarg.0 IL_02a0: ldc.i4.m1 IL_02a1: dup IL_02a2: stloc.0 IL_02a3: stfld ""int Test.<G>d__0.<>1__state"" IL_02a8: ldloca.s V_2 IL_02aa: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()"" IL_02af: ldarg.0 IL_02b0: ldarg.0 IL_02b1: ldfld ""int Test.<G>d__0.<x>5__2"" IL_02b6: ldc.i4.1 IL_02b7: add IL_02b8: stfld ""int Test.<G>d__0.<x>5__2"" IL_02bd: leave.s IL_02d2 } finally { IL_02bf: ldloc.0 IL_02c0: ldc.i4.0 IL_02c1: bge.s IL_02d1 IL_02c3: ldarg.0 IL_02c4: ldarg.0 IL_02c5: ldfld ""int Test.<G>d__0.<x>5__2"" IL_02ca: ldc.i4.1 IL_02cb: add IL_02cc: stfld ""int Test.<G>d__0.<x>5__2"" IL_02d1: endfinally } IL_02d2: leave.s IL_02e7 } finally { IL_02d4: ldloc.0 IL_02d5: ldc.i4.0 IL_02d6: bge.s IL_02e6 IL_02d8: ldarg.0 IL_02d9: ldarg.0 IL_02da: ldfld ""int Test.<G>d__0.<x>5__2"" IL_02df: ldc.i4.1 IL_02e0: add IL_02e1: stfld ""int Test.<G>d__0.<x>5__2"" IL_02e6: endfinally } IL_02e7: leave.s IL_02fc } finally { IL_02e9: ldloc.0 IL_02ea: ldc.i4.0 IL_02eb: bge.s IL_02fb IL_02ed: ldarg.0 IL_02ee: ldarg.0 IL_02ef: ldfld ""int Test.<G>d__0.<x>5__2"" IL_02f4: ldc.i4.1 IL_02f5: add IL_02f6: stfld ""int Test.<G>d__0.<x>5__2"" IL_02fb: endfinally } IL_02fc: ldarg.0 IL_02fd: ldfld ""int Test.<G>d__0.<x>5__2"" IL_0302: stloc.1 IL_0303: leave.s IL_031e } catch System.Exception { IL_0305: stloc.s V_4 IL_0307: ldarg.0 IL_0308: ldc.i4.s -2 IL_030a: stfld ""int Test.<G>d__0.<>1__state"" IL_030f: ldarg.0 IL_0310: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<G>d__0.<>t__builder"" IL_0315: ldloc.s V_4 IL_0317: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_031c: leave.s IL_0332 } IL_031e: ldarg.0 IL_031f: ldc.i4.s -2 IL_0321: stfld ""int Test.<G>d__0.<>1__state"" IL_0326: ldarg.0 IL_0327: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<G>d__0.<>t__builder"" IL_032c: ldloc.1 IL_032d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_0332: ret } "); } [Fact, WorkItem(855080, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/855080")] public void GenericCatchVariableInAsyncMethod() { var source = @" using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Console.WriteLine(Bar().Result); } static async Task<int> Bar() { NotImplementedException ex = await Goo<NotImplementedException>(); return 3; } public static async Task<T> Goo<T>() where T : Exception { Task<int> task = null; if (task != null) await task; T result = null; try { } catch (T ex) { result = ex; } return result; } } } "; CompileAndVerify(source, expectedOutput: "3"); } [Fact] public void AsyncWithException1() { var source = @" using System; using System.Threading.Tasks; class Test { static async Task<int> F() { throw new Exception(); } static async Task<int> G() { try { return await F(); } catch(Exception) { return -1; } } public static void Main() { Task<int> t2 = G(); t2.Wait(1000 * 60); Console.WriteLine(t2.Result); } }"; var expected = @" -1 "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void AsyncWithException2() { var source = @" using System; using System.Threading.Tasks; class Test { static async Task<int> F() { throw new Exception(); } static async Task<int> H() { return await F(); } public static void Main() { Task<int> t1 = H(); try { t1.Wait(1000 * 60); } catch (AggregateException) { Console.WriteLine(""exception""); } } }"; var expected = @" exception "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void AsyncInFinally001() { var source = @" using System; using System.Threading.Tasks; class Test { static async Task<int> F() { return 2; } static async Task<int> G() { int x = 42; try { } finally { x = await F(); } return x; } public static void Main() { Task<int> t2 = G(); t2.Wait(1000 * 60); Console.WriteLine(t2.Result); } }"; var expected = @" 2 "; CompileAndVerify(source, expectedOutput: expected). VerifyIL("Test.<G>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 210 (0xd2) .maxstack 3 .locals init (int V_0, int V_1, object V_2, System.Runtime.CompilerServices.TaskAwaiter<int> V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int Test.<G>d__1.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0058 IL_000a: ldarg.0 IL_000b: ldnull IL_000c: stfld ""object Test.<G>d__1.<>7__wrap1"" IL_0011: ldarg.0 IL_0012: ldc.i4.0 IL_0013: stfld ""int Test.<G>d__1.<>7__wrap2"" .try { IL_0018: leave.s IL_0024 } catch object { IL_001a: stloc.2 IL_001b: ldarg.0 IL_001c: ldloc.2 IL_001d: stfld ""object Test.<G>d__1.<>7__wrap1"" IL_0022: leave.s IL_0024 } IL_0024: call ""System.Threading.Tasks.Task<int> Test.F()"" IL_0029: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_002e: stloc.3 IL_002f: ldloca.s V_3 IL_0031: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_0036: brtrue.s IL_0074 IL_0038: ldarg.0 IL_0039: ldc.i4.0 IL_003a: dup IL_003b: stloc.0 IL_003c: stfld ""int Test.<G>d__1.<>1__state"" IL_0041: ldarg.0 IL_0042: ldloc.3 IL_0043: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<G>d__1.<>u__1"" IL_0048: ldarg.0 IL_0049: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<G>d__1.<>t__builder"" IL_004e: ldloca.s V_3 IL_0050: ldarg.0 IL_0051: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Test.<G>d__1>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Test.<G>d__1)"" IL_0056: leave.s IL_00d1 IL_0058: ldarg.0 IL_0059: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<G>d__1.<>u__1"" IL_005e: stloc.3 IL_005f: ldarg.0 IL_0060: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<G>d__1.<>u__1"" IL_0065: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_006b: ldarg.0 IL_006c: ldc.i4.m1 IL_006d: dup IL_006e: stloc.0 IL_006f: stfld ""int Test.<G>d__1.<>1__state"" IL_0074: ldloca.s V_3 IL_0076: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_007b: ldarg.0 IL_007c: ldfld ""object Test.<G>d__1.<>7__wrap1"" IL_0081: stloc.2 IL_0082: ldloc.2 IL_0083: brfalse.s IL_009a IL_0085: ldloc.2 IL_0086: isinst ""System.Exception"" IL_008b: dup IL_008c: brtrue.s IL_0090 IL_008e: ldloc.2 IL_008f: throw IL_0090: call ""System.Runtime.ExceptionServices.ExceptionDispatchInfo System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(System.Exception)"" IL_0095: callvirt ""void System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()"" IL_009a: ldarg.0 IL_009b: ldnull IL_009c: stfld ""object Test.<G>d__1.<>7__wrap1"" IL_00a1: stloc.1 IL_00a2: leave.s IL_00bd } catch System.Exception { IL_00a4: stloc.s V_4 IL_00a6: ldarg.0 IL_00a7: ldc.i4.s -2 IL_00a9: stfld ""int Test.<G>d__1.<>1__state"" IL_00ae: ldarg.0 IL_00af: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<G>d__1.<>t__builder"" IL_00b4: ldloc.s V_4 IL_00b6: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_00bb: leave.s IL_00d1 } IL_00bd: ldarg.0 IL_00be: ldc.i4.s -2 IL_00c0: stfld ""int Test.<G>d__1.<>1__state"" IL_00c5: ldarg.0 IL_00c6: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<G>d__1.<>t__builder"" IL_00cb: ldloc.1 IL_00cc: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_00d1: ret } "); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] public void AsyncInFinally002() { var source = @" using System; using System.Threading.Tasks; class Test { static async Task<int> F() { System.Console.Write(""F""); return 2; } static async Task G() { int x = 0; try { throw new Exception(""hello""); } finally { x += await F(); } } public static void Main() { System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture; System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture; try { Task t2 = G(); try { t2.Wait(1000 * 60); } catch (Exception ex) { Console.WriteLine(ex.Message); } } finally { System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture; } } }"; var expected = @"FOne or more errors occurred. "; CompileAndVerify(source, expectedOutput: expected); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void AsyncInFinally003() { var source = @" using System; using System.Threading.Tasks; class Test { static async Task<int> F() { return 2; } static async Task<int> G() { int x = 0; try { x = await F(); return x; } finally { x += await F(); } } public static void Main() { Task<int> t2 = G(); t2.Wait(1000 * 60); Console.WriteLine(t2.Result); } }"; var expected = @" 2 "; var v = CompileAndVerify(source, s_asyncRefs, targetFramework: TargetFramework.Empty, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), expectedOutput: expected, symbolValidator: module => { Assert.Equal(new[] { "<>1__state", "<>t__builder", "<x>5__1", "<>s__2", // pending exception "<>s__3", // pending branch "<>s__4", // return value "<>s__5", // spill "<>s__6", // spill "<>s__7", // spill "<>u__1", // awaiter }, module.GetFieldNames("Test.<G>d__1")); }); v.VerifyPdb("Test.G", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""Test"" methodName=""Main"" /> <methods> <method containingType=""Test"" name=""G""> <customDebugInfo> <forwardIterator name=""&lt;G&gt;d__1"" /> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> <slot kind=""22"" offset=""33"" /> <slot kind=""23"" offset=""33"" /> <slot kind=""20"" offset=""33"" /> <slot kind=""28"" offset=""65"" /> <slot kind=""28"" offset=""156"" /> <slot kind=""28"" offset=""156"" ordinal=""1"" /> </encLocalSlotMap> </customDebugInfo> </method> </methods> </symbols> "); v.VerifyIL("Test.<G>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @"{ // Code size 461 (0x1cd) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, Test.<G>d__1 V_3, object V_4, System.Runtime.CompilerServices.TaskAwaiter<int> V_5, System.Exception V_6, int V_7) ~IL_0000: ldarg.0 IL_0001: ldfld ""int Test.<G>d__1.<>1__state"" IL_0006: stloc.0 .try { ~IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0019 IL_0012: br.s IL_002f IL_0014: br IL_0115 -IL_0019: nop -IL_001a: ldarg.0 IL_001b: ldc.i4.0 IL_001c: stfld ""int Test.<G>d__1.<x>5__1"" ~IL_0021: ldarg.0 IL_0022: ldnull IL_0023: stfld ""object Test.<G>d__1.<>s__2"" IL_0028: ldarg.0 IL_0029: ldc.i4.0 IL_002a: stfld ""int Test.<G>d__1.<>s__3"" ~IL_002f: nop .try { ~IL_0030: ldloc.0 IL_0031: brfalse.s IL_0035 IL_0033: br.s IL_0037 IL_0035: br.s IL_0073 -IL_0037: nop -IL_0038: call ""System.Threading.Tasks.Task<int> Test.F()"" IL_003d: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0042: stloc.2 ~IL_0043: ldloca.s V_2 IL_0045: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_004a: brtrue.s IL_008f IL_004c: ldarg.0 IL_004d: ldc.i4.0 IL_004e: dup IL_004f: stloc.0 IL_0050: stfld ""int Test.<G>d__1.<>1__state"" <IL_0055: ldarg.0 IL_0056: ldloc.2 IL_0057: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<G>d__1.<>u__1"" IL_005c: ldarg.0 IL_005d: stloc.3 IL_005e: ldarg.0 IL_005f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<G>d__1.<>t__builder"" IL_0064: ldloca.s V_2 IL_0066: ldloca.s V_3 IL_0068: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Test.<G>d__1>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Test.<G>d__1)"" IL_006d: nop IL_006e: leave IL_01cc >IL_0073: ldarg.0 IL_0074: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<G>d__1.<>u__1"" IL_0079: stloc.2 IL_007a: ldarg.0 IL_007b: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<G>d__1.<>u__1"" IL_0080: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0086: ldarg.0 IL_0087: ldc.i4.m1 IL_0088: dup IL_0089: stloc.0 IL_008a: stfld ""int Test.<G>d__1.<>1__state"" IL_008f: ldarg.0 IL_0090: ldloca.s V_2 IL_0092: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0097: stfld ""int Test.<G>d__1.<>s__5"" IL_009c: ldarg.0 IL_009d: ldarg.0 IL_009e: ldfld ""int Test.<G>d__1.<>s__5"" IL_00a3: stfld ""int Test.<G>d__1.<x>5__1"" -IL_00a8: ldarg.0 IL_00a9: ldarg.0 IL_00aa: ldfld ""int Test.<G>d__1.<x>5__1"" IL_00af: stfld ""int Test.<G>d__1.<>s__4"" IL_00b4: br.s IL_00b6 IL_00b6: ldarg.0 IL_00b7: ldc.i4.1 IL_00b8: stfld ""int Test.<G>d__1.<>s__3"" IL_00bd: leave.s IL_00cb } catch object { ~IL_00bf: stloc.s V_4 IL_00c1: ldarg.0 IL_00c2: ldloc.s V_4 IL_00c4: stfld ""object Test.<G>d__1.<>s__2"" IL_00c9: leave.s IL_00cb } -IL_00cb: nop -IL_00cc: ldarg.0 IL_00cd: ldarg.0 IL_00ce: ldfld ""int Test.<G>d__1.<x>5__1"" IL_00d3: stfld ""int Test.<G>d__1.<>s__6"" IL_00d8: call ""System.Threading.Tasks.Task<int> Test.F()"" IL_00dd: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_00e2: stloc.s V_5 ~IL_00e4: ldloca.s V_5 IL_00e6: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_00eb: brtrue.s IL_0132 IL_00ed: ldarg.0 IL_00ee: ldc.i4.1 IL_00ef: dup IL_00f0: stloc.0 IL_00f1: stfld ""int Test.<G>d__1.<>1__state"" <IL_00f6: ldarg.0 IL_00f7: ldloc.s V_5 IL_00f9: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<G>d__1.<>u__1"" IL_00fe: ldarg.0 IL_00ff: stloc.3 IL_0100: ldarg.0 IL_0101: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<G>d__1.<>t__builder"" IL_0106: ldloca.s V_5 IL_0108: ldloca.s V_3 IL_010a: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Test.<G>d__1>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Test.<G>d__1)"" IL_010f: nop IL_0110: leave IL_01cc >IL_0115: ldarg.0 IL_0116: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<G>d__1.<>u__1"" IL_011b: stloc.s V_5 IL_011d: ldarg.0 IL_011e: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<G>d__1.<>u__1"" IL_0123: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0129: ldarg.0 IL_012a: ldc.i4.m1 IL_012b: dup IL_012c: stloc.0 IL_012d: stfld ""int Test.<G>d__1.<>1__state"" IL_0132: ldarg.0 IL_0133: ldloca.s V_5 IL_0135: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_013a: stfld ""int Test.<G>d__1.<>s__7"" IL_013f: ldarg.0 IL_0140: ldarg.0 IL_0141: ldfld ""int Test.<G>d__1.<>s__6"" IL_0146: ldarg.0 IL_0147: ldfld ""int Test.<G>d__1.<>s__7"" IL_014c: add IL_014d: stfld ""int Test.<G>d__1.<x>5__1"" -IL_0152: nop ~IL_0153: ldarg.0 IL_0154: ldfld ""object Test.<G>d__1.<>s__2"" IL_0159: stloc.s V_4 IL_015b: ldloc.s V_4 IL_015d: brfalse.s IL_017c IL_015f: ldloc.s V_4 IL_0161: isinst ""System.Exception"" IL_0166: stloc.s V_6 IL_0168: ldloc.s V_6 IL_016a: brtrue.s IL_016f IL_016c: ldloc.s V_4 IL_016e: throw IL_016f: ldloc.s V_6 IL_0171: call ""System.Runtime.ExceptionServices.ExceptionDispatchInfo System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(System.Exception)"" IL_0176: callvirt ""void System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()"" IL_017b: nop IL_017c: ldarg.0 IL_017d: ldfld ""int Test.<G>d__1.<>s__3"" IL_0182: stloc.s V_7 IL_0184: ldloc.s V_7 IL_0186: ldc.i4.1 IL_0187: beq.s IL_018b IL_0189: br.s IL_0194 IL_018b: ldarg.0 IL_018c: ldfld ""int Test.<G>d__1.<>s__4"" IL_0191: stloc.1 IL_0192: leave.s IL_01b7 IL_0194: ldarg.0 IL_0195: ldnull IL_0196: stfld ""object Test.<G>d__1.<>s__2"" IL_019b: leave.s IL_01b7 } catch System.Exception { ~IL_019d: stloc.s V_6 IL_019f: ldarg.0 IL_01a0: ldc.i4.s -2 IL_01a2: stfld ""int Test.<G>d__1.<>1__state"" IL_01a7: ldarg.0 IL_01a8: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<G>d__1.<>t__builder"" IL_01ad: ldloc.s V_6 IL_01af: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_01b4: nop IL_01b5: leave.s IL_01cc } -IL_01b7: ldarg.0 IL_01b8: ldc.i4.s -2 IL_01ba: stfld ""int Test.<G>d__1.<>1__state"" ~IL_01bf: ldarg.0 IL_01c0: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<G>d__1.<>t__builder"" IL_01c5: ldloc.1 IL_01c6: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_01cb: nop IL_01cc: ret }", sequencePoints: "Test+<G>d__1.MoveNext"); } [Fact] public void AsyncInFinally004() { var source = @" using System; using System.Threading.Tasks; class Test { static async Task<int> F() { return 2; } static async Task<int> G() { int x = 0; try { try { throw new Exception(); } finally { x += await F(); } } catch { return x; } } public static void Main() { Task<int> t2 = G(); t2.Wait(1000 * 60); Console.WriteLine(t2.Result); } }"; var expected = @" 2 "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void AsyncInFinallyNested001() { var source = @" using System; using System.Threading.Tasks; class Test { static async Task<int> F(int a) { await Task.Yield(); return a; } static async Task<int> G() { int x = 0; try { try { x = await F(1); goto L1; System.Console.WriteLine(""FAIL""); } finally { x += await F(2); } } finally { try { x += await F(4); } finally { x += await F(8); } } System.Console.WriteLine(""FAIL""); L1: return x; } public static void Main() { Task<int> t2 = G(); t2.Wait(1000 * 60); Console.WriteLine(t2.Result); } }"; var expected = @"15"; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void AsyncInFinallyNested002() { var source = @" using System; using System.Threading.Tasks; class Test { static async Task<int> F(int a) { await Task.Yield(); return a; } static async Task<int> G() { int x = 0; try { try { try { x = await F(1); throw new Exception(""hello""); System.Console.WriteLine(""FAIL""); } finally { x += await F(2); } System.Console.WriteLine(""FAIL""); } finally { try { x += await F(4); } finally { x += await F(8); } } System.Console.WriteLine(""FAIL""); } catch(Exception ex) { System.Console.WriteLine(ex.Message); } return x; } public static void Main() { Task<int> t2 = G(); t2.Wait(1000 * 60); Console.WriteLine(t2.Result); } }"; var expected = @"hello 15"; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void AsyncInFinallyNested003() { var source = @" using System; using System.Threading.Tasks; class Test { static async Task<int> F(int a) { await Task.Yield(); return a; } static async Task<int> G() { int x = 0; try { try { try { x = await F(1); throw new Exception(""hello""); System.Console.WriteLine(""FAIL""); } finally { x += await F(2); } System.Console.WriteLine(""FAIL""); } finally { try { x += await F(4); } finally { x += await F(8); throw new Exception(""bye""); } } System.Console.WriteLine(""FAIL""); } catch(Exception ex) { System.Console.WriteLine(ex.Message); } return x; } public static void Main() { Task<int> t2 = G(); t2.Wait(1000 * 60); Console.WriteLine(t2.Result); } }"; var expected = @"bye 15"; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void AsyncInCatch001() { var source = @" using System; using System.Threading.Tasks; class Test { static async Task<int> F() { return 2; } static async Task<int> G() { int x = 0; try { x = x / x; } catch { x = await F(); } return x; } public static void Main() { Task<int> t2 = G(); t2.Wait(1000 * 60); Console.WriteLine(t2.Result); } }"; var expected = @" 2 "; CompileAndVerify(source, expectedOutput: expected). VerifyIL("Test.<G>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 170 (0xaa) .maxstack 3 .locals init (int V_0, int V_1, int V_2, //x int V_3, System.Runtime.CompilerServices.TaskAwaiter<int> V_4, System.Exception V_5) IL_0000: ldarg.0 IL_0001: ldfld ""int Test.<G>d__1.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0053 IL_000a: ldc.i4.0 IL_000b: stloc.2 IL_000c: ldc.i4.0 IL_000d: stloc.3 .try { IL_000e: ldloc.2 IL_000f: ldloc.2 IL_0010: div IL_0011: stloc.2 IL_0012: leave.s IL_0019 } catch object { IL_0014: pop IL_0015: ldc.i4.1 IL_0016: stloc.3 IL_0017: leave.s IL_0019 } IL_0019: ldloc.3 IL_001a: ldc.i4.1 IL_001b: bne.un.s IL_0078 IL_001d: call ""System.Threading.Tasks.Task<int> Test.F()"" IL_0022: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0027: stloc.s V_4 IL_0029: ldloca.s V_4 IL_002b: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_0030: brtrue.s IL_0070 IL_0032: ldarg.0 IL_0033: ldc.i4.0 IL_0034: dup IL_0035: stloc.0 IL_0036: stfld ""int Test.<G>d__1.<>1__state"" IL_003b: ldarg.0 IL_003c: ldloc.s V_4 IL_003e: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<G>d__1.<>u__1"" IL_0043: ldarg.0 IL_0044: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<G>d__1.<>t__builder"" IL_0049: ldloca.s V_4 IL_004b: ldarg.0 IL_004c: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Test.<G>d__1>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Test.<G>d__1)"" IL_0051: leave.s IL_00a9 IL_0053: ldarg.0 IL_0054: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<G>d__1.<>u__1"" IL_0059: stloc.s V_4 IL_005b: ldarg.0 IL_005c: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<G>d__1.<>u__1"" IL_0061: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0067: ldarg.0 IL_0068: ldc.i4.m1 IL_0069: dup IL_006a: stloc.0 IL_006b: stfld ""int Test.<G>d__1.<>1__state"" IL_0070: ldloca.s V_4 IL_0072: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0077: stloc.2 IL_0078: ldloc.2 IL_0079: stloc.1 IL_007a: leave.s IL_0095 } catch System.Exception { IL_007c: stloc.s V_5 IL_007e: ldarg.0 IL_007f: ldc.i4.s -2 IL_0081: stfld ""int Test.<G>d__1.<>1__state"" IL_0086: ldarg.0 IL_0087: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<G>d__1.<>t__builder"" IL_008c: ldloc.s V_5 IL_008e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_0093: leave.s IL_00a9 } IL_0095: ldarg.0 IL_0096: ldc.i4.s -2 IL_0098: stfld ""int Test.<G>d__1.<>1__state"" IL_009d: ldarg.0 IL_009e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<G>d__1.<>t__builder"" IL_00a3: ldloc.1 IL_00a4: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_00a9: ret } "); } [Fact] public void AsyncInCatchRethrow() { var source = @" using System; using System.Threading.Tasks; class Test { static async Task<int> F() { await Task.Yield(); return 2; } static async Task<int> G() { int x = 0; try { try { x = x / x; } catch { x = await F(); throw; } } catch(DivideByZeroException ex) { x = await F(); System.Console.WriteLine(ex.Message); } return x; } public static void Main() { System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture; System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture; try { Task<int> t2 = G(); t2.Wait(1000 * 60); Console.WriteLine(t2.Result); } finally { System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture; } } }"; var expected = @" Attempted to divide by zero. 2 "; CompileAndVerify(source, expectedOutput: expected); } [WorkItem(74, "https://github.com/dotnet/roslyn/issues/1334")] [Fact] public void AsyncInCatchRethrow01() { var source = @" using System; using System.Threading.Tasks; class Test { static async Task<int> F() { await Task.Yield(); return 2; } static async Task<int> G() { int x = 0; try { try { x = x / x; } catch (ArgumentNullException) { x = await F(); } catch { Console.WriteLine(""rethrowing""); throw; } } catch(DivideByZeroException ex) { x += await F(); System.Console.WriteLine(ex.Message); } return x; } public static void Main() { System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture; System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture; try { Task<int> t2 = G(); t2.Wait(1000 * 60); Console.WriteLine(t2.Result); } finally { System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture; } } }"; var expected = @"rethrowing Attempted to divide by zero. 2 "; CompileAndVerify(source, expectedOutput: expected); } [WorkItem(74, "https://github.com/dotnet/roslyn/issues/1334")] [Fact] public void AsyncInCatchRethrow02() { var source = @" using System; using System.Threading.Tasks; class Test { static async Task<int> F() { await Task.Yield(); return 2; } static async Task<int> G() { int x = 0; try { try { x = x / x; } catch (ArgumentNullException) { Console.WriteLine(""should not get here""); } catch (Exception ex) when (ex == null) { Console.WriteLine(""should not get here""); } catch { x = await F(); Console.WriteLine(""rethrowing""); throw; } } catch(DivideByZeroException ex) { x += await F(); System.Console.WriteLine(ex.Message); } return x; } public static void Main() { System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture; System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture; try { Task<int> t2 = G(); t2.Wait(1000 * 60); Console.WriteLine(t2.Result); } finally { System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture; } } }"; var expected = @"rethrowing Attempted to divide by zero. 4 "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void AsyncInCatchFilter() { var source = @" using System; using System.Threading.Tasks; class Test { static async Task<int> F() { await Task.Yield(); return 2; } static async Task<int> G() { int x = 0; try { try { x = x / x; } catch when(x != 0) { x = await F(); throw; } } catch(Exception ex) when(x == 0 && ((ex = new Exception(""hello"")) != null)) { x = await F(); System.Console.WriteLine(ex.Message); } return x; } public static void Main() { Task<int> t2 = G(); t2.Wait(1000 * 60); Console.WriteLine(t2.Result); } }"; var expected = @" hello 2 "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void AsyncInCatchFilterLifted() { var source = @" using System; using System.Threading.Tasks; class Test { static async Task<int> F() { await Task.Yield(); return 2; } static bool T(Func<bool> f, ref Exception ex) { var result = f(); ex = new Exception(result.ToString()); return result; } static async Task<int> G() { int x = 0; try { x = x / x; } catch(Exception ex) when(T(()=>ex.Message == null, ref ex)) { x = await F(); System.Console.WriteLine(ex.Message); } catch(Exception ex) when(T(()=>ex.Message != null, ref ex)) { x = await F(); System.Console.WriteLine(ex.Message); } return x; } public static void Main() { Task<int> t2 = G(); t2.Wait(1000 * 60); Console.WriteLine(t2.Result); } }"; var expected = @"True 2 "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void AsyncInCatchFinallyMixed() { var source = @" using System; using System.Threading.Tasks; class Test { static async Task<int> F(int x) { await Task.Yield(); return x; } static async Task<int> G() { int x = 0; try { try { for (int i = 0; i < 5; i++) { try { try { x = x / await F(0); } catch (DivideByZeroException) when (i < 3) { await Task.Yield(); continue; } catch (DivideByZeroException) { x = 2 + await F(x); throw; } System.Console.WriteLine(""FAIL""); } finally { x = await F(x) + 3; if (i >= 3) { throw new Exception(""hello""); } } } } finally { x = 11 + await F(x); } } catch (Exception ex) { x = await F(x) + 17; System.Console.WriteLine(ex.Message); } return x; } public static void Main() { Task<int> t2 = G(); t2.Wait(1000 * 60); Console.WriteLine(t2.Result); } }"; var expected = @" hello 42 "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void AsyncInCatchFinallyMixed_InAsyncLambda() { var source = @" using System; using System.Threading.Tasks; class Test { static async Task<int> F(int x) { await Task.Yield(); return x; } static Func<Task<int>> G() { int x = 0; return async () => { try { try { for (int i = 0; i < 5; i++) { try { try { x = x / await F(0); } catch (DivideByZeroException) when (i < 3) { await Task.Yield(); continue; } catch (DivideByZeroException) { x = 2 + await F(x); throw; } System.Console.WriteLine(""FAIL""); } finally { x = await F(x) + 3; if (i >= 3) { throw new Exception(""hello""); } } } } finally { x = 11 + await F(x); } } catch (Exception ex) { x = await F(x) + 17; System.Console.WriteLine(ex.Message); } return x; }; } public static void Main() { Task<int> t2 = G()(); t2.Wait(1000 * 60); Console.WriteLine(t2.Result); } }"; var expected = @" hello 42 "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void DoFinallyBodies() { var source = @" using System.Threading.Tasks; using System; class Driver { public static int finally_count = 0; static async Task F() { try { await Task.Factory.StartNew(() => { }); } finally { Driver.finally_count++; } } static void Main() { var t = F(); t.Wait(); Console.WriteLine(Driver.finally_count); } }"; var expected = @" 1 "; CompileAndVerify(source, expected); } } }
-1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/Completion/CompletionProviders/TupleNameCompletionProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportCompletionProvider(nameof(TupleNameCompletionProvider), LanguageNames.CSharp)] [ExtensionOrder(After = nameof(XmlDocCommentCompletionProvider))] [Shared] internal class TupleNameCompletionProvider : LSPCompletionProvider { private const string ColonString = ":"; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TupleNameCompletionProvider() { } public override async Task ProvideCompletionsAsync(CompletionContext completionContext) { try { var document = completionContext.Document; var position = completionContext.Position; var cancellationToken = completionContext.CancellationToken; var semanticModel = await document.ReuseExistingSpeculativeModelAsync(position, cancellationToken).ConfigureAwait(false); var workspace = document.Project.Solution.Workspace; var context = CSharpSyntaxContext.CreateContext(workspace, semanticModel, position, cancellationToken); var index = GetElementIndex(context); if (index == null) { return; } var typeInferrer = document.GetLanguageService<ITypeInferenceService>(); var inferredTypes = typeInferrer.InferTypes(semanticModel, context.TargetToken.Parent.SpanStart, cancellationToken) .Where(t => t.IsTupleType) .Cast<INamedTypeSymbol>() .ToImmutableArray(); AddItems(inferredTypes, index.Value, completionContext, context.TargetToken.Parent.SpanStart); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e)) { // nop } } private static int? GetElementIndex(CSharpSyntaxContext context) { var token = context.TargetToken; if (token.IsKind(SyntaxKind.OpenParenToken)) { if (token.Parent.IsKind(SyntaxKind.ParenthesizedExpression, SyntaxKind.TupleExpression, SyntaxKind.CastExpression)) { return 0; } } if (token.IsKind(SyntaxKind.CommaToken) && token.Parent.IsKind(SyntaxKind.TupleExpression)) { var tupleExpr = (TupleExpressionSyntax)context.TargetToken.Parent as TupleExpressionSyntax; return (tupleExpr.Arguments.GetWithSeparators().IndexOf(context.TargetToken) + 1) / 2; } return null; } private static void AddItems(ImmutableArray<INamedTypeSymbol> inferredTypes, int index, CompletionContext context, int spanStart) { foreach (var type in inferredTypes) { if (index >= type.TupleElements.Length) { return; } // Note: the filter text does not include the ':'. We want to ensure that if // the user types the name exactly (up to the colon) that it is selected as an // exact match. var field = type.TupleElements[index]; context.AddItem(SymbolCompletionItem.CreateWithSymbolId( displayText: field.Name, displayTextSuffix: ColonString, symbols: ImmutableArray.Create(field), rules: CompletionItemRules.Default, contextPosition: spanStart, filterText: field.Name)); } } protected override Task<TextChange?> GetTextChangeAsync(CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) { return Task.FromResult<TextChange?>(new TextChange( selectedItem.Span, selectedItem.DisplayText)); } public override ImmutableHashSet<char> TriggerCharacters => ImmutableHashSet<char>.Empty; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportCompletionProvider(nameof(TupleNameCompletionProvider), LanguageNames.CSharp)] [ExtensionOrder(After = nameof(XmlDocCommentCompletionProvider))] [Shared] internal class TupleNameCompletionProvider : LSPCompletionProvider { private const string ColonString = ":"; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TupleNameCompletionProvider() { } public override async Task ProvideCompletionsAsync(CompletionContext completionContext) { try { var document = completionContext.Document; var position = completionContext.Position; var cancellationToken = completionContext.CancellationToken; var semanticModel = await document.ReuseExistingSpeculativeModelAsync(position, cancellationToken).ConfigureAwait(false); var workspace = document.Project.Solution.Workspace; var context = CSharpSyntaxContext.CreateContext(workspace, semanticModel, position, cancellationToken); var index = GetElementIndex(context); if (index == null) { return; } var typeInferrer = document.GetLanguageService<ITypeInferenceService>(); var inferredTypes = typeInferrer.InferTypes(semanticModel, context.TargetToken.Parent.SpanStart, cancellationToken) .Where(t => t.IsTupleType) .Cast<INamedTypeSymbol>() .ToImmutableArray(); AddItems(inferredTypes, index.Value, completionContext, context.TargetToken.Parent.SpanStart); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e)) { // nop } } private static int? GetElementIndex(CSharpSyntaxContext context) { var token = context.TargetToken; if (token.IsKind(SyntaxKind.OpenParenToken)) { if (token.Parent.IsKind(SyntaxKind.ParenthesizedExpression, SyntaxKind.TupleExpression, SyntaxKind.CastExpression)) { return 0; } } if (token.IsKind(SyntaxKind.CommaToken) && token.Parent.IsKind(SyntaxKind.TupleExpression)) { var tupleExpr = (TupleExpressionSyntax)context.TargetToken.Parent as TupleExpressionSyntax; return (tupleExpr.Arguments.GetWithSeparators().IndexOf(context.TargetToken) + 1) / 2; } return null; } private static void AddItems(ImmutableArray<INamedTypeSymbol> inferredTypes, int index, CompletionContext context, int spanStart) { foreach (var type in inferredTypes) { if (index >= type.TupleElements.Length) { return; } // Note: the filter text does not include the ':'. We want to ensure that if // the user types the name exactly (up to the colon) that it is selected as an // exact match. var field = type.TupleElements[index]; context.AddItem(SymbolCompletionItem.CreateWithSymbolId( displayText: field.Name, displayTextSuffix: ColonString, symbols: ImmutableArray.Create(field), rules: CompletionItemRules.Default, contextPosition: spanStart, filterText: field.Name)); } } protected override Task<TextChange?> GetTextChangeAsync(CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) { return Task.FromResult<TextChange?>(new TextChange( selectedItem.Span, selectedItem.DisplayText)); } public override ImmutableHashSet<char> TriggerCharacters => ImmutableHashSet<char>.Empty; } }
-1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/UseConditionalExpression/ForReturn/AbstractUseConditionalExpressionForReturnDiagnosticAnalyzer.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.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis.UseConditionalExpression { internal abstract class AbstractUseConditionalExpressionForReturnDiagnosticAnalyzer< TIfStatementSyntax> : AbstractUseConditionalExpressionDiagnosticAnalyzer<TIfStatementSyntax> where TIfStatementSyntax : SyntaxNode { protected AbstractUseConditionalExpressionForReturnDiagnosticAnalyzer( LocalizableResourceString message) : base(IDEDiagnosticIds.UseConditionalExpressionForReturnDiagnosticId, EnforceOnBuildValues.UseConditionalExpressionForReturn, message, CodeStyleOptions2.PreferConditionalExpressionOverReturn) { } protected override bool TryMatchPattern(IConditionalOperation ifOperation, ISymbol containingSymbol) => UseConditionalExpressionForReturnHelpers.TryMatchPattern( GetSyntaxFacts(), ifOperation, containingSymbol, out _, out _, out _, out _); } }
// Licensed to the .NET Foundation under one or more 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.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis.UseConditionalExpression { internal abstract class AbstractUseConditionalExpressionForReturnDiagnosticAnalyzer< TIfStatementSyntax> : AbstractUseConditionalExpressionDiagnosticAnalyzer<TIfStatementSyntax> where TIfStatementSyntax : SyntaxNode { protected AbstractUseConditionalExpressionForReturnDiagnosticAnalyzer( LocalizableResourceString message) : base(IDEDiagnosticIds.UseConditionalExpressionForReturnDiagnosticId, EnforceOnBuildValues.UseConditionalExpressionForReturn, message, CodeStyleOptions2.PreferConditionalExpressionOverReturn) { } protected override bool TryMatchPattern(IConditionalOperation ifOperation, ISymbol containingSymbol) => UseConditionalExpressionForReturnHelpers.TryMatchPattern( GetSyntaxFacts(), ifOperation, containingSymbol, out _, out _, out _, out _); } }
-1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/Symbols/CompilationCreationTests.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.IO; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class CompilationCreationTests : CSharpTestBase { #region Helpers private static SyntaxTree CreateSyntaxTree(string className) { var text = string.Format("public partial class {0} {{ }}", className); var path = string.Format("{0}.cs", className); return SyntaxFactory.ParseSyntaxTree(text, path: path); } private static void CheckCompilationSyntaxTrees(CSharpCompilation compilation, params SyntaxTree[] expectedSyntaxTrees) { ImmutableArray<SyntaxTree> actualSyntaxTrees = compilation.SyntaxTrees; int numTrees = expectedSyntaxTrees.Length; Assert.Equal(numTrees, actualSyntaxTrees.Length); for (int i = 0; i < numTrees; i++) { Assert.Equal(expectedSyntaxTrees[i], actualSyntaxTrees[i]); } for (int i = 0; i < numTrees; i++) { for (int j = 0; j < numTrees; j++) { Assert.Equal(Math.Sign(compilation.CompareSyntaxTreeOrdering(expectedSyntaxTrees[i], expectedSyntaxTrees[j])), Math.Sign(i.CompareTo(j))); } } var types = expectedSyntaxTrees.Select(tree => compilation.GetSemanticModel(tree).GetDeclaredSymbol(tree.GetCompilationUnitRoot().Members.Single())).ToArray(); for (int i = 0; i < numTrees; i++) { for (int j = 0; j < numTrees; j++) { Assert.Equal(Math.Sign(compilation.CompareSourceLocations(types[i].Locations[0], types[j].Locations[0])), Math.Sign(i.CompareTo(j))); } } } #endregion [Fact] public void CorLibTypes() { var mdTestLib1 = TestReferences.SymbolsTests.MDTestLib1; var c1 = CSharpCompilation.Create("Test", references: new MetadataReference[] { MscorlibRef_v4_0_30316_17626, mdTestLib1 }); TypeSymbol c107 = c1.GlobalNamespace.GetTypeMembers("C107").Single(); Assert.Equal(SpecialType.None, c107.SpecialType); for (int i = 1; i <= (int)SpecialType.Count; i++) { NamedTypeSymbol type = c1.GetSpecialType((SpecialType)i); if (i == (int)SpecialType.System_Runtime_CompilerServices_RuntimeFeature || i == (int)SpecialType.System_Runtime_CompilerServices_PreserveBaseOverridesAttribute) { Assert.True(type.IsErrorType()); // Not available } else { Assert.False(type.IsErrorType()); } Assert.Equal((SpecialType)i, type.SpecialType); } Assert.Equal(SpecialType.None, c107.SpecialType); var arrayOfc107 = ArrayTypeSymbol.CreateCSharpArray(c1.Assembly, TypeWithAnnotations.Create(c107)); Assert.Equal(SpecialType.None, arrayOfc107.SpecialType); var c2 = CSharpCompilation.Create("Test", references: new[] { mdTestLib1 }); Assert.Equal(SpecialType.None, c2.GlobalNamespace.GetTypeMembers("C107").Single().SpecialType); } [Fact] public void CyclicReference() { var mscorlibRef = Net451.mscorlib; var cyclic2Ref = TestReferences.SymbolsTests.Cyclic.Cyclic2.dll; var tc1 = CSharpCompilation.Create("Cyclic1", references: new[] { mscorlibRef, cyclic2Ref }); Assert.NotNull(tc1.Assembly); // force creation of SourceAssemblySymbol var cyclic1Asm = (SourceAssemblySymbol)tc1.Assembly; var cyclic1Mod = (SourceModuleSymbol)cyclic1Asm.Modules[0]; var cyclic2Asm = (PEAssemblySymbol)tc1.GetReferencedAssemblySymbol(cyclic2Ref); var cyclic2Mod = (PEModuleSymbol)cyclic2Asm.Modules[0]; Assert.Same(cyclic2Mod.GetReferencedAssemblySymbols()[1], cyclic1Asm); Assert.Same(cyclic1Mod.GetReferencedAssemblySymbols()[1], cyclic2Asm); } [Fact] public void MultiTargeting1() { var varV1MTTestLib2Ref = TestReferences.SymbolsTests.V1.MTTestLib2.dll; var asm1 = MetadataTestHelpers.GetSymbolsForReferences(mrefs: new[] { Net451.mscorlib, varV1MTTestLib2Ref }); Assert.Equal("mscorlib", asm1[0].Identity.Name); Assert.Equal(0, asm1[0].BoundReferences().Length); Assert.Equal("MTTestLib2", asm1[1].Identity.Name); Assert.Equal(1, (from a in asm1[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm1[1].BoundReferences() where object.ReferenceEquals(a, asm1[0]) select a).Count()); Assert.Equal(SymbolKind.ErrorType, asm1[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType.Kind); var asm2 = MetadataTestHelpers.GetSymbolsForReferences(new[] { Net451.mscorlib, varV1MTTestLib2Ref, TestReferences.SymbolsTests.V1.MTTestLib1.dll }); Assert.Same(asm2[0], asm1[0]); Assert.Equal("MTTestLib2", asm2[1].Identity.Name); Assert.NotSame(asm2[1], asm1[1]); Assert.Same(((PEAssemblySymbol)asm2[1]).Assembly, ((PEAssemblySymbol)asm1[1]).Assembly); Assert.Equal(2, (from a in asm2[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); Assert.Equal(1, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[2]) select a).Count()); var retval1 = asm2[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval1.Kind); Assert.Same(retval1, asm2[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm2[2].Identity.Name); Assert.Equal(1, asm2[2].Identity.Version.Major); Assert.Equal(1, (from a in asm2[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[2].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); var varV2MTTestLib3Ref = TestReferences.SymbolsTests.V2.MTTestLib3.dll; var asm3 = MetadataTestHelpers.GetSymbolsForReferences(new[] { Net451.mscorlib, varV1MTTestLib2Ref, TestReferences.SymbolsTests.V2.MTTestLib1.dll, varV2MTTestLib3Ref }); Assert.Same(asm3[0], asm1[0]); Assert.Equal("MTTestLib2", asm3[1].Identity.Name); Assert.NotSame(asm3[1], asm1[1]); Assert.NotSame(asm3[1], asm2[1]); Assert.Same(((PEAssemblySymbol)asm3[1]).Assembly, ((PEAssemblySymbol)asm1[1]).Assembly); Assert.Equal(2, (from a in asm3[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(1, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); var retval2 = asm3[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval2.Kind); Assert.Same(retval2, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm3[2].Identity.Name); Assert.NotSame(asm3[2], asm2[2]); Assert.NotSame(((PEAssemblySymbol)asm3[2]).Assembly, ((PEAssemblySymbol)asm2[2]).Assembly); Assert.Equal(2, asm3[2].Identity.Version.Major); Assert.Equal(1, (from a in asm3[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[2].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal("MTTestLib3", asm3[3].Identity.Name); Assert.Equal(3, (from a in asm3[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[1]) select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); var type1 = asm3[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); var retval3 = type1.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval3.Kind); Assert.Same(retval3, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); var retval4 = type1.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval4.Kind); Assert.Same(retval4, asm3[2].GlobalNamespace.GetMembers("Class2").Single()); var retval5 = type1.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval5.Kind); Assert.Same(retval5, asm3[1].GlobalNamespace.GetMembers("Class4").Single()); var varV3MTTestLib4Ref = TestReferences.SymbolsTests.V3.MTTestLib4.dll; var asm4 = MetadataTestHelpers.GetSymbolsForReferences(new MetadataReference[] { Net451.mscorlib, varV1MTTestLib2Ref, TestReferences.SymbolsTests.V3.MTTestLib1.dll, varV2MTTestLib3Ref, varV3MTTestLib4Ref }); Assert.Same(asm3[0], asm1[0]); Assert.Equal("MTTestLib2", asm4[1].Identity.Name); Assert.NotSame(asm4[1], asm1[1]); Assert.NotSame(asm4[1], asm2[1]); Assert.NotSame(asm4[1], asm3[1]); Assert.Same(((PEAssemblySymbol)asm4[1]).Assembly, ((PEAssemblySymbol)asm1[1]).Assembly); Assert.Equal(2, (from a in asm4[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); var retval6 = asm4[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval6.Kind); Assert.Same(retval6, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm4[2].Identity.Name); Assert.NotSame(asm4[2], asm2[2]); Assert.NotSame(asm4[2], asm3[2]); Assert.NotSame(((PEAssemblySymbol)asm4[2]).Assembly, ((PEAssemblySymbol)asm2[2]).Assembly); Assert.NotSame(((PEAssemblySymbol)asm4[2]).Assembly, ((PEAssemblySymbol)asm3[2]).Assembly); Assert.Equal(3, asm4[2].Identity.Version.Major); Assert.Equal(1, (from a in asm4[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[2].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal("MTTestLib3", asm4[3].Identity.Name); Assert.NotSame(asm4[3], asm3[3]); Assert.Same(((PEAssemblySymbol)asm4[3]).Assembly, ((PEAssemblySymbol)asm3[3]).Assembly); Assert.Equal(3, (from a in asm4[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); var type2 = asm4[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); var retval7 = type2.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval7.Kind); Assert.Same(retval7, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); var retval8 = type2.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval8.Kind); Assert.Same(retval8, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); var retval9 = type2.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval9.Kind); Assert.Same(retval9, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm4[4].Identity.Name); Assert.Equal(4, (from a in asm4[4].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[3]) select a).Count()); var type3 = asm4[4].GlobalNamespace.GetTypeMembers("Class6"). Single(); var retval10 = type3.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval10.Kind); Assert.Same(retval10, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); var retval11 = type3.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval11.Kind); Assert.Same(retval11, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); var retval12 = type3.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval12.Kind); Assert.Same(retval12, asm4[2].GlobalNamespace.GetMembers("Class3").Single()); var retval13 = type3.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval13.Kind); Assert.Same(retval13, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); var retval14 = type3.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval14.Kind); Assert.Same(retval14, asm4[3].GlobalNamespace.GetMembers("Class5").Single()); var asm5 = MetadataTestHelpers.GetSymbolsForReferences(new[] { Net451.mscorlib, varV2MTTestLib3Ref }); Assert.Same(asm5[0], asm1[0]); Assert.True(asm5[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm3[3])); var asm6 = MetadataTestHelpers.GetSymbolsForReferences(new[] { Net451.mscorlib, varV1MTTestLib2Ref }); Assert.Same(asm6[0], asm1[0]); Assert.Same(asm6[1], asm1[1]); var asm7 = MetadataTestHelpers.GetSymbolsForReferences(new[] { Net451.mscorlib, varV1MTTestLib2Ref, varV2MTTestLib3Ref, varV3MTTestLib4Ref }); Assert.Same(asm7[0], asm1[0]); Assert.Same(asm7[1], asm1[1]); Assert.NotSame(asm7[2], asm3[3]); Assert.NotSame(asm7[2], asm4[3]); Assert.NotSame(asm7[3], asm4[4]); Assert.Equal("MTTestLib3", asm7[2].Identity.Name); Assert.Same(((PEAssemblySymbol)asm7[2]).Assembly, ((PEAssemblySymbol)asm3[3]).Assembly); Assert.Equal(2, (from a in asm7[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(1, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); var type4 = asm7[2].GlobalNamespace.GetTypeMembers("Class5"). Single(); var retval15 = type4.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval15.Kind); var retval16 = type4.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval16.Kind); var retval17 = type4.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval17.Kind); Assert.Same(retval17, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm7[3].Identity.Name); Assert.Same(((PEAssemblySymbol)asm7[3]).Assembly, ((PEAssemblySymbol)asm4[4]).Assembly); Assert.Equal(3, (from a in asm7[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[2]) select a).Count()); var type5 = asm7[3].GlobalNamespace.GetTypeMembers("Class6"). Single(); var retval18 = type5.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval18.Kind); var retval19 = type5.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval19.Kind); var retval20 = type5.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval20.Kind); var retval21 = type5.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval21.Kind); Assert.Same(retval21, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); var retval22 = type5.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval22.Kind); Assert.Same(retval22, asm7[2].GlobalNamespace.GetMembers("Class5").Single()); // This test shows that simple reordering of references doesn't pick different set of assemblies var asm8 = MetadataTestHelpers.GetSymbolsForReferences(new[] { Net451.mscorlib, varV3MTTestLib4Ref, varV1MTTestLib2Ref, varV2MTTestLib3Ref }); Assert.Same(asm8[0], asm1[0]); Assert.Same(asm8[0], asm1[0]); Assert.Same(asm8[2], asm7[1]); Assert.True(asm8[3].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[3])); Assert.Same(asm8[3], asm7[2]); Assert.True(asm8[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[4])); Assert.Same(asm8[1], asm7[3]); var asm9 = MetadataTestHelpers.GetSymbolsForReferences(new[] { Net451.mscorlib, varV3MTTestLib4Ref }); Assert.Same(asm9[0], asm1[0]); Assert.True(asm9[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[4])); var asm10 = MetadataTestHelpers.GetSymbolsForReferences(new[] { Net451.mscorlib, varV1MTTestLib2Ref, TestReferences.SymbolsTests.V3.MTTestLib1.dll, varV2MTTestLib3Ref, varV3MTTestLib4Ref }); Assert.Same(asm10[0], asm1[0]); Assert.Same(asm10[1], asm4[1]); Assert.Same(asm10[2], asm4[2]); Assert.Same(asm10[3], asm4[3]); Assert.Same(asm10[4], asm4[4]); // Run the same tests again to make sure we didn't corrupt prior state by loading additional assemblies Assert.Equal("MTTestLib2", asm1[1].Identity.Name); Assert.Equal(1, (from a in asm1[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm1[1].BoundReferences() where ReferenceEquals(a, asm1[0]) select a).Count()); Assert.Equal(SymbolKind.ErrorType, asm1[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType.Kind); Assert.Same(asm2[0], asm1[0]); Assert.Equal("MTTestLib2", asm2[1].Identity.Name); Assert.NotSame(asm2[1], asm1[1]); Assert.Same(((PEAssemblySymbol)asm2[1]).Assembly, ((PEAssemblySymbol)asm1[1]).Assembly); Assert.Equal(2, (from a in asm2[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[1].BoundReferences() where ReferenceEquals(a, asm2[0]) select a).Count()); Assert.Equal(1, (from a in asm2[1].BoundReferences() where ReferenceEquals(a, asm2[2]) select a).Count()); retval1 = asm2[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval1.Kind); Assert.Same(retval1, asm2[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm2[2].Identity.Name); Assert.Equal(1, asm2[2].Identity.Version.Major); Assert.Equal(1, (from a in asm2[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[2].BoundReferences() where ReferenceEquals(a, asm2[0]) select a).Count()); Assert.Same(asm3[0], asm1[0]); Assert.Equal("MTTestLib2", asm3[1].Identity.Name); Assert.NotSame(asm3[1], asm1[1]); Assert.NotSame(asm3[1], asm2[1]); Assert.Same(((PEAssemblySymbol)asm3[1]).Assembly, ((PEAssemblySymbol)asm1[1]).Assembly); Assert.Equal(2, (from a in asm3[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[1].BoundReferences() where ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(1, (from a in asm3[1].BoundReferences() where ReferenceEquals(a, asm3[2]) select a).Count()); retval2 = asm3[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval2.Kind); Assert.Same(retval2, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm3[2].Identity.Name); Assert.NotSame(asm3[2], asm2[2]); Assert.NotSame(((PEAssemblySymbol)asm3[2]).Assembly, ((PEAssemblySymbol)asm2[2]).Assembly); Assert.Equal(2, asm3[2].Identity.Version.Major); Assert.Equal(1, (from a in asm3[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[2].BoundReferences() where ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal("MTTestLib3", asm3[3].Identity.Name); Assert.Equal(3, (from a in asm3[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where ReferenceEquals(a, asm3[1]) select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where ReferenceEquals(a, asm3[2]) select a).Count()); type1 = asm3[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); retval3 = type1.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval3.Kind); Assert.Same(retval3, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); retval4 = type1.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval4.Kind); Assert.Same(retval4, asm3[2].GlobalNamespace.GetMembers("Class2").Single()); retval5 = type1.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval5.Kind); Assert.Same(retval5, asm3[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Same(asm3[0], asm1[0]); Assert.Equal("MTTestLib2", asm4[1].Identity.Name); Assert.NotSame(asm4[1], asm1[1]); Assert.NotSame(asm4[1], asm2[1]); Assert.NotSame(asm4[1], asm3[1]); Assert.Same(((PEAssemblySymbol)asm4[1]).Assembly, ((PEAssemblySymbol)asm1[1]).Assembly); Assert.Equal(2, (from a in asm4[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[1].BoundReferences() where ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[1].BoundReferences() where ReferenceEquals(a, asm4[2]) select a).Count()); retval6 = asm4[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval6.Kind); Assert.Same(retval6, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm4[2].Identity.Name); Assert.NotSame(asm4[2], asm2[2]); Assert.NotSame(asm4[2], asm3[2]); Assert.NotSame(((PEAssemblySymbol)asm4[2]).Assembly, ((PEAssemblySymbol)asm2[2]).Assembly); Assert.NotSame(((PEAssemblySymbol)asm4[2]).Assembly, ((PEAssemblySymbol)asm3[2]).Assembly); Assert.Equal(3, asm4[2].Identity.Version.Major); Assert.Equal(1, (from a in asm4[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[2].BoundReferences() where ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal("MTTestLib3", asm4[3].Identity.Name); Assert.NotSame(asm4[3], asm3[3]); Assert.Same(((PEAssemblySymbol)asm4[3]).Assembly, ((PEAssemblySymbol)asm3[3]).Assembly); Assert.Equal(3, (from a in asm4[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where ReferenceEquals(a, asm4[2]) select a).Count()); type2 = asm4[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); retval7 = type2.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval7.Kind); Assert.Same(retval7, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); retval8 = type2.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval8.Kind); Assert.Same(retval8, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); retval9 = type2.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval9.Kind); Assert.Same(retval9, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm4[4].Identity.Name); Assert.Equal(4, (from a in asm4[4].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where ReferenceEquals(a, asm4[2]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where ReferenceEquals(a, asm4[3]) select a).Count()); type3 = asm4[4].GlobalNamespace.GetTypeMembers("Class6"). Single(); retval10 = type3.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval10.Kind); Assert.Same(retval10, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); retval11 = type3.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval11.Kind); Assert.Same(retval11, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); retval12 = type3.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval12.Kind); Assert.Same(retval12, asm4[2].GlobalNamespace.GetMembers("Class3").Single()); retval13 = type3.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval13.Kind); Assert.Same(retval13, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); retval14 = type3.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval14.Kind); Assert.Same(retval14, asm4[3].GlobalNamespace.GetMembers("Class5").Single()); Assert.Same(asm7[0], asm1[0]); Assert.Same(asm7[1], asm1[1]); Assert.NotSame(asm7[2], asm3[3]); Assert.NotSame(asm7[2], asm4[3]); Assert.NotSame(asm7[3], asm4[4]); Assert.Equal("MTTestLib3", asm7[2].Identity.Name); Assert.Same(((PEAssemblySymbol)asm7[2]).Assembly, ((PEAssemblySymbol)asm3[3]).Assembly); Assert.Equal(2, (from a in asm7[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm7[2].BoundReferences() where ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(1, (from a in asm7[2].BoundReferences() where ReferenceEquals(a, asm7[1]) select a).Count()); type4 = asm7[2].GlobalNamespace.GetTypeMembers("Class5"). Single(); retval15 = type4.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval15.Kind); retval16 = type4.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval16.Kind); retval17 = type4.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval17.Kind); Assert.Same(retval17, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm7[3].Identity.Name); Assert.Same(((PEAssemblySymbol)asm7[3]).Assembly, ((PEAssemblySymbol)asm4[4]).Assembly); Assert.Equal(3, (from a in asm7[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where ReferenceEquals(a, asm7[1]) select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where ReferenceEquals(a, asm7[2]) select a).Count()); type5 = asm7[3].GlobalNamespace.GetTypeMembers("Class6"). Single(); retval18 = type5.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval18.Kind); retval19 = type5.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval19.Kind); retval20 = type5.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval20.Kind); retval21 = type5.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval21.Kind); Assert.Same(retval21, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); retval22 = type5.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval22.Kind); Assert.Same(retval22, asm7[2].GlobalNamespace.GetMembers("Class5").Single()); } [Fact] public void MultiTargeting2() { var varMTTestLib1_V1_Name = new AssemblyIdentity("MTTestLib1", new Version("1.0.0.0")); var varC_MTTestLib1_V1 = CreateCompilation(varMTTestLib1_V1_Name, new string[] { // AssemblyPaths.SymbolsTests.V1.MTTestModule1.netmodule @" public class Class1 { } " }, new[] { Net451.mscorlib }); var asm_MTTestLib1_V1 = varC_MTTestLib1_V1.SourceAssembly().BoundReferences(); var varMTTestLib2_Name = new AssemblyIdentity("MTTestLib2"); var varC_MTTestLib2 = CreateCompilation(varMTTestLib2_Name, new string[] { // AssemblyPaths.SymbolsTests.V1.MTTestModule2.netmodule @" public class Class4 { Class1 Foo() { return null; } public Class1 Bar; } " }, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib1_V1.ToMetadataReference() }); var asm_MTTestLib2 = varC_MTTestLib2.SourceAssembly().BoundReferences(); Assert.Same(asm_MTTestLib2[0], asm_MTTestLib1_V1[0]); Assert.Same(asm_MTTestLib2[1], varC_MTTestLib1_V1.SourceAssembly()); var c2 = CreateCompilation(new AssemblyIdentity("c2"), null, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib2.ToMetadataReference(), varC_MTTestLib1_V1.ToMetadataReference() }); var asm2 = c2.SourceAssembly().BoundReferences(); Assert.Same(asm2[0], asm_MTTestLib1_V1[0]); Assert.Same(asm2[1], varC_MTTestLib2.SourceAssembly()); Assert.Same(asm2[2], varC_MTTestLib1_V1.SourceAssembly()); Assert.Equal("MTTestLib2", asm2[1].Identity.Name); Assert.Equal(2, (from a in asm2[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); Assert.Equal(1, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[2]) select a).Count()); var retval1 = asm2[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval1.Kind); Assert.Same(retval1, asm2[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm2[2].Identity.Name); Assert.Equal(1, asm2[2].Identity.Version.Major); Assert.Equal(1, (from a in asm2[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[2].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); var varMTTestLib1_V2_Name = new AssemblyIdentity("MTTestLib1", new Version("2.0.0.0")); var varC_MTTestLib1_V2 = CreateCompilation(varMTTestLib1_V2_Name, new string[] { // AssemblyPaths.SymbolsTests.V2.MTTestModule1.netmodule @" public class Class1 { } public class Class2 { } " }, new MetadataReference[] { Net451.mscorlib }); var asm_MTTestLib1_V2 = varC_MTTestLib1_V2.SourceAssembly().BoundReferences(); var varMTTestLib3_Name = new AssemblyIdentity("MTTestLib3"); var varC_MTTestLib3 = CreateCompilation(varMTTestLib3_Name, new string[] { // AssemblyPaths.SymbolsTests.V2.MTTestModule3.netmodule @" public class Class5 { Class1 Foo1() { return null; } Class2 Foo2() { return null; } Class4 Foo3() { return null; } Class1 Bar1; Class2 Bar2; Class4 Bar3; } " }, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib2.ToMetadataReference(), varC_MTTestLib1_V2.ToMetadataReference() }); var asm_MTTestLib3 = varC_MTTestLib3.SourceAssembly().BoundReferences(); Assert.Same(asm_MTTestLib3[0], asm_MTTestLib1_V1[0]); Assert.NotSame(asm_MTTestLib3[1], varC_MTTestLib2.SourceAssembly()); Assert.NotSame(asm_MTTestLib3[2], varC_MTTestLib1_V1.SourceAssembly()); var c3 = CreateCompilation(new AssemblyIdentity("c3"), null, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib2.ToMetadataReference(), varC_MTTestLib1_V2.ToMetadataReference(), varC_MTTestLib3.ToMetadataReference() }); var asm3 = c3.SourceAssembly().BoundReferences(); Assert.Same(asm3[0], asm_MTTestLib1_V1[0]); Assert.Same(asm3[1], asm_MTTestLib3[1]); Assert.Same(asm3[2], asm_MTTestLib3[2]); Assert.Same(asm3[3], varC_MTTestLib3.SourceAssembly()); Assert.Equal("MTTestLib2", asm3[1].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm3[1]).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly()); Assert.Equal(2, (from a in asm3[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(1, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); var retval2 = asm3[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval2.Kind); Assert.Same(retval2, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm3[2].Identity.Name); Assert.NotSame(asm3[2], asm2[2]); Assert.NotSame(asm3[2].DeclaringCompilation, asm2[2].DeclaringCompilation); Assert.Equal(2, asm3[2].Identity.Version.Major); Assert.Equal(1, (from a in asm3[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[2].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal("MTTestLib3", asm3[3].Identity.Name); Assert.Equal(3, (from a in asm3[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[1]) select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); var type1 = asm3[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); var retval3 = type1.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval3.Kind); Assert.Same(retval3, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); var retval4 = type1.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval4.Kind); Assert.Same(retval4, asm3[2].GlobalNamespace.GetMembers("Class2").Single()); var retval5 = type1.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval5.Kind); Assert.Same(retval5, asm3[1].GlobalNamespace.GetMembers("Class4").Single()); var varMTTestLib1_V3_Name = new AssemblyIdentity("MTTestLib1", new Version("3.0.0.0")); var varC_MTTestLib1_V3 = CreateCompilation(varMTTestLib1_V3_Name, new string[] { // AssemblyPaths.SymbolsTests.V3.MTTestModule1.netmodule @" public class Class1 { } public class Class2 { } public class Class3 { } " }, new MetadataReference[] { Net451.mscorlib }); var asm_MTTestLib1_V3 = varC_MTTestLib1_V3.SourceAssembly().BoundReferences(); var varMTTestLib4_Name = new AssemblyIdentity("MTTestLib4"); var varC_MTTestLib4 = CreateCompilation(varMTTestLib4_Name, new string[] { // AssemblyPaths.SymbolsTests.V3.MTTestModule4.netmodule @" public class Class6 { Class1 Foo1() { return null; } Class2 Foo2() { return null; } Class3 Foo3() { return null; } Class4 Foo4() { return null; } Class5 Foo5() { return null; } Class1 Bar1; Class2 Bar2; Class3 Bar3; Class4 Bar4; Class5 Bar5; } " }, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib2.ToMetadataReference(), varC_MTTestLib1_V3.ToMetadataReference(), varC_MTTestLib3.ToMetadataReference() }); var asm_MTTestLib4 = varC_MTTestLib4.SourceAssembly().BoundReferences(); Assert.Same(asm_MTTestLib4[0], asm_MTTestLib1_V1[0]); Assert.NotSame(asm_MTTestLib4[1], varC_MTTestLib2.SourceAssembly()); Assert.Same(asm_MTTestLib4[2], varC_MTTestLib1_V3.SourceAssembly()); Assert.NotSame(asm_MTTestLib4[3], varC_MTTestLib3.SourceAssembly()); var c4 = CreateCompilation(new AssemblyIdentity("c4"), null, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib2.ToMetadataReference(), varC_MTTestLib1_V3.ToMetadataReference(), varC_MTTestLib3.ToMetadataReference(), varC_MTTestLib4.ToMetadataReference() }); var asm4 = c4.SourceAssembly().BoundReferences(); Assert.Same(asm4[0], asm_MTTestLib1_V1[0]); Assert.Same(asm4[1], asm_MTTestLib4[1]); Assert.Same(asm4[2], asm_MTTestLib4[2]); Assert.Same(asm4[3], asm_MTTestLib4[3]); Assert.Same(asm4[4], varC_MTTestLib4.SourceAssembly()); Assert.Equal("MTTestLib2", asm4[1].Identity.Name); Assert.NotSame(asm4[1], varC_MTTestLib2.SourceAssembly()); Assert.NotSame(asm4[1], asm2[1]); Assert.NotSame(asm4[1], asm3[1]); Assert.Same(((RetargetingAssemblySymbol)asm4[1]).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly()); Assert.Equal(2, (from a in asm4[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); var retval6 = asm4[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval6.Kind); Assert.Same(retval6, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm4[2].Identity.Name); Assert.NotSame(asm4[2], asm2[2]); Assert.NotSame(asm4[2], asm3[2]); Assert.NotSame(asm4[2].DeclaringCompilation, asm2[2].DeclaringCompilation); Assert.NotSame(asm4[2].DeclaringCompilation, asm3[2].DeclaringCompilation); Assert.Equal(3, asm4[2].Identity.Version.Major); Assert.Equal(1, (from a in asm4[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[2].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal("MTTestLib3", asm4[3].Identity.Name); Assert.NotSame(asm4[3], asm3[3]); Assert.Same(((RetargetingAssemblySymbol)asm4[3]).UnderlyingAssembly, asm3[3]); Assert.Equal(3, (from a in asm4[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); var type2 = asm4[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); var retval7 = type2.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval7.Kind); Assert.Same(retval7, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); var retval8 = type2.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval8.Kind); Assert.Same(retval8, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); var retval9 = type2.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval9.Kind); Assert.Same(retval9, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm4[4].Identity.Name); Assert.Equal(4, (from a in asm4[4].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[3]) select a).Count()); var type3 = asm4[4].GlobalNamespace.GetTypeMembers("Class6"). Single(); var retval10 = type3.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval10.Kind); Assert.Same(retval10, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); var retval11 = type3.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval11.Kind); Assert.Same(retval11, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); var retval12 = type3.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval12.Kind); Assert.Same(retval12, asm4[2].GlobalNamespace.GetMembers("Class3").Single()); var retval13 = type3.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval13.Kind); Assert.Same(retval13, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); var retval14 = type3.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval14.Kind); Assert.Same(retval14, asm4[3].GlobalNamespace.GetMembers("Class5").Single()); var c5 = CreateCompilation(new AssemblyIdentity("c5"), null, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib3.ToMetadataReference() }); var asm5 = c5.SourceAssembly().BoundReferences(); Assert.Same(asm5[0], asm2[0]); Assert.True(asm5[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm3[3])); var c6 = CreateCompilation(new AssemblyIdentity("c6"), null, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib2.ToMetadataReference() }); var asm6 = c6.SourceAssembly().BoundReferences(); Assert.Same(asm6[0], asm2[0]); Assert.True(asm6[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly())); var c7 = CreateCompilation(new AssemblyIdentity("c7"), null, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib2.ToMetadataReference(), varC_MTTestLib3.ToMetadataReference(), varC_MTTestLib4.ToMetadataReference() }); var asm7 = c7.SourceAssembly().BoundReferences(); Assert.Same(asm7[0], asm2[0]); Assert.True(asm7[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly())); Assert.NotSame(asm7[2], asm3[3]); Assert.NotSame(asm7[2], asm4[3]); Assert.NotSame(asm7[3], asm4[4]); Assert.Equal("MTTestLib3", asm7[2].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm7[2]).UnderlyingAssembly, asm3[3]); Assert.Equal(2, (from a in asm7[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(1, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); var type4 = asm7[2].GlobalNamespace.GetTypeMembers("Class5"). Single(); var retval15 = type4.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval15.ContainingAssembly.Name); Assert.Equal(0, (from a in asm7 where a != null && a.Name == "MTTestLib1" select a).Count()); var retval16 = type4.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval16.ContainingAssembly.Name); var retval17 = type4.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval17.Kind); Assert.Same(retval17, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm7[3].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm7[3]).UnderlyingAssembly, asm4[4]); Assert.Equal(3, (from a in asm7[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[2]) select a).Count()); var type5 = asm7[3].GlobalNamespace.GetTypeMembers("Class6"). Single(); var retval18 = type5.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval18.ContainingAssembly.Name); var retval19 = type5.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval19.ContainingAssembly.Name); var retval20 = type5.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval20.ContainingAssembly.Name); var retval21 = type5.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval21.Kind); Assert.Same(retval21, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); var retval22 = type5.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval22.Kind); Assert.Same(retval22, asm7[2].GlobalNamespace.GetMembers("Class5").Single()); // This test shows that simple reordering of references doesn't pick different set of assemblies var c8 = CreateCompilation(new AssemblyIdentity("c8"), null, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib4.ToMetadataReference(), varC_MTTestLib2.ToMetadataReference(), varC_MTTestLib3.ToMetadataReference() }); var asm8 = c8.SourceAssembly().BoundReferences(); Assert.Same(asm8[0], asm2[0]); Assert.True(asm8[2].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[1])); Assert.Same(asm8[2], asm7[1]); Assert.True(asm8[3].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[3])); Assert.Same(asm8[3], asm7[2]); Assert.True(asm8[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[4])); Assert.Same(asm8[1], asm7[3]); var c9 = CreateCompilation(new AssemblyIdentity("c9"), null, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib4.ToMetadataReference() }); var asm9 = c9.SourceAssembly().BoundReferences(); Assert.Same(asm9[0], asm2[0]); Assert.True(asm9[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[4])); var c10 = CreateCompilation(new AssemblyIdentity("c10"), null, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib2.ToMetadataReference(), varC_MTTestLib1_V3.ToMetadataReference(), varC_MTTestLib3.ToMetadataReference(), varC_MTTestLib4.ToMetadataReference() }); var asm10 = c10.SourceAssembly().BoundReferences(); Assert.Same(asm10[0], asm2[0]); Assert.Same(asm10[1], asm4[1]); Assert.Same(asm10[2], asm4[2]); Assert.Same(asm10[3], asm4[3]); Assert.Same(asm10[4], asm4[4]); // Run the same tests again to make sure we didn't corrupt prior state by loading additional assemblies Assert.Same(asm2[0], asm_MTTestLib1_V1[0]); Assert.Equal("MTTestLib2", asm2[1].Identity.Name); Assert.Equal(2, (from a in asm2[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); Assert.Equal(1, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[2]) select a).Count()); retval1 = asm2[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval1.Kind); Assert.Same(retval1, asm2[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm2[2].Identity.Name); Assert.Equal(1, asm2[2].Identity.Version.Major); Assert.Equal(1, (from a in asm2[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[2].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); Assert.Same(asm_MTTestLib3[0], asm_MTTestLib1_V1[0]); Assert.NotSame(asm_MTTestLib3[1], varC_MTTestLib2.SourceAssembly()); Assert.NotSame(asm_MTTestLib3[2], varC_MTTestLib1_V1.SourceAssembly()); Assert.Same(asm3[0], asm_MTTestLib1_V1[0]); Assert.Same(asm3[1], asm_MTTestLib3[1]); Assert.Same(asm3[2], asm_MTTestLib3[2]); Assert.Same(asm3[3], varC_MTTestLib3.SourceAssembly()); Assert.Equal("MTTestLib2", asm3[1].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm3[1]).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly()); Assert.Equal(2, (from a in asm3[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(1, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); retval2 = asm3[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval2.Kind); Assert.Same(retval2, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm3[2].Identity.Name); Assert.NotSame(asm3[2], asm2[2]); Assert.NotSame(asm3[2].DeclaringCompilation, asm2[2].DeclaringCompilation); Assert.Equal(2, asm3[2].Identity.Version.Major); Assert.Equal(1, (from a in asm3[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[2].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal("MTTestLib3", asm3[3].Identity.Name); Assert.Equal(3, (from a in asm3[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[1]) select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); type1 = asm3[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); retval3 = type1.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval3.Kind); Assert.Same(retval3, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); retval4 = type1.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval4.Kind); Assert.Same(retval4, asm3[2].GlobalNamespace.GetMembers("Class2").Single()); retval5 = type1.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval5.Kind); Assert.Same(retval5, asm3[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Same(asm4[0], asm_MTTestLib1_V1[0]); Assert.Same(asm4[1], asm_MTTestLib4[1]); Assert.Same(asm4[2], asm_MTTestLib4[2]); Assert.Same(asm4[3], asm_MTTestLib4[3]); Assert.Same(asm4[4], varC_MTTestLib4.SourceAssembly()); Assert.Equal("MTTestLib2", asm4[1].Identity.Name); Assert.NotSame(asm4[1], varC_MTTestLib2.SourceAssembly()); Assert.NotSame(asm4[1], asm2[1]); Assert.NotSame(asm4[1], asm3[1]); Assert.Same(((RetargetingAssemblySymbol)asm4[1]).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly()); Assert.Equal(2, (from a in asm4[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); retval6 = asm4[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval6.Kind); Assert.Same(retval6, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm4[2].Identity.Name); Assert.NotSame(asm4[2], asm2[2]); Assert.NotSame(asm4[2], asm3[2]); Assert.NotSame(asm4[2].DeclaringCompilation, asm2[2].DeclaringCompilation); Assert.NotSame(asm4[2].DeclaringCompilation, asm3[2].DeclaringCompilation); Assert.Equal(3, asm4[2].Identity.Version.Major); Assert.Equal(1, (from a in asm4[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[2].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal("MTTestLib3", asm4[3].Identity.Name); Assert.NotSame(asm4[3], asm3[3]); Assert.Same(((RetargetingAssemblySymbol)asm4[3]).UnderlyingAssembly, asm3[3]); Assert.Equal(3, (from a in asm4[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); type2 = asm4[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); retval7 = type2.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval7.Kind); Assert.Same(retval7, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); retval8 = type2.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval8.Kind); Assert.Same(retval8, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); retval9 = type2.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval9.Kind); Assert.Same(retval9, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm4[4].Identity.Name); Assert.Equal(4, (from a in asm4[4].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[3]) select a).Count()); type3 = asm4[4].GlobalNamespace.GetTypeMembers("Class6"). Single(); retval10 = type3.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval10.Kind); Assert.Same(retval10, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); retval11 = type3.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval11.Kind); Assert.Same(retval11, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); retval12 = type3.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval12.Kind); Assert.Same(retval12, asm4[2].GlobalNamespace.GetMembers("Class3").Single()); retval13 = type3.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval13.Kind); Assert.Same(retval13, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); retval14 = type3.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval14.Kind); Assert.Same(retval14, asm4[3].GlobalNamespace.GetMembers("Class5").Single()); Assert.Same(asm5[0], asm2[0]); Assert.True(asm5[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm3[3])); Assert.Same(asm6[0], asm2[0]); Assert.True(asm6[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly())); Assert.Same(asm7[0], asm2[0]); Assert.True(asm7[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly())); Assert.NotSame(asm7[2], asm3[3]); Assert.NotSame(asm7[2], asm4[3]); Assert.NotSame(asm7[3], asm4[4]); Assert.Equal("MTTestLib3", asm7[2].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm7[2]).UnderlyingAssembly, asm3[3]); Assert.Equal(2, (from a in asm7[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(1, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); type4 = asm7[2].GlobalNamespace.GetTypeMembers("Class5"). Single(); retval15 = type4.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval15.ContainingAssembly.Name); Assert.Equal(0, (from a in asm7 where a != null && a.Name == "MTTestLib1" select a).Count()); retval16 = type4.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval16.ContainingAssembly.Name); retval17 = type4.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval17.Kind); Assert.Same(retval17, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm7[3].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm7[3]).UnderlyingAssembly, asm4[4]); Assert.Equal(3, (from a in asm7[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[2]) select a).Count()); type5 = asm7[3].GlobalNamespace.GetTypeMembers("Class6"). Single(); retval18 = type5.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval18.ContainingAssembly.Name); retval19 = type5.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval19.ContainingAssembly.Name); retval20 = type5.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval20.ContainingAssembly.Name); retval21 = type5.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval21.Kind); Assert.Same(retval21, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); retval22 = type5.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval22.Kind); Assert.Same(retval22, asm7[2].GlobalNamespace.GetMembers("Class5").Single()); } [Fact] public void MultiTargeting3() { var varMTTestLib2_Name = new AssemblyIdentity("MTTestLib2"); var varC_MTTestLib2 = CreateCompilation(varMTTestLib2_Name, (string[])null, new[] { Net451.mscorlib, TestReferences.SymbolsTests.V1.MTTestLib1.dll, TestReferences.SymbolsTests.V1.MTTestModule2.netmodule }); var asm_MTTestLib2 = varC_MTTestLib2.SourceAssembly().BoundReferences(); var c2 = CreateCompilation(new AssemblyIdentity("c2"), null, new MetadataReference[] { Net451.mscorlib, TestReferences.SymbolsTests.V1.MTTestLib1.dll, new CSharpCompilationReference(varC_MTTestLib2) }); var asm2Prime = c2.SourceAssembly().BoundReferences(); var asm2 = new AssemblySymbol[] { asm2Prime[0], asm2Prime[2], asm2Prime[1] }; Assert.Same(asm2[0], asm_MTTestLib2[0]); Assert.Same(asm2[1], varC_MTTestLib2.SourceAssembly()); Assert.Same(asm2[2], asm_MTTestLib2[1]); Assert.Equal("MTTestLib2", asm2[1].Identity.Name); Assert.Equal(4, (from a in asm2[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); Assert.Equal(2, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[2]) select a).Count()); var retval1 = asm2[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.Same(retval1, asm2[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Bar").OfType<FieldSymbol>().Single().Type); Assert.NotEqual(SymbolKind.ErrorType, retval1.Kind); Assert.Same(retval1, asm2[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm2[2].Identity.Name); Assert.Equal(1, asm2[2].Identity.Version.Major); Assert.Equal(1, (from a in asm2[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[2].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); var varMTTestLib3_Name = new AssemblyIdentity("MTTestLib3"); var varC_MTTestLib3 = CreateCompilation(varMTTestLib3_Name, null, new MetadataReference[] { Net451.mscorlib, TestReferences.SymbolsTests.V2.MTTestLib1.dll, new CSharpCompilationReference(varC_MTTestLib2), TestReferences.SymbolsTests.V2.MTTestModule3.netmodule }); var asm_MTTestLib3Prime = varC_MTTestLib3.SourceAssembly().BoundReferences(); var asm_MTTestLib3 = new AssemblySymbol[] { asm_MTTestLib3Prime[0], asm_MTTestLib3Prime[2], asm_MTTestLib3Prime[1] }; Assert.Same(asm_MTTestLib3[0], asm_MTTestLib2[0]); Assert.NotSame(asm_MTTestLib3[1], varC_MTTestLib2.SourceAssembly()); Assert.NotSame(asm_MTTestLib3[2], asm_MTTestLib2[1]); var c3 = CreateCompilation(new AssemblyIdentity("c3"), null, new MetadataReference[] { Net451.mscorlib, TestReferences.SymbolsTests.V2.MTTestLib1.dll, new CSharpCompilationReference(varC_MTTestLib2), new CSharpCompilationReference(varC_MTTestLib3) }); var asm3Prime = c3.SourceAssembly().BoundReferences(); var asm3 = new AssemblySymbol[] { asm3Prime[0], asm3Prime[2], asm3Prime[1], asm3Prime[3] }; Assert.Same(asm3[0], asm_MTTestLib2[0]); Assert.Same(asm3[1], asm_MTTestLib3[1]); Assert.Same(asm3[2], asm_MTTestLib3[2]); Assert.Same(asm3[3], varC_MTTestLib3.SourceAssembly()); Assert.Equal("MTTestLib2", asm3[1].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm3[1]).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly()); Assert.Equal(4, (from a in asm3[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(2, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); var retval2 = asm3[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.Same(retval2, asm3[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Bar").OfType<FieldSymbol>().Single().Type); Assert.NotEqual(SymbolKind.ErrorType, retval2.Kind); Assert.Same(retval2, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm3[2].Identity.Name); Assert.NotSame(asm3[2], asm2[2]); Assert.NotSame(asm3[2], asm2[2]); Assert.NotSame(((PEAssemblySymbol)asm3[2]).Assembly, ((PEAssemblySymbol)asm2[2]).Assembly); Assert.Equal(2, asm3[2].Identity.Version.Major); Assert.Equal(1, (from a in asm3[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[2].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal("MTTestLib3", asm3[3].Identity.Name); Assert.Equal(6, (from a in asm3[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(2, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[1]) select a).Count()); Assert.Equal(2, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); var type1 = asm3[3].GlobalNamespace.GetTypeMembers("Class5").Single(); var retval3 = type1.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval3.Kind); Assert.Same(retval3, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); var retval4 = type1.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval4.Kind); Assert.Same(retval4, asm3[2].GlobalNamespace.GetMembers("Class2").Single()); var retval5 = type1.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval5.Kind); Assert.Same(retval5, asm3[1].GlobalNamespace.GetMembers("Class4").Single()); var varMTTestLib4_Name = new AssemblyIdentity("MTTestLib4"); var varC_MTTestLib4 = CreateCompilation(varMTTestLib4_Name, null, new MetadataReference[] { Net451.mscorlib, TestReferences.SymbolsTests.V3.MTTestLib1.dll, new CSharpCompilationReference(varC_MTTestLib2), new CSharpCompilationReference(varC_MTTestLib3), TestReferences.SymbolsTests.V3.MTTestModule4.netmodule }); var asm_MTTestLib4Prime = varC_MTTestLib4.SourceAssembly().BoundReferences(); var asm_MTTestLib4 = new AssemblySymbol[] { asm_MTTestLib4Prime[0], asm_MTTestLib4Prime[2], asm_MTTestLib4Prime[1], asm_MTTestLib4Prime[3] }; Assert.Same(asm_MTTestLib4[0], asm_MTTestLib2[0]); Assert.NotSame(asm_MTTestLib4[1], varC_MTTestLib2.SourceAssembly()); Assert.NotSame(asm_MTTestLib4[2], asm3[2]); Assert.NotSame(asm_MTTestLib4[2], asm2[2]); Assert.NotSame(asm_MTTestLib4[3], varC_MTTestLib3.SourceAssembly()); var c4 = CreateCompilation(new AssemblyIdentity("c4"), null, new MetadataReference[] { Net451.mscorlib, TestReferences.SymbolsTests.V3.MTTestLib1.dll, new CSharpCompilationReference(varC_MTTestLib2), new CSharpCompilationReference(varC_MTTestLib3), new CSharpCompilationReference(varC_MTTestLib4) }); var asm4Prime = c4.SourceAssembly().BoundReferences(); var asm4 = new AssemblySymbol[] { asm4Prime[0], asm4Prime[2], asm4Prime[1], asm4Prime[3], asm4Prime[4] }; Assert.Same(asm4[0], asm_MTTestLib2[0]); Assert.Same(asm4[1], asm_MTTestLib4[1]); Assert.Same(asm4[2], asm_MTTestLib4[2]); Assert.Same(asm4[3], asm_MTTestLib4[3]); Assert.Same(asm4[4], varC_MTTestLib4.SourceAssembly()); Assert.Equal("MTTestLib2", asm4[1].Identity.Name); Assert.NotSame(asm4[1], varC_MTTestLib2.SourceAssembly()); Assert.NotSame(asm4[1], asm2[1]); Assert.NotSame(asm4[1], asm3[1]); Assert.Same(((RetargetingAssemblySymbol)asm4[1]).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly()); Assert.Equal(4, (from a in asm4[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(2, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); var retval6 = asm4[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval6.Kind); Assert.Same(retval6, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm4[2].Identity.Name); Assert.NotSame(asm4[2], asm2[2]); Assert.NotSame(asm4[2], asm3[2]); Assert.NotSame(((PEAssemblySymbol)asm4[2]).Assembly, ((PEAssemblySymbol)asm2[2]).Assembly); Assert.NotSame(((PEAssemblySymbol)asm4[2]).Assembly, ((PEAssemblySymbol)asm3[2]).Assembly); Assert.Equal(3, asm4[2].Identity.Version.Major); Assert.Equal(1, (from a in asm4[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[2].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal("MTTestLib3", asm4[3].Identity.Name); Assert.NotSame(asm4[3], asm3[3]); Assert.Same(((RetargetingAssemblySymbol)asm4[3]).UnderlyingAssembly, asm3[3]); Assert.Equal(6, (from a in asm4[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(2, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(2, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); var type2 = asm4[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); var retval7 = type2.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval7.Kind); Assert.Same(retval7, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); var retval8 = type2.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval8.Kind); Assert.Same(retval8, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); var retval9 = type2.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval9.Kind); Assert.Same(retval9, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm4[4].Identity.Name); Assert.Equal(8, (from a in asm4[4].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(2, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(2, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); Assert.Equal(2, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[3]) select a).Count()); var type3 = asm4[4].GlobalNamespace.GetTypeMembers("Class6"). Single(); var retval10 = type3.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval10.Kind); Assert.Same(retval10, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); var retval11 = type3.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval11.Kind); Assert.Same(retval11, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); var retval12 = type3.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval12.Kind); Assert.Same(retval12, asm4[2].GlobalNamespace.GetMembers("Class3").Single()); var retval13 = type3.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval13.Kind); Assert.Same(retval13, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); var retval14 = type3.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval14.Kind); Assert.Same(retval14, asm4[3].GlobalNamespace.GetMembers("Class5").Single()); var c5 = CreateCompilation(new AssemblyIdentity("c5"), null, new MetadataReference[] { Net451.mscorlib, new CSharpCompilationReference(varC_MTTestLib3) }); var asm5 = c5.SourceAssembly().BoundReferences(); Assert.Same(asm5[0], asm2[0]); Assert.True(asm5[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm3[3])); var c6 = CreateCompilation(new AssemblyIdentity("c6"), null, new MetadataReference[] { Net451.mscorlib, new CSharpCompilationReference(varC_MTTestLib2) }); var asm6 = c6.SourceAssembly().BoundReferences(); Assert.Same(asm6[0], asm2[0]); Assert.True(asm6[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly())); var c7 = CreateCompilation(new AssemblyIdentity("c7"), null, new MetadataReference[] { Net451.mscorlib, new CSharpCompilationReference(varC_MTTestLib2), new CSharpCompilationReference(varC_MTTestLib3), new CSharpCompilationReference(varC_MTTestLib4) }); var asm7 = c7.SourceAssembly().BoundReferences(); Assert.Same(asm7[0], asm2[0]); Assert.True(asm7[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly())); Assert.NotSame(asm7[2], asm3[3]); Assert.NotSame(asm7[2], asm4[3]); Assert.NotSame(asm7[3], asm4[4]); Assert.Equal("MTTestLib3", asm7[2].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm7[2]).UnderlyingAssembly, asm3[3]); Assert.Equal(4, (from a in asm7[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(2, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); var type4 = asm7[2].GlobalNamespace.GetTypeMembers("Class5"). Single(); var retval15 = type4.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; AssemblySymbol missingAssembly; missingAssembly = retval15.ContainingAssembly; Assert.True(missingAssembly.IsMissing); Assert.Equal("MTTestLib1", missingAssembly.Identity.Name); var retval16 = type4.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Same(missingAssembly, retval16.ContainingAssembly); var retval17 = type4.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval17.Kind); Assert.Same(retval17, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm7[3].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm7[3]).UnderlyingAssembly, asm4[4]); Assert.Equal(6, (from a in asm7[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(2, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); Assert.Equal(2, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[2]) select a).Count()); var type5 = asm7[3].GlobalNamespace.GetTypeMembers("Class6"). Single(); var retval18 = type5.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", ((MissingMetadataTypeSymbol)retval18).ContainingAssembly.Identity.Name); var retval19 = type5.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Same(retval18.ContainingAssembly, retval19.ContainingAssembly); var retval20 = type5.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.Same(retval18.ContainingAssembly, retval20.ContainingAssembly); var retval21 = type5.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval21.Kind); Assert.Same(retval21, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); var retval22 = type5.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval22.Kind); Assert.Same(retval22, asm7[2].GlobalNamespace.GetMembers("Class5").Single()); // This test shows that simple reordering of references doesn't pick different set of assemblies var c8 = CreateCompilation(new AssemblyIdentity("c8"), null, new MetadataReference[] { Net451.mscorlib, new CSharpCompilationReference(varC_MTTestLib4), new CSharpCompilationReference(varC_MTTestLib2), new CSharpCompilationReference(varC_MTTestLib3) }); var asm8 = c8.SourceAssembly().BoundReferences(); Assert.Same(asm8[0], asm2[0]); Assert.True(asm8[2].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[1])); Assert.Same(asm8[2], asm7[1]); Assert.True(asm8[3].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[3])); Assert.Same(asm8[3], asm7[2]); Assert.True(asm8[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[4])); Assert.Same(asm8[1], asm7[3]); var c9 = CreateCompilation(new AssemblyIdentity("c9"), null, new MetadataReference[] { Net451.mscorlib, new CSharpCompilationReference(varC_MTTestLib4) }); var asm9 = c9.SourceAssembly().BoundReferences(); Assert.Same(asm9[0], asm2[0]); Assert.True(asm9[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[4])); var c10 = CreateCompilation(new AssemblyIdentity("c10"), null, new MetadataReference[] { Net451.mscorlib, TestReferences.SymbolsTests.V3.MTTestLib1.dll, new CSharpCompilationReference(varC_MTTestLib2), new CSharpCompilationReference(varC_MTTestLib3), new CSharpCompilationReference(varC_MTTestLib4) }); var asm10Prime = c10.SourceAssembly().BoundReferences(); var asm10 = new AssemblySymbol[] { asm10Prime[0], asm10Prime[2], asm10Prime[1], asm10Prime[3], asm10Prime[4] }; Assert.Same(asm10[0], asm2[0]); Assert.Same(asm10[1], asm4[1]); Assert.Same(asm10[2], asm4[2]); Assert.Same(asm10[3], asm4[3]); Assert.Same(asm10[4], asm4[4]); // Run the same tests again to make sure we didn't corrupt prior state by loading additional assemblies Assert.Same(asm2[0], asm_MTTestLib2[0]); Assert.Equal("MTTestLib2", asm2[1].Identity.Name); Assert.Equal(4, (from a in asm2[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); Assert.Equal(2, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[2]) select a).Count()); retval1 = asm2[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval1.Kind); Assert.Same(retval1, asm2[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm2[2].Identity.Name); Assert.Equal(1, asm2[2].Identity.Version.Major); Assert.Equal(1, (from a in asm2[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[2].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); Assert.Same(asm_MTTestLib3[0], asm_MTTestLib2[0]); Assert.NotSame(asm_MTTestLib3[1], varC_MTTestLib2.SourceAssembly()); Assert.NotSame(asm_MTTestLib3[2], asm_MTTestLib2[1]); Assert.Same(asm3[0], asm_MTTestLib2[0]); Assert.Same(asm3[1], asm_MTTestLib3[1]); Assert.Same(asm3[2], asm_MTTestLib3[2]); Assert.Same(asm3[3], varC_MTTestLib3.SourceAssembly()); Assert.Equal("MTTestLib2", asm3[1].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm3[1]).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly()); Assert.Equal(4, (from a in asm3[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(2, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); retval2 = asm3[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval2.Kind); Assert.Same(retval2, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm3[2].Identity.Name); Assert.NotSame(asm3[2], asm2[2]); Assert.NotSame(((PEAssemblySymbol)asm3[2]).Assembly, ((PEAssemblySymbol)asm2[2]).Assembly); Assert.Equal(2, asm3[2].Identity.Version.Major); Assert.Equal(1, (from a in asm3[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[2].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal("MTTestLib3", asm3[3].Identity.Name); Assert.Equal(6, (from a in asm3[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(2, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[1]) select a).Count()); Assert.Equal(2, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); type1 = asm3[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); retval3 = type1.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval3.Kind); Assert.Same(retval3, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); retval4 = type1.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval4.Kind); Assert.Same(retval4, asm3[2].GlobalNamespace.GetMembers("Class2").Single()); retval5 = type1.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval5.Kind); Assert.Same(retval5, asm3[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Same(asm4[0], asm_MTTestLib2[0]); Assert.Same(asm4[1], asm_MTTestLib4[1]); Assert.Same(asm4[2], asm_MTTestLib4[2]); Assert.Same(asm4[3], asm_MTTestLib4[3]); Assert.Same(asm4[4], varC_MTTestLib4.SourceAssembly()); Assert.Equal("MTTestLib2", asm4[1].Identity.Name); Assert.NotSame(asm4[1], varC_MTTestLib2.SourceAssembly()); Assert.NotSame(asm4[1], asm2[1]); Assert.NotSame(asm4[1], asm3[1]); Assert.Same(((RetargetingAssemblySymbol)asm4[1]).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly()); Assert.Equal(4, (from a in asm4[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(2, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); retval6 = asm4[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval6.Kind); Assert.Same(retval6, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm4[2].Identity.Name); Assert.NotSame(asm4[2], asm2[2]); Assert.NotSame(asm4[2], asm3[2]); Assert.NotSame(((PEAssemblySymbol)asm4[2]).Assembly, ((PEAssemblySymbol)asm2[2]).Assembly); Assert.NotSame(((PEAssemblySymbol)asm4[2]).Assembly, ((PEAssemblySymbol)asm3[2]).Assembly); Assert.Equal(3, asm4[2].Identity.Version.Major); Assert.Equal(1, (from a in asm4[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[2].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal("MTTestLib3", asm4[3].Identity.Name); Assert.NotSame(asm4[3], asm3[3]); Assert.Same(((RetargetingAssemblySymbol)asm4[3]).UnderlyingAssembly, asm3[3]); Assert.Equal(6, (from a in asm4[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(2, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(2, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); type2 = asm4[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); retval7 = type2.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval7.Kind); Assert.Same(retval7, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); retval8 = type2.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval8.Kind); Assert.Same(retval8, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); retval9 = type2.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval9.Kind); Assert.Same(retval9, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm4[4].Identity.Name); Assert.Equal(8, (from a in asm4[4].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(2, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(2, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); Assert.Equal(2, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[3]) select a).Count()); type3 = asm4[4].GlobalNamespace.GetTypeMembers("Class6"). Single(); retval10 = type3.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval10.Kind); Assert.Same(retval10, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); retval11 = type3.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval11.Kind); Assert.Same(retval11, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); retval12 = type3.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval12.Kind); Assert.Same(retval12, asm4[2].GlobalNamespace.GetMembers("Class3").Single()); retval13 = type3.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval13.Kind); Assert.Same(retval13, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); retval14 = type3.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval14.Kind); Assert.Same(retval14, asm4[3].GlobalNamespace.GetMembers("Class5").Single()); Assert.Same(asm5[0], asm2[0]); Assert.True(asm5[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm3[3])); Assert.Same(asm6[0], asm2[0]); Assert.True(asm6[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly())); Assert.Same(asm7[0], asm2[0]); Assert.True(asm7[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly())); Assert.NotSame(asm7[2], asm3[3]); Assert.NotSame(asm7[2], asm4[3]); Assert.NotSame(asm7[3], asm4[4]); Assert.Equal("MTTestLib3", asm7[2].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm7[2]).UnderlyingAssembly, asm3[3]); Assert.Equal(4, (from a in asm7[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(2, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); type4 = asm7[2].GlobalNamespace.GetTypeMembers("Class5"). Single(); retval15 = type4.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; missingAssembly = retval15.ContainingAssembly; Assert.True(missingAssembly.IsMissing); Assert.Equal("MTTestLib1", missingAssembly.Identity.Name); retval16 = type4.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Same(missingAssembly, retval16.ContainingAssembly); retval17 = type4.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval17.Kind); Assert.Same(retval17, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm7[3].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm7[3]).UnderlyingAssembly, asm4[4]); Assert.Equal(6, (from a in asm7[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(2, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); Assert.Equal(2, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[2]) select a).Count()); type5 = asm7[3].GlobalNamespace.GetTypeMembers("Class6"). Single(); retval18 = type5.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", ((MissingMetadataTypeSymbol)retval18).ContainingAssembly.Identity.Name); retval19 = type5.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Same(retval18.ContainingAssembly, retval19.ContainingAssembly); retval20 = type5.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.Same(retval18.ContainingAssembly, retval20.ContainingAssembly); retval21 = type5.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval21.Kind); Assert.Same(retval21, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); retval22 = type5.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval22.Kind); Assert.Same(retval22, asm7[2].GlobalNamespace.GetMembers("Class5").Single()); } [Fact] public void MultiTargeting4() { var localC1_V1_Name = new AssemblyIdentity("c1", new Version("1.0.0.0")); var localC1_V1 = CreateCompilation(localC1_V1_Name, new string[] { // AssemblyPaths.SymbolsTests.MultiTargeting.Source1Module.netmodule @" public class C1<T> { public class C2<S> { public C1<T>.C2<S> Foo() { return null; } } } " }, new[] { Net451.mscorlib }); var asm1_V1 = localC1_V1.SourceAssembly(); var localC1_V2_Name = new AssemblyIdentity("c1", new Version("2.0.0.0")); var localC1_V2 = CreateCompilation(localC1_V2_Name, new string[] { // AssemblyPaths.SymbolsTests.MultiTargeting.Source1Module.netmodule @" public class C1<T> { public class C2<S> { public C1<T>.C2<S> Foo() { return null; } } } " }, new MetadataReference[] { Net451.mscorlib }); var asm1_V2 = localC1_V2.SourceAssembly(); var localC4_V1_Name = new AssemblyIdentity("c4", new Version("1.0.0.0")); var localC4_V1 = CreateCompilation(localC4_V1_Name, new string[] { // AssemblyPaths.SymbolsTests.MultiTargeting.Source4Module.netmodule @" public class C4 { } " }, new MetadataReference[] { Net451.mscorlib }); var asm4_V1 = localC4_V1.SourceAssembly(); var localC4_V2_Name = new AssemblyIdentity("c4", new Version("2.0.0.0")); var localC4_V2 = CreateCompilation(localC4_V2_Name, new string[] { // AssemblyPaths.SymbolsTests.MultiTargeting.Source4Module.netmodule @" public class C4 { } " }, new MetadataReference[] { Net451.mscorlib }); var asm4_V2 = localC4_V2.SourceAssembly(); var c7 = CreateCompilation(new AssemblyIdentity("C7"), new string[] { // AssemblyPaths.SymbolsTests.MultiTargeting.Source7Module.netmodule @" public class C7 {} public class C8<T> { } " }, new MetadataReference[] { Net451.mscorlib }); var asm7 = c7.SourceAssembly(); var c3 = CreateCompilation(new AssemblyIdentity("C3"), new string[] { // AssemblyPaths.SymbolsTests.MultiTargeting.Source3Module.netmodule @" public class C3 { public C1<C3>.C2<C4> Foo() { return null; } public static C6<C4> Bar() { return null; } public C8<C7> Foo1() { return null; } public void Foo2(ref C300[,] x1, out C4 x2, ref C7[] x3, C4 x4 = null) { x2 = null; } internal virtual TFoo3 Foo3<TFoo3>() where TFoo3: C4 { return null; } public C8<C4> Foo4() { return null; } public abstract class C301 : I1 { } internal class C302 { } } public class C6<T> where T: new () {} public class C300 {} public interface I1 {} namespace ns1 { namespace ns2 { public class C303 {} } public class C304 { public class C305 {} } } " }, new MetadataReference[] { Net451.mscorlib, new CSharpCompilationReference(localC1_V1), new CSharpCompilationReference(localC4_V1), new CSharpCompilationReference(c7) }); var asm3 = c3.SourceAssembly(); var localC3Foo2 = asm3.GlobalNamespace.GetTypeMembers("C3"). Single().GetMembers("Foo2").OfType<MethodSymbol>().Single(); var c5 = CreateCompilation(new AssemblyIdentity("C5"), new string[] { // AssemblyPaths.SymbolsTests.MultiTargeting.Source5Module.netmodule @" public class C5 : ns1.C304.C305 {} " }, new MetadataReference[] { Net451.mscorlib, new CSharpCompilationReference(c3), new CSharpCompilationReference(localC1_V2), new CSharpCompilationReference(localC4_V2), new CSharpCompilationReference(c7) }); var asm5 = c5.SourceAssembly().BoundReferences(); Assert.NotSame(asm5[1], asm3); Assert.Same(((RetargetingAssemblySymbol)asm5[1]).UnderlyingAssembly, asm3); Assert.Same(asm5[2], asm1_V2); Assert.Same(asm5[3], asm4_V2); Assert.Same(asm5[4], asm7); var type3 = asm5[1].GlobalNamespace.GetTypeMembers("C3"). Single(); var type1 = asm1_V2.GlobalNamespace.GetTypeMembers("C1"). Single(); var type2 = type1.GetTypeMembers("C2"). Single(); var type4 = asm4_V2.GlobalNamespace.GetTypeMembers("C4"). Single(); var retval1 = (NamedTypeSymbol)type3.GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("C1<C3>.C2<C4>", retval1.ToTestDisplayString()); Assert.Same(retval1.OriginalDefinition, type2); var args1 = retval1.ContainingType.TypeArguments().Concat(retval1.TypeArguments()); var params1 = retval1.ContainingType.TypeParameters.Concat(retval1.TypeParameters); Assert.Same(params1[0], type1.TypeParameters[0]); Assert.Same(params1[1].OriginalDefinition, type2.TypeParameters[0].OriginalDefinition); Assert.Same(args1[0], type3); Assert.Same(args1[0].ContainingAssembly, asm5[1]); Assert.Same(args1[1], type4); var retval2 = retval1.ContainingType; Assert.Equal("C1<C3>", retval2.ToTestDisplayString()); Assert.Same(retval2.OriginalDefinition, type1); var bar = type3.GetMembers("Bar").OfType<MethodSymbol>().Single(); var retval3 = (NamedTypeSymbol)bar.ReturnType; var type6 = asm5[1].GlobalNamespace.GetTypeMembers("C6"). Single(); Assert.Equal("C6<C4>", retval3.ToTestDisplayString()); Assert.Same(retval3.OriginalDefinition, type6); Assert.Same(retval3.ContainingAssembly, asm5[1]); var args3 = retval3.TypeArguments(); var params3 = retval3.TypeParameters; Assert.Same(params3[0], type6.TypeParameters[0]); Assert.Same(params3[0].ContainingAssembly, asm5[1]); Assert.Same(args3[0], type4); var foo1 = type3.GetMembers("Foo1").OfType<MethodSymbol>().Single(); var retval4 = foo1.ReturnType; Assert.Equal("C8<C7>", retval4.ToTestDisplayString()); Assert.Same(retval4, asm3.GlobalNamespace.GetTypeMembers("C3"). Single(). GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType); var foo1Params = foo1.Parameters; Assert.Equal(0, foo1Params.Length); var foo2 = type3.GetMembers("Foo2").OfType<MethodSymbol>().Single(); Assert.NotEqual(localC3Foo2, foo2); Assert.Same(localC3Foo2, ((RetargetingMethodSymbol)foo2).UnderlyingMethod); Assert.Equal(1, ((RetargetingMethodSymbol)foo2).Locations.Length); var foo2Params = foo2.Parameters; Assert.Equal(4, foo2Params.Length); Assert.Same(localC3Foo2.Parameters[0], ((RetargetingParameterSymbol)foo2Params[0]).UnderlyingParameter); Assert.Same(localC3Foo2.Parameters[1], ((RetargetingParameterSymbol)foo2Params[1]).UnderlyingParameter); Assert.Same(localC3Foo2.Parameters[2], ((RetargetingParameterSymbol)foo2Params[2]).UnderlyingParameter); Assert.Same(localC3Foo2.Parameters[3], ((RetargetingParameterSymbol)foo2Params[3]).UnderlyingParameter); var x1 = foo2Params[0]; var x2 = foo2Params[1]; var x3 = foo2Params[2]; var x4 = foo2Params[3]; Assert.Equal("x1", x1.Name); Assert.NotEqual(localC3Foo2.Parameters[0].Type, x1.Type); Assert.Equal(localC3Foo2.Parameters[0].ToTestDisplayString(), x1.ToTestDisplayString()); Assert.Same(asm5[1], x1.ContainingAssembly); Assert.Same(foo2, x1.ContainingSymbol); Assert.False(x1.HasExplicitDefaultValue); Assert.False(x1.IsOptional); Assert.Equal(RefKind.Ref, x1.RefKind); Assert.Equal(2, ((ArrayTypeSymbol)x1.Type).Rank); Assert.Equal("x2", x2.Name); Assert.NotEqual(localC3Foo2.Parameters[1].Type, x2.Type); Assert.Equal(RefKind.Out, x2.RefKind); Assert.Equal("x3", x3.Name); Assert.Same(localC3Foo2.Parameters[2].Type, x3.Type); Assert.Equal("x4", x4.Name); Assert.True(x4.HasExplicitDefaultValue); Assert.True(x4.IsOptional); Assert.Equal("Foo2", foo2.Name); Assert.Equal(localC3Foo2.ToTestDisplayString(), foo2.ToTestDisplayString()); Assert.Same(asm5[1], foo2.ContainingAssembly); Assert.Same(type3, foo2.ContainingSymbol); Assert.Equal(Accessibility.Public, foo2.DeclaredAccessibility); Assert.False(foo2.HidesBaseMethodsByName); Assert.False(foo2.IsAbstract); Assert.False(foo2.IsExtern); Assert.False(foo2.IsGenericMethod); Assert.False(foo2.IsOverride); Assert.False(foo2.IsSealed); Assert.False(foo2.IsStatic); Assert.False(foo2.IsVararg); Assert.False(foo2.IsVirtual); Assert.True(foo2.ReturnsVoid); Assert.Equal(0, foo2.TypeParameters.Length); Assert.Equal(0, foo2.TypeArgumentsWithAnnotations.Length); Assert.True(bar.IsStatic); Assert.False(bar.ReturnsVoid); var foo3 = type3.GetMembers("Foo3").OfType<MethodSymbol>().Single(); Assert.Equal(Accessibility.Internal, foo3.DeclaredAccessibility); Assert.True(foo3.IsGenericMethod); Assert.True(foo3.IsVirtual); var foo3TypeParams = foo3.TypeParameters; Assert.Equal(1, foo3TypeParams.Length); Assert.Equal(1, foo3.TypeArgumentsWithAnnotations.Length); Assert.Same(foo3TypeParams[0], foo3.TypeArgumentsWithAnnotations[0].Type); var typeC301 = type3.GetTypeMembers("C301").Single(); var typeC302 = type3.GetTypeMembers("C302").Single(); var typeC6 = asm5[1].GlobalNamespace.GetTypeMembers("C6").Single(); Assert.Equal(typeC301.ToTestDisplayString(), asm3.GlobalNamespace.GetTypeMembers("C3").Single(). GetTypeMembers("C301").Single().ToTestDisplayString()); Assert.Equal(typeC6.ToTestDisplayString(), asm3.GlobalNamespace.GetTypeMembers("C6").Single().ToTestDisplayString()); Assert.Equal(typeC301.ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat), asm3.GlobalNamespace.GetTypeMembers("C3").Single(). GetTypeMembers("C301").Single().ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat)); Assert.Equal(typeC6.ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat), asm3.GlobalNamespace.GetTypeMembers("C6").Single().ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat)); Assert.Equal(type3.GetMembers().Length, asm3.GlobalNamespace.GetTypeMembers("C3").Single().GetMembers().Length); Assert.Equal(type3.GetTypeMembers().Length, asm3.GlobalNamespace.GetTypeMembers("C3").Single().GetTypeMembers().Length); Assert.Same(typeC301, type3.GetTypeMembers("C301", 0).Single()); Assert.Equal(0, type3.Arity); Assert.Equal(1, typeC6.Arity); Assert.NotNull(type3.BaseType()); Assert.Equal("System.Object", type3.BaseType().ToTestDisplayString()); Assert.Equal(Accessibility.Public, type3.DeclaredAccessibility); Assert.Equal(Accessibility.Internal, typeC302.DeclaredAccessibility); Assert.Equal(0, type3.Interfaces().Length); Assert.Equal(1, typeC301.Interfaces().Length); Assert.Equal("I1", typeC301.Interfaces().Single().Name); Assert.False(type3.IsAbstract); Assert.True(typeC301.IsAbstract); Assert.False(type3.IsSealed); Assert.False(type3.IsStatic); Assert.Equal(0, type3.TypeArguments().Length); Assert.Equal(0, type3.TypeParameters.Length); var localC6Params = typeC6.TypeParameters; Assert.Equal(1, localC6Params.Length); Assert.Equal(1, typeC6.TypeArguments().Length); Assert.Same(localC6Params[0], typeC6.TypeArguments()[0]); Assert.Same(((RetargetingNamedTypeSymbol)type3).UnderlyingNamedType, asm3.GlobalNamespace.GetTypeMembers("C3").Single()); Assert.Equal(1, ((RetargetingNamedTypeSymbol)type3).Locations.Length); Assert.Equal(TypeKind.Class, type3.TypeKind); Assert.Equal(TypeKind.Interface, asm5[1].GlobalNamespace.GetTypeMembers("I1").Single().TypeKind); var localC6_T = localC6Params[0]; var foo3TypeParam = foo3TypeParams[0]; Assert.Equal(0, localC6_T.ConstraintTypes().Length); Assert.Equal(1, foo3TypeParam.ConstraintTypes().Length); Assert.Same(type4, foo3TypeParam.ConstraintTypes().Single()); Assert.Same(typeC6, localC6_T.ContainingSymbol); Assert.False(foo3TypeParam.HasConstructorConstraint); Assert.True(localC6_T.HasConstructorConstraint); Assert.False(foo3TypeParam.HasReferenceTypeConstraint); Assert.False(foo3TypeParam.HasValueTypeConstraint); Assert.Equal("TFoo3", foo3TypeParam.Name); Assert.Equal("T", localC6_T.Name); Assert.Equal(0, foo3TypeParam.Ordinal); Assert.Equal(0, localC6_T.Ordinal); Assert.Equal(VarianceKind.None, foo3TypeParam.Variance); Assert.Same(((RetargetingTypeParameterSymbol)localC6_T).UnderlyingTypeParameter, asm3.GlobalNamespace.GetTypeMembers("C6").Single().TypeParameters[0]); var ns1 = asm5[1].GlobalNamespace.GetMembers("ns1").OfType<NamespaceSymbol>().Single(); var ns2 = ns1.GetMembers("ns2").OfType<NamespaceSymbol>().Single(); Assert.Equal("ns1.ns2", ns2.ToTestDisplayString()); Assert.Equal(2, ns1.GetMembers().Length); Assert.Equal(1, ns1.GetTypeMembers().Length); Assert.Same(ns1.GetTypeMembers("C304").Single(), ns1.GetTypeMembers("C304", 0).Single()); Assert.Same(asm5[1].Modules[0], asm5[1].Modules[0].GlobalNamespace.ContainingSymbol); Assert.Same(asm5[1].Modules[0].GlobalNamespace, ns1.ContainingSymbol); Assert.Same(asm5[1].Modules[0], ns1.Extent.Module); Assert.Equal(1, ns1.ConstituentNamespaces.Length); Assert.Same(ns1, ns1.ConstituentNamespaces[0]); Assert.False(ns1.IsGlobalNamespace); Assert.True(asm5[1].Modules[0].GlobalNamespace.IsGlobalNamespace); Assert.Same(asm3.Modules[0].GlobalNamespace, ((RetargetingNamespaceSymbol)asm5[1].Modules[0].GlobalNamespace).UnderlyingNamespace); Assert.Same(asm3.Modules[0].GlobalNamespace.GetMembers("ns1").Single(), ((RetargetingNamespaceSymbol)ns1).UnderlyingNamespace); var module3 = (RetargetingModuleSymbol)asm5[1].Modules[0]; Assert.Equal("C3.dll", module3.ToTestDisplayString()); Assert.Equal("C3.dll", module3.Name); Assert.Same(asm5[1], module3.ContainingSymbol); Assert.Same(asm5[1], module3.ContainingAssembly); Assert.Null(module3.ContainingType); var retval5 = type3.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("C8<C4>", retval5.ToTestDisplayString()); var typeC5 = c5.Assembly.GlobalNamespace.GetTypeMembers("C5").Single(); Assert.Same(asm5[1], typeC5.BaseType().ContainingAssembly); Assert.Equal("ns1.C304.C305", typeC5.BaseType().ToTestDisplayString()); Assert.NotEqual(SymbolKind.ErrorType, typeC5.Kind); } [Fact] public void MultiTargeting5() { var c1_Name = new AssemblyIdentity("c1"); var text = @" class Module1 { Class4 M1() {} Class4.Class4_1 M2() {} Class4 M3() {} } "; var c1 = CreateEmptyCompilation(text, new MetadataReference[] { MscorlibRef, TestReferences.SymbolsTests.V1.MTTestLib1.dll, TestReferences.SymbolsTests.V1.MTTestModule2.netmodule }); var c2_Name = new AssemblyIdentity("MTTestLib2"); var c2 = CreateCompilation(c2_Name, null, new MetadataReference[] { Net451.mscorlib, TestReferences.SymbolsTests.V2.MTTestLib1.dll, new CSharpCompilationReference(c1) }); SourceAssemblySymbol c1AsmSource = (SourceAssemblySymbol)c1.Assembly; PEAssemblySymbol Lib1_V1 = (PEAssemblySymbol)c1AsmSource.Modules[0].GetReferencedAssemblySymbols()[1]; PEModuleSymbol module1 = (PEModuleSymbol)c1AsmSource.Modules[1]; Assert.Equal(LocationKind.MetadataFile, ((MetadataLocation)Lib1_V1.Locations[0]).Kind); SourceAssemblySymbol c2AsmSource = (SourceAssemblySymbol)c2.Assembly; RetargetingAssemblySymbol c1AsmRef = (RetargetingAssemblySymbol)c2AsmSource.Modules[0].GetReferencedAssemblySymbols()[2]; PEAssemblySymbol Lib1_V2 = (PEAssemblySymbol)c2AsmSource.Modules[0].GetReferencedAssemblySymbols()[1]; PEModuleSymbol module2 = (PEModuleSymbol)c1AsmRef.Modules[1]; Assert.Equal(1, Lib1_V1.Identity.Version.Major); Assert.Equal(2, Lib1_V2.Identity.Version.Major); Assert.NotEqual(module1, module2); Assert.Same(module1.Module, module2.Module); NamedTypeSymbol classModule1 = c1AsmRef.Modules[0].GlobalNamespace.GetTypeMembers("Module1").Single(); MethodSymbol m1 = classModule1.GetMembers("M1").OfType<MethodSymbol>().Single(); MethodSymbol m2 = classModule1.GetMembers("M2").OfType<MethodSymbol>().Single(); MethodSymbol m3 = classModule1.GetMembers("M3").OfType<MethodSymbol>().Single(); Assert.Same(module2, m1.ReturnType.ContainingModule); Assert.Same(module2, m2.ReturnType.ContainingModule); Assert.Same(module2, m3.ReturnType.ContainingModule); } // Very simplistic test if a compilation has a single type with the given full name. Does NOT handle generics. private bool HasSingleTypeOfKind(CSharpCompilation c, TypeKind kind, string fullName) { string[] names = fullName.Split('.'); NamespaceOrTypeSymbol current = c.GlobalNamespace; foreach (string name in names) { var matchingSym = current.GetMembers(name); if (matchingSym.Length != 1) { return false; } current = (NamespaceOrTypeSymbol)matchingSym.First(); } return current is TypeSymbol && ((TypeSymbol)current).TypeKind == kind; } [Fact] public void AddRemoveReferences() { var mscorlibRef = Net451.mscorlib; var systemCoreRef = Net451.SystemCore; var systemRef = Net451.System; CSharpCompilation c = CSharpCompilation.Create("Test"); Assert.False(HasSingleTypeOfKind(c, TypeKind.Struct, "System.Int32")); c = c.AddReferences(mscorlibRef); Assert.True(HasSingleTypeOfKind(c, TypeKind.Struct, "System.Int32")); Assert.False(HasSingleTypeOfKind(c, TypeKind.Class, "System.Linq.Enumerable")); c = c.AddReferences(systemCoreRef); Assert.True(HasSingleTypeOfKind(c, TypeKind.Class, "System.Linq.Enumerable")); Assert.False(HasSingleTypeOfKind(c, TypeKind.Class, "System.Uri")); c = c.ReplaceReference(systemCoreRef, systemRef); Assert.False(HasSingleTypeOfKind(c, TypeKind.Class, "System.Linq.Enumerable")); Assert.True(HasSingleTypeOfKind(c, TypeKind.Class, "System.Uri")); c = c.RemoveReferences(systemRef); Assert.False(HasSingleTypeOfKind(c, TypeKind.Class, "System.Uri")); Assert.True(HasSingleTypeOfKind(c, TypeKind.Struct, "System.Int32")); c = c.RemoveReferences(mscorlibRef); Assert.False(HasSingleTypeOfKind(c, TypeKind.Struct, "System.Int32")); } private sealed class Resolver : MetadataReferenceResolver { private readonly string _data, _core, _system; public Resolver(string data, string core, string system) { _data = data; _core = core; _system = system; } public override ImmutableArray<PortableExecutableReference> ResolveReference(string reference, string baseFilePath, MetadataReferenceProperties properties) { switch (reference) { case "System.Data": return ImmutableArray.Create(MetadataReference.CreateFromFile(_data)); case "System.Core": return ImmutableArray.Create(MetadataReference.CreateFromFile(_core)); case "System": return ImmutableArray.Create(MetadataReference.CreateFromFile(_system)); default: if (File.Exists(reference)) { return ImmutableArray.Create(MetadataReference.CreateFromFile(reference)); } return ImmutableArray<PortableExecutableReference>.Empty; } } public override bool Equals(object other) => true; public override int GetHashCode() => 1; } [Fact] public void CompilationWithReferenceDirectives() { var data = Temp.CreateFile().WriteAllBytes(ResourcesNet451.SystemData).Path; var core = Temp.CreateFile().WriteAllBytes(ResourcesNet451.SystemCore).Path; var xml = Temp.CreateFile().WriteAllBytes(ResourcesNet451.SystemXml).Path; var system = Temp.CreateFile().WriteAllBytes(ResourcesNet451.System).Path; var trees = new[] { SyntaxFactory.ParseSyntaxTree($@" #r ""System.Data"" #r ""{xml}"" #r ""{core}"" ", options: TestOptions.Script), SyntaxFactory.ParseSyntaxTree(@" #r ""System"" ", options: TestOptions.Script), SyntaxFactory.ParseSyntaxTree(@" new System.Data.DataSet(); System.Linq.Expressions.Expression.Constant(123); System.Diagnostics.Process.GetCurrentProcess(); ", options: TestOptions.Script) }; var compilation = CreateCompilationWithMscorlib45( trees, options: TestOptions.ReleaseDll.WithMetadataReferenceResolver(new Resolver(data, core, system))); compilation.VerifyDiagnostics(); var boundRefs = compilation.Assembly.BoundReferences(); AssertEx.Equal(new[] { "System.Data", "System.Xml", "System.Core", "System", "mscorlib" }, boundRefs.Select(r => r.Name)); } [Fact] public void CompilationWithReferenceDirectives_Errors() { var data = Temp.CreateFile().WriteAllBytes(ResourcesNet451.SystemData).Path; var core = Temp.CreateFile().WriteAllBytes(ResourcesNet451.SystemCore).Path; var system = Temp.CreateFile().WriteAllBytes(ResourcesNet451.System).Path; var trees = new[] { SyntaxFactory.ParseSyntaxTree(@" #r System #r ""~!@#$%^&*():\?/"" #r ""non-existing-reference"" ", options: TestOptions.Script), SyntaxFactory.ParseSyntaxTree(@" #r ""System.Core"" ", TestOptions.Regular) }; var compilation = CreateCompilationWithMscorlib45( trees, options: TestOptions.ReleaseDll.WithMetadataReferenceResolver(new Resolver(data, core, system))); compilation.VerifyDiagnostics( // (3,1): error CS0006: Metadata file '~!@#$%^&*():\?/' could not be found Diagnostic(ErrorCode.ERR_NoMetadataFile, @"#r ""~!@#$%^&*():\?/""").WithArguments(@"~!@#$%^&*():\?/"), // (4,1): error CS0006: Metadata file 'non-existing-reference' could not be found Diagnostic(ErrorCode.ERR_NoMetadataFile, @"#r ""non-existing-reference""").WithArguments("non-existing-reference"), // (2,4): error CS7010: Quoted file name expected Diagnostic(ErrorCode.ERR_ExpectedPPFile, "System"), // (2,1): error CS7011: #r is only allowed in scripts Diagnostic(ErrorCode.ERR_ReferenceDirectiveOnlyAllowedInScripts, "r")); } private class DummyReferenceResolver : MetadataReferenceResolver { private readonly string _targetDll; public DummyReferenceResolver(string targetDll) { _targetDll = targetDll; } public override ImmutableArray<PortableExecutableReference> ResolveReference(string reference, string baseFilePath, MetadataReferenceProperties properties) { var path = reference.EndsWith("-resolve", StringComparison.Ordinal) ? _targetDll : reference; return ImmutableArray.Create(MetadataReference.CreateFromFile(path, properties)); } public override bool Equals(object other) => true; public override int GetHashCode() => 1; } [Fact] public void MetadataReferenceProvider() { var csClasses01 = Temp.CreateFile().WriteAllBytes(TestResources.MetadataTests.InterfaceAndClass.CSClasses01).Path; var csInterfaces01 = Temp.CreateFile().WriteAllBytes(TestResources.MetadataTests.InterfaceAndClass.CSInterfaces01).Path; var source = @" #r """ + "!@#$%^/&*-resolve" + @""" #r """ + csInterfaces01 + @""" class C : Metadata.ICSPropImpl { }"; var compilation = CreateCompilationWithMscorlib45( new[] { Parse(source, options: TestOptions.Script) }, options: TestOptions.ReleaseDll.WithMetadataReferenceResolver(new DummyReferenceResolver(csClasses01))); compilation.VerifyDiagnostics(); } [Fact] public void CompilationWithReferenceDirective_NoResolver() { var compilation = CreateCompilationWithMscorlib45( new[] { SyntaxFactory.ParseSyntaxTree(@"#r ""bar""", TestOptions.Script, "a.csx", Encoding.UTF8) }, options: TestOptions.ReleaseDll.WithMetadataReferenceResolver(null)); compilation.VerifyDiagnostics( // a.csx(1,1): error CS7099: Metadata references not supported. // #r "bar" Diagnostic(ErrorCode.ERR_MetadataReferencesNotSupported, @"#r ""bar""")); } [Fact] public void GlobalUsings1() { var trees = new[] { SyntaxFactory.ParseSyntaxTree(@" WriteLine(1); Console.WriteLine(2); ", options: TestOptions.Script), SyntaxFactory.ParseSyntaxTree(@" class C { void Foo() { Console.WriteLine(3); } } ", TestOptions.Regular) }; var compilation = CreateCompilationWithMscorlib45( trees, options: TestOptions.ReleaseDll.WithUsings(ImmutableArray.Create("System.Console", "System"))); var diagnostics = compilation.GetDiagnostics().ToArray(); // global usings are only visible in script code: DiagnosticsUtils.VerifyErrorCodes(diagnostics, // (4,18): error CS0103: The name 'Console' does not exist in the current context new ErrorDescription() { Code = (int)ErrorCode.ERR_NameNotInContext, Line = 4, Column = 18 }); } [Fact] public void GlobalUsings_Errors() { var trees = new[] { SyntaxFactory.ParseSyntaxTree(@" WriteLine(1); Console.WriteLine(2); ", options: TestOptions.Script) }; var compilation = CreateCompilationWithMscorlib45( trees, options: TestOptions.ReleaseDll.WithUsings("System.Console!", "Blah")); compilation.VerifyDiagnostics( // error CS0234: The type or namespace name 'Console!' does not exist in the namespace 'System' (are you missing an assembly reference?) Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS).WithArguments("Console!", "System"), // error CS0246: The type or namespace name 'Blah' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound).WithArguments("Blah"), // (2,1): error CS0103: The name 'WriteLine' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "WriteLine").WithArguments("WriteLine"), // (3,1): error CS0103: The name 'Console' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "Console").WithArguments("Console")); } [Fact] public void ReferenceToAssemblyWithSpecialCharactersInName() { var r = TestReferences.SymbolsTests.Metadata.InvalidCharactersInAssemblyName; var st = SyntaxFactory.ParseSyntaxTree("class C { static void Main() { new lib.Class1(); } }"); var compilation = CSharpCompilation.Create("foo", references: new[] { MscorlibRef, r }, syntaxTrees: new[] { st }); var diags = compilation.GetDiagnostics().ToArray(); Assert.Equal(0, diags.Length); using (var stream = new MemoryStream()) { compilation.Emit(stream); } } [Fact] public void SyntaxTreeOrderConstruct() { var tree1 = CreateSyntaxTree("A"); var tree2 = CreateSyntaxTree("B"); SyntaxTree[] treeOrder1 = new[] { tree1, tree2 }; var compilation1 = CSharpCompilation.Create("Compilation1", syntaxTrees: treeOrder1); CheckCompilationSyntaxTrees(compilation1, treeOrder1); SyntaxTree[] treeOrder2 = new[] { tree2, tree1 }; var compilation2 = CSharpCompilation.Create("Compilation2", syntaxTrees: treeOrder2); CheckCompilationSyntaxTrees(compilation2, treeOrder2); } [Fact] public void SyntaxTreeOrderAdd() { var tree1 = CreateSyntaxTree("A"); var tree2 = CreateSyntaxTree("B"); var tree3 = CreateSyntaxTree("C"); var tree4 = CreateSyntaxTree("D"); SyntaxTree[] treeList1 = new[] { tree1, tree2 }; var compilation1 = CSharpCompilation.Create("Compilation1", syntaxTrees: treeList1); CheckCompilationSyntaxTrees(compilation1, treeList1); SyntaxTree[] treeList2 = new[] { tree3, tree4 }; var compilation2 = compilation1.AddSyntaxTrees(treeList2); CheckCompilationSyntaxTrees(compilation1, treeList1); //compilation1 untouched CheckCompilationSyntaxTrees(compilation2, treeList1.Concat(treeList2).ToArray()); SyntaxTree[] treeList3 = new[] { tree4, tree3 }; var compilation3 = CSharpCompilation.Create("Compilation3", syntaxTrees: treeList3); CheckCompilationSyntaxTrees(compilation3, treeList3); SyntaxTree[] treeList4 = new[] { tree2, tree1 }; var compilation4 = compilation3.AddSyntaxTrees(treeList4); CheckCompilationSyntaxTrees(compilation3, treeList3); //compilation3 untouched CheckCompilationSyntaxTrees(compilation4, treeList3.Concat(treeList4).ToArray()); } [Fact] public void SyntaxTreeOrderRemove() { var tree1 = CreateSyntaxTree("A"); var tree2 = CreateSyntaxTree("B"); var tree3 = CreateSyntaxTree("C"); var tree4 = CreateSyntaxTree("D"); SyntaxTree[] treeList1 = new[] { tree1, tree2, tree3, tree4 }; var compilation1 = CSharpCompilation.Create("Compilation1", syntaxTrees: treeList1); CheckCompilationSyntaxTrees(compilation1, treeList1); SyntaxTree[] treeList2 = new[] { tree3, tree1 }; var compilation2 = compilation1.RemoveSyntaxTrees(treeList2); CheckCompilationSyntaxTrees(compilation1, treeList1); //compilation1 untouched CheckCompilationSyntaxTrees(compilation2, tree2, tree4); SyntaxTree[] treeList3 = new[] { tree4, tree3, tree2, tree1 }; var compilation3 = CSharpCompilation.Create("Compilation3", syntaxTrees: treeList3); CheckCompilationSyntaxTrees(compilation3, treeList3); SyntaxTree[] treeList4 = new[] { tree3, tree1 }; var compilation4 = compilation3.RemoveSyntaxTrees(treeList4); CheckCompilationSyntaxTrees(compilation3, treeList3); //compilation3 untouched CheckCompilationSyntaxTrees(compilation4, tree4, tree2); } [Fact] public void SyntaxTreeOrderReplace() { var tree1 = CreateSyntaxTree("A"); var tree2 = CreateSyntaxTree("B"); var tree3 = CreateSyntaxTree("C"); SyntaxTree[] treeList1 = new[] { tree1, tree2 }; var compilation1 = CSharpCompilation.Create("Compilation1", syntaxTrees: treeList1); CheckCompilationSyntaxTrees(compilation1, treeList1); var compilation2 = compilation1.ReplaceSyntaxTree(tree1, tree3); CheckCompilationSyntaxTrees(compilation1, treeList1); //compilation1 untouched CheckCompilationSyntaxTrees(compilation2, tree3, tree2); SyntaxTree[] treeList3 = new[] { tree2, tree1 }; var compilation3 = CSharpCompilation.Create("Compilation3", syntaxTrees: treeList3); CheckCompilationSyntaxTrees(compilation3, treeList3); var compilation4 = compilation3.ReplaceSyntaxTree(tree1, tree3); CheckCompilationSyntaxTrees(compilation3, treeList3); //compilation3 untouched CheckCompilationSyntaxTrees(compilation4, tree2, tree3); } [WorkItem(578706, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578706")] [Fact] public void DeclaringCompilationOfAddedModule() { var source1 = "public class C1 { }"; var source2 = "public class C2 { }"; var lib1 = CreateCompilation(source1, assemblyName: "Lib1", options: TestOptions.ReleaseModule); var ref1 = lib1.EmitToImageReference(); // NOTE: can't use a compilation reference for a module. var lib2 = CreateCompilation(source2, new[] { ref1 }, assemblyName: "Lib2"); lib2.VerifyDiagnostics(); var sourceAssembly = lib2.Assembly; var sourceModule = sourceAssembly.Modules[0]; var sourceType = sourceModule.GlobalNamespace.GetMember<NamedTypeSymbol>("C2"); Assert.IsType<SourceAssemblySymbol>(sourceAssembly); Assert.Equal(lib2, sourceAssembly.DeclaringCompilation); Assert.IsType<SourceModuleSymbol>(sourceModule); Assert.Equal(lib2, sourceModule.DeclaringCompilation); Assert.IsType<SourceNamedTypeSymbol>(sourceType); Assert.Equal(lib2, sourceType.DeclaringCompilation); var addedModule = sourceAssembly.Modules[1]; var addedModuleAssembly = addedModule.ContainingAssembly; var addedModuleType = addedModule.GlobalNamespace.GetMember<NamedTypeSymbol>("C1"); Assert.IsType<SourceAssemblySymbol>(addedModuleAssembly); Assert.Equal(lib2, addedModuleAssembly.DeclaringCompilation); //NB: not lib1, not null Assert.IsType<PEModuleSymbol>(addedModule); Assert.Null(addedModule.DeclaringCompilation); Assert.IsAssignableFrom<PENamedTypeSymbol>(addedModuleType); Assert.Null(addedModuleType.DeclaringCompilation); } } }
// Licensed to the .NET Foundation under one or more 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.IO; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class CompilationCreationTests : CSharpTestBase { #region Helpers private static SyntaxTree CreateSyntaxTree(string className) { var text = string.Format("public partial class {0} {{ }}", className); var path = string.Format("{0}.cs", className); return SyntaxFactory.ParseSyntaxTree(text, path: path); } private static void CheckCompilationSyntaxTrees(CSharpCompilation compilation, params SyntaxTree[] expectedSyntaxTrees) { ImmutableArray<SyntaxTree> actualSyntaxTrees = compilation.SyntaxTrees; int numTrees = expectedSyntaxTrees.Length; Assert.Equal(numTrees, actualSyntaxTrees.Length); for (int i = 0; i < numTrees; i++) { Assert.Equal(expectedSyntaxTrees[i], actualSyntaxTrees[i]); } for (int i = 0; i < numTrees; i++) { for (int j = 0; j < numTrees; j++) { Assert.Equal(Math.Sign(compilation.CompareSyntaxTreeOrdering(expectedSyntaxTrees[i], expectedSyntaxTrees[j])), Math.Sign(i.CompareTo(j))); } } var types = expectedSyntaxTrees.Select(tree => compilation.GetSemanticModel(tree).GetDeclaredSymbol(tree.GetCompilationUnitRoot().Members.Single())).ToArray(); for (int i = 0; i < numTrees; i++) { for (int j = 0; j < numTrees; j++) { Assert.Equal(Math.Sign(compilation.CompareSourceLocations(types[i].Locations[0], types[j].Locations[0])), Math.Sign(i.CompareTo(j))); } } } #endregion [Fact] public void CorLibTypes() { var mdTestLib1 = TestReferences.SymbolsTests.MDTestLib1; var c1 = CSharpCompilation.Create("Test", references: new MetadataReference[] { MscorlibRef_v4_0_30316_17626, mdTestLib1 }); TypeSymbol c107 = c1.GlobalNamespace.GetTypeMembers("C107").Single(); Assert.Equal(SpecialType.None, c107.SpecialType); for (int i = 1; i <= (int)SpecialType.Count; i++) { NamedTypeSymbol type = c1.GetSpecialType((SpecialType)i); if (i == (int)SpecialType.System_Runtime_CompilerServices_RuntimeFeature || i == (int)SpecialType.System_Runtime_CompilerServices_PreserveBaseOverridesAttribute) { Assert.True(type.IsErrorType()); // Not available } else { Assert.False(type.IsErrorType()); } Assert.Equal((SpecialType)i, type.SpecialType); } Assert.Equal(SpecialType.None, c107.SpecialType); var arrayOfc107 = ArrayTypeSymbol.CreateCSharpArray(c1.Assembly, TypeWithAnnotations.Create(c107)); Assert.Equal(SpecialType.None, arrayOfc107.SpecialType); var c2 = CSharpCompilation.Create("Test", references: new[] { mdTestLib1 }); Assert.Equal(SpecialType.None, c2.GlobalNamespace.GetTypeMembers("C107").Single().SpecialType); } [Fact] public void CyclicReference() { var mscorlibRef = Net451.mscorlib; var cyclic2Ref = TestReferences.SymbolsTests.Cyclic.Cyclic2.dll; var tc1 = CSharpCompilation.Create("Cyclic1", references: new[] { mscorlibRef, cyclic2Ref }); Assert.NotNull(tc1.Assembly); // force creation of SourceAssemblySymbol var cyclic1Asm = (SourceAssemblySymbol)tc1.Assembly; var cyclic1Mod = (SourceModuleSymbol)cyclic1Asm.Modules[0]; var cyclic2Asm = (PEAssemblySymbol)tc1.GetReferencedAssemblySymbol(cyclic2Ref); var cyclic2Mod = (PEModuleSymbol)cyclic2Asm.Modules[0]; Assert.Same(cyclic2Mod.GetReferencedAssemblySymbols()[1], cyclic1Asm); Assert.Same(cyclic1Mod.GetReferencedAssemblySymbols()[1], cyclic2Asm); } [Fact] public void MultiTargeting1() { var varV1MTTestLib2Ref = TestReferences.SymbolsTests.V1.MTTestLib2.dll; var asm1 = MetadataTestHelpers.GetSymbolsForReferences(mrefs: new[] { Net451.mscorlib, varV1MTTestLib2Ref }); Assert.Equal("mscorlib", asm1[0].Identity.Name); Assert.Equal(0, asm1[0].BoundReferences().Length); Assert.Equal("MTTestLib2", asm1[1].Identity.Name); Assert.Equal(1, (from a in asm1[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm1[1].BoundReferences() where object.ReferenceEquals(a, asm1[0]) select a).Count()); Assert.Equal(SymbolKind.ErrorType, asm1[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType.Kind); var asm2 = MetadataTestHelpers.GetSymbolsForReferences(new[] { Net451.mscorlib, varV1MTTestLib2Ref, TestReferences.SymbolsTests.V1.MTTestLib1.dll }); Assert.Same(asm2[0], asm1[0]); Assert.Equal("MTTestLib2", asm2[1].Identity.Name); Assert.NotSame(asm2[1], asm1[1]); Assert.Same(((PEAssemblySymbol)asm2[1]).Assembly, ((PEAssemblySymbol)asm1[1]).Assembly); Assert.Equal(2, (from a in asm2[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); Assert.Equal(1, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[2]) select a).Count()); var retval1 = asm2[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval1.Kind); Assert.Same(retval1, asm2[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm2[2].Identity.Name); Assert.Equal(1, asm2[2].Identity.Version.Major); Assert.Equal(1, (from a in asm2[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[2].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); var varV2MTTestLib3Ref = TestReferences.SymbolsTests.V2.MTTestLib3.dll; var asm3 = MetadataTestHelpers.GetSymbolsForReferences(new[] { Net451.mscorlib, varV1MTTestLib2Ref, TestReferences.SymbolsTests.V2.MTTestLib1.dll, varV2MTTestLib3Ref }); Assert.Same(asm3[0], asm1[0]); Assert.Equal("MTTestLib2", asm3[1].Identity.Name); Assert.NotSame(asm3[1], asm1[1]); Assert.NotSame(asm3[1], asm2[1]); Assert.Same(((PEAssemblySymbol)asm3[1]).Assembly, ((PEAssemblySymbol)asm1[1]).Assembly); Assert.Equal(2, (from a in asm3[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(1, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); var retval2 = asm3[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval2.Kind); Assert.Same(retval2, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm3[2].Identity.Name); Assert.NotSame(asm3[2], asm2[2]); Assert.NotSame(((PEAssemblySymbol)asm3[2]).Assembly, ((PEAssemblySymbol)asm2[2]).Assembly); Assert.Equal(2, asm3[2].Identity.Version.Major); Assert.Equal(1, (from a in asm3[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[2].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal("MTTestLib3", asm3[3].Identity.Name); Assert.Equal(3, (from a in asm3[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[1]) select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); var type1 = asm3[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); var retval3 = type1.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval3.Kind); Assert.Same(retval3, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); var retval4 = type1.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval4.Kind); Assert.Same(retval4, asm3[2].GlobalNamespace.GetMembers("Class2").Single()); var retval5 = type1.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval5.Kind); Assert.Same(retval5, asm3[1].GlobalNamespace.GetMembers("Class4").Single()); var varV3MTTestLib4Ref = TestReferences.SymbolsTests.V3.MTTestLib4.dll; var asm4 = MetadataTestHelpers.GetSymbolsForReferences(new MetadataReference[] { Net451.mscorlib, varV1MTTestLib2Ref, TestReferences.SymbolsTests.V3.MTTestLib1.dll, varV2MTTestLib3Ref, varV3MTTestLib4Ref }); Assert.Same(asm3[0], asm1[0]); Assert.Equal("MTTestLib2", asm4[1].Identity.Name); Assert.NotSame(asm4[1], asm1[1]); Assert.NotSame(asm4[1], asm2[1]); Assert.NotSame(asm4[1], asm3[1]); Assert.Same(((PEAssemblySymbol)asm4[1]).Assembly, ((PEAssemblySymbol)asm1[1]).Assembly); Assert.Equal(2, (from a in asm4[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); var retval6 = asm4[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval6.Kind); Assert.Same(retval6, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm4[2].Identity.Name); Assert.NotSame(asm4[2], asm2[2]); Assert.NotSame(asm4[2], asm3[2]); Assert.NotSame(((PEAssemblySymbol)asm4[2]).Assembly, ((PEAssemblySymbol)asm2[2]).Assembly); Assert.NotSame(((PEAssemblySymbol)asm4[2]).Assembly, ((PEAssemblySymbol)asm3[2]).Assembly); Assert.Equal(3, asm4[2].Identity.Version.Major); Assert.Equal(1, (from a in asm4[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[2].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal("MTTestLib3", asm4[3].Identity.Name); Assert.NotSame(asm4[3], asm3[3]); Assert.Same(((PEAssemblySymbol)asm4[3]).Assembly, ((PEAssemblySymbol)asm3[3]).Assembly); Assert.Equal(3, (from a in asm4[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); var type2 = asm4[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); var retval7 = type2.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval7.Kind); Assert.Same(retval7, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); var retval8 = type2.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval8.Kind); Assert.Same(retval8, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); var retval9 = type2.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval9.Kind); Assert.Same(retval9, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm4[4].Identity.Name); Assert.Equal(4, (from a in asm4[4].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[3]) select a).Count()); var type3 = asm4[4].GlobalNamespace.GetTypeMembers("Class6"). Single(); var retval10 = type3.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval10.Kind); Assert.Same(retval10, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); var retval11 = type3.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval11.Kind); Assert.Same(retval11, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); var retval12 = type3.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval12.Kind); Assert.Same(retval12, asm4[2].GlobalNamespace.GetMembers("Class3").Single()); var retval13 = type3.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval13.Kind); Assert.Same(retval13, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); var retval14 = type3.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval14.Kind); Assert.Same(retval14, asm4[3].GlobalNamespace.GetMembers("Class5").Single()); var asm5 = MetadataTestHelpers.GetSymbolsForReferences(new[] { Net451.mscorlib, varV2MTTestLib3Ref }); Assert.Same(asm5[0], asm1[0]); Assert.True(asm5[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm3[3])); var asm6 = MetadataTestHelpers.GetSymbolsForReferences(new[] { Net451.mscorlib, varV1MTTestLib2Ref }); Assert.Same(asm6[0], asm1[0]); Assert.Same(asm6[1], asm1[1]); var asm7 = MetadataTestHelpers.GetSymbolsForReferences(new[] { Net451.mscorlib, varV1MTTestLib2Ref, varV2MTTestLib3Ref, varV3MTTestLib4Ref }); Assert.Same(asm7[0], asm1[0]); Assert.Same(asm7[1], asm1[1]); Assert.NotSame(asm7[2], asm3[3]); Assert.NotSame(asm7[2], asm4[3]); Assert.NotSame(asm7[3], asm4[4]); Assert.Equal("MTTestLib3", asm7[2].Identity.Name); Assert.Same(((PEAssemblySymbol)asm7[2]).Assembly, ((PEAssemblySymbol)asm3[3]).Assembly); Assert.Equal(2, (from a in asm7[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(1, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); var type4 = asm7[2].GlobalNamespace.GetTypeMembers("Class5"). Single(); var retval15 = type4.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval15.Kind); var retval16 = type4.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval16.Kind); var retval17 = type4.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval17.Kind); Assert.Same(retval17, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm7[3].Identity.Name); Assert.Same(((PEAssemblySymbol)asm7[3]).Assembly, ((PEAssemblySymbol)asm4[4]).Assembly); Assert.Equal(3, (from a in asm7[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[2]) select a).Count()); var type5 = asm7[3].GlobalNamespace.GetTypeMembers("Class6"). Single(); var retval18 = type5.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval18.Kind); var retval19 = type5.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval19.Kind); var retval20 = type5.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval20.Kind); var retval21 = type5.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval21.Kind); Assert.Same(retval21, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); var retval22 = type5.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval22.Kind); Assert.Same(retval22, asm7[2].GlobalNamespace.GetMembers("Class5").Single()); // This test shows that simple reordering of references doesn't pick different set of assemblies var asm8 = MetadataTestHelpers.GetSymbolsForReferences(new[] { Net451.mscorlib, varV3MTTestLib4Ref, varV1MTTestLib2Ref, varV2MTTestLib3Ref }); Assert.Same(asm8[0], asm1[0]); Assert.Same(asm8[0], asm1[0]); Assert.Same(asm8[2], asm7[1]); Assert.True(asm8[3].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[3])); Assert.Same(asm8[3], asm7[2]); Assert.True(asm8[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[4])); Assert.Same(asm8[1], asm7[3]); var asm9 = MetadataTestHelpers.GetSymbolsForReferences(new[] { Net451.mscorlib, varV3MTTestLib4Ref }); Assert.Same(asm9[0], asm1[0]); Assert.True(asm9[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[4])); var asm10 = MetadataTestHelpers.GetSymbolsForReferences(new[] { Net451.mscorlib, varV1MTTestLib2Ref, TestReferences.SymbolsTests.V3.MTTestLib1.dll, varV2MTTestLib3Ref, varV3MTTestLib4Ref }); Assert.Same(asm10[0], asm1[0]); Assert.Same(asm10[1], asm4[1]); Assert.Same(asm10[2], asm4[2]); Assert.Same(asm10[3], asm4[3]); Assert.Same(asm10[4], asm4[4]); // Run the same tests again to make sure we didn't corrupt prior state by loading additional assemblies Assert.Equal("MTTestLib2", asm1[1].Identity.Name); Assert.Equal(1, (from a in asm1[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm1[1].BoundReferences() where ReferenceEquals(a, asm1[0]) select a).Count()); Assert.Equal(SymbolKind.ErrorType, asm1[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType.Kind); Assert.Same(asm2[0], asm1[0]); Assert.Equal("MTTestLib2", asm2[1].Identity.Name); Assert.NotSame(asm2[1], asm1[1]); Assert.Same(((PEAssemblySymbol)asm2[1]).Assembly, ((PEAssemblySymbol)asm1[1]).Assembly); Assert.Equal(2, (from a in asm2[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[1].BoundReferences() where ReferenceEquals(a, asm2[0]) select a).Count()); Assert.Equal(1, (from a in asm2[1].BoundReferences() where ReferenceEquals(a, asm2[2]) select a).Count()); retval1 = asm2[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval1.Kind); Assert.Same(retval1, asm2[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm2[2].Identity.Name); Assert.Equal(1, asm2[2].Identity.Version.Major); Assert.Equal(1, (from a in asm2[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[2].BoundReferences() where ReferenceEquals(a, asm2[0]) select a).Count()); Assert.Same(asm3[0], asm1[0]); Assert.Equal("MTTestLib2", asm3[1].Identity.Name); Assert.NotSame(asm3[1], asm1[1]); Assert.NotSame(asm3[1], asm2[1]); Assert.Same(((PEAssemblySymbol)asm3[1]).Assembly, ((PEAssemblySymbol)asm1[1]).Assembly); Assert.Equal(2, (from a in asm3[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[1].BoundReferences() where ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(1, (from a in asm3[1].BoundReferences() where ReferenceEquals(a, asm3[2]) select a).Count()); retval2 = asm3[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval2.Kind); Assert.Same(retval2, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm3[2].Identity.Name); Assert.NotSame(asm3[2], asm2[2]); Assert.NotSame(((PEAssemblySymbol)asm3[2]).Assembly, ((PEAssemblySymbol)asm2[2]).Assembly); Assert.Equal(2, asm3[2].Identity.Version.Major); Assert.Equal(1, (from a in asm3[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[2].BoundReferences() where ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal("MTTestLib3", asm3[3].Identity.Name); Assert.Equal(3, (from a in asm3[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where ReferenceEquals(a, asm3[1]) select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where ReferenceEquals(a, asm3[2]) select a).Count()); type1 = asm3[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); retval3 = type1.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval3.Kind); Assert.Same(retval3, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); retval4 = type1.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval4.Kind); Assert.Same(retval4, asm3[2].GlobalNamespace.GetMembers("Class2").Single()); retval5 = type1.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval5.Kind); Assert.Same(retval5, asm3[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Same(asm3[0], asm1[0]); Assert.Equal("MTTestLib2", asm4[1].Identity.Name); Assert.NotSame(asm4[1], asm1[1]); Assert.NotSame(asm4[1], asm2[1]); Assert.NotSame(asm4[1], asm3[1]); Assert.Same(((PEAssemblySymbol)asm4[1]).Assembly, ((PEAssemblySymbol)asm1[1]).Assembly); Assert.Equal(2, (from a in asm4[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[1].BoundReferences() where ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[1].BoundReferences() where ReferenceEquals(a, asm4[2]) select a).Count()); retval6 = asm4[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval6.Kind); Assert.Same(retval6, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm4[2].Identity.Name); Assert.NotSame(asm4[2], asm2[2]); Assert.NotSame(asm4[2], asm3[2]); Assert.NotSame(((PEAssemblySymbol)asm4[2]).Assembly, ((PEAssemblySymbol)asm2[2]).Assembly); Assert.NotSame(((PEAssemblySymbol)asm4[2]).Assembly, ((PEAssemblySymbol)asm3[2]).Assembly); Assert.Equal(3, asm4[2].Identity.Version.Major); Assert.Equal(1, (from a in asm4[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[2].BoundReferences() where ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal("MTTestLib3", asm4[3].Identity.Name); Assert.NotSame(asm4[3], asm3[3]); Assert.Same(((PEAssemblySymbol)asm4[3]).Assembly, ((PEAssemblySymbol)asm3[3]).Assembly); Assert.Equal(3, (from a in asm4[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where ReferenceEquals(a, asm4[2]) select a).Count()); type2 = asm4[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); retval7 = type2.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval7.Kind); Assert.Same(retval7, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); retval8 = type2.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval8.Kind); Assert.Same(retval8, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); retval9 = type2.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval9.Kind); Assert.Same(retval9, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm4[4].Identity.Name); Assert.Equal(4, (from a in asm4[4].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where ReferenceEquals(a, asm4[2]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where ReferenceEquals(a, asm4[3]) select a).Count()); type3 = asm4[4].GlobalNamespace.GetTypeMembers("Class6"). Single(); retval10 = type3.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval10.Kind); Assert.Same(retval10, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); retval11 = type3.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval11.Kind); Assert.Same(retval11, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); retval12 = type3.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval12.Kind); Assert.Same(retval12, asm4[2].GlobalNamespace.GetMembers("Class3").Single()); retval13 = type3.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval13.Kind); Assert.Same(retval13, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); retval14 = type3.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval14.Kind); Assert.Same(retval14, asm4[3].GlobalNamespace.GetMembers("Class5").Single()); Assert.Same(asm7[0], asm1[0]); Assert.Same(asm7[1], asm1[1]); Assert.NotSame(asm7[2], asm3[3]); Assert.NotSame(asm7[2], asm4[3]); Assert.NotSame(asm7[3], asm4[4]); Assert.Equal("MTTestLib3", asm7[2].Identity.Name); Assert.Same(((PEAssemblySymbol)asm7[2]).Assembly, ((PEAssemblySymbol)asm3[3]).Assembly); Assert.Equal(2, (from a in asm7[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm7[2].BoundReferences() where ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(1, (from a in asm7[2].BoundReferences() where ReferenceEquals(a, asm7[1]) select a).Count()); type4 = asm7[2].GlobalNamespace.GetTypeMembers("Class5"). Single(); retval15 = type4.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval15.Kind); retval16 = type4.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval16.Kind); retval17 = type4.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval17.Kind); Assert.Same(retval17, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm7[3].Identity.Name); Assert.Same(((PEAssemblySymbol)asm7[3]).Assembly, ((PEAssemblySymbol)asm4[4]).Assembly); Assert.Equal(3, (from a in asm7[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where ReferenceEquals(a, asm7[1]) select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where ReferenceEquals(a, asm7[2]) select a).Count()); type5 = asm7[3].GlobalNamespace.GetTypeMembers("Class6"). Single(); retval18 = type5.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval18.Kind); retval19 = type5.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval19.Kind); retval20 = type5.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal(SymbolKind.ErrorType, retval20.Kind); retval21 = type5.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval21.Kind); Assert.Same(retval21, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); retval22 = type5.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval22.Kind); Assert.Same(retval22, asm7[2].GlobalNamespace.GetMembers("Class5").Single()); } [Fact] public void MultiTargeting2() { var varMTTestLib1_V1_Name = new AssemblyIdentity("MTTestLib1", new Version("1.0.0.0")); var varC_MTTestLib1_V1 = CreateCompilation(varMTTestLib1_V1_Name, new string[] { // AssemblyPaths.SymbolsTests.V1.MTTestModule1.netmodule @" public class Class1 { } " }, new[] { Net451.mscorlib }); var asm_MTTestLib1_V1 = varC_MTTestLib1_V1.SourceAssembly().BoundReferences(); var varMTTestLib2_Name = new AssemblyIdentity("MTTestLib2"); var varC_MTTestLib2 = CreateCompilation(varMTTestLib2_Name, new string[] { // AssemblyPaths.SymbolsTests.V1.MTTestModule2.netmodule @" public class Class4 { Class1 Foo() { return null; } public Class1 Bar; } " }, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib1_V1.ToMetadataReference() }); var asm_MTTestLib2 = varC_MTTestLib2.SourceAssembly().BoundReferences(); Assert.Same(asm_MTTestLib2[0], asm_MTTestLib1_V1[0]); Assert.Same(asm_MTTestLib2[1], varC_MTTestLib1_V1.SourceAssembly()); var c2 = CreateCompilation(new AssemblyIdentity("c2"), null, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib2.ToMetadataReference(), varC_MTTestLib1_V1.ToMetadataReference() }); var asm2 = c2.SourceAssembly().BoundReferences(); Assert.Same(asm2[0], asm_MTTestLib1_V1[0]); Assert.Same(asm2[1], varC_MTTestLib2.SourceAssembly()); Assert.Same(asm2[2], varC_MTTestLib1_V1.SourceAssembly()); Assert.Equal("MTTestLib2", asm2[1].Identity.Name); Assert.Equal(2, (from a in asm2[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); Assert.Equal(1, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[2]) select a).Count()); var retval1 = asm2[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval1.Kind); Assert.Same(retval1, asm2[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm2[2].Identity.Name); Assert.Equal(1, asm2[2].Identity.Version.Major); Assert.Equal(1, (from a in asm2[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[2].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); var varMTTestLib1_V2_Name = new AssemblyIdentity("MTTestLib1", new Version("2.0.0.0")); var varC_MTTestLib1_V2 = CreateCompilation(varMTTestLib1_V2_Name, new string[] { // AssemblyPaths.SymbolsTests.V2.MTTestModule1.netmodule @" public class Class1 { } public class Class2 { } " }, new MetadataReference[] { Net451.mscorlib }); var asm_MTTestLib1_V2 = varC_MTTestLib1_V2.SourceAssembly().BoundReferences(); var varMTTestLib3_Name = new AssemblyIdentity("MTTestLib3"); var varC_MTTestLib3 = CreateCompilation(varMTTestLib3_Name, new string[] { // AssemblyPaths.SymbolsTests.V2.MTTestModule3.netmodule @" public class Class5 { Class1 Foo1() { return null; } Class2 Foo2() { return null; } Class4 Foo3() { return null; } Class1 Bar1; Class2 Bar2; Class4 Bar3; } " }, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib2.ToMetadataReference(), varC_MTTestLib1_V2.ToMetadataReference() }); var asm_MTTestLib3 = varC_MTTestLib3.SourceAssembly().BoundReferences(); Assert.Same(asm_MTTestLib3[0], asm_MTTestLib1_V1[0]); Assert.NotSame(asm_MTTestLib3[1], varC_MTTestLib2.SourceAssembly()); Assert.NotSame(asm_MTTestLib3[2], varC_MTTestLib1_V1.SourceAssembly()); var c3 = CreateCompilation(new AssemblyIdentity("c3"), null, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib2.ToMetadataReference(), varC_MTTestLib1_V2.ToMetadataReference(), varC_MTTestLib3.ToMetadataReference() }); var asm3 = c3.SourceAssembly().BoundReferences(); Assert.Same(asm3[0], asm_MTTestLib1_V1[0]); Assert.Same(asm3[1], asm_MTTestLib3[1]); Assert.Same(asm3[2], asm_MTTestLib3[2]); Assert.Same(asm3[3], varC_MTTestLib3.SourceAssembly()); Assert.Equal("MTTestLib2", asm3[1].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm3[1]).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly()); Assert.Equal(2, (from a in asm3[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(1, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); var retval2 = asm3[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval2.Kind); Assert.Same(retval2, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm3[2].Identity.Name); Assert.NotSame(asm3[2], asm2[2]); Assert.NotSame(asm3[2].DeclaringCompilation, asm2[2].DeclaringCompilation); Assert.Equal(2, asm3[2].Identity.Version.Major); Assert.Equal(1, (from a in asm3[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[2].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal("MTTestLib3", asm3[3].Identity.Name); Assert.Equal(3, (from a in asm3[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[1]) select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); var type1 = asm3[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); var retval3 = type1.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval3.Kind); Assert.Same(retval3, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); var retval4 = type1.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval4.Kind); Assert.Same(retval4, asm3[2].GlobalNamespace.GetMembers("Class2").Single()); var retval5 = type1.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval5.Kind); Assert.Same(retval5, asm3[1].GlobalNamespace.GetMembers("Class4").Single()); var varMTTestLib1_V3_Name = new AssemblyIdentity("MTTestLib1", new Version("3.0.0.0")); var varC_MTTestLib1_V3 = CreateCompilation(varMTTestLib1_V3_Name, new string[] { // AssemblyPaths.SymbolsTests.V3.MTTestModule1.netmodule @" public class Class1 { } public class Class2 { } public class Class3 { } " }, new MetadataReference[] { Net451.mscorlib }); var asm_MTTestLib1_V3 = varC_MTTestLib1_V3.SourceAssembly().BoundReferences(); var varMTTestLib4_Name = new AssemblyIdentity("MTTestLib4"); var varC_MTTestLib4 = CreateCompilation(varMTTestLib4_Name, new string[] { // AssemblyPaths.SymbolsTests.V3.MTTestModule4.netmodule @" public class Class6 { Class1 Foo1() { return null; } Class2 Foo2() { return null; } Class3 Foo3() { return null; } Class4 Foo4() { return null; } Class5 Foo5() { return null; } Class1 Bar1; Class2 Bar2; Class3 Bar3; Class4 Bar4; Class5 Bar5; } " }, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib2.ToMetadataReference(), varC_MTTestLib1_V3.ToMetadataReference(), varC_MTTestLib3.ToMetadataReference() }); var asm_MTTestLib4 = varC_MTTestLib4.SourceAssembly().BoundReferences(); Assert.Same(asm_MTTestLib4[0], asm_MTTestLib1_V1[0]); Assert.NotSame(asm_MTTestLib4[1], varC_MTTestLib2.SourceAssembly()); Assert.Same(asm_MTTestLib4[2], varC_MTTestLib1_V3.SourceAssembly()); Assert.NotSame(asm_MTTestLib4[3], varC_MTTestLib3.SourceAssembly()); var c4 = CreateCompilation(new AssemblyIdentity("c4"), null, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib2.ToMetadataReference(), varC_MTTestLib1_V3.ToMetadataReference(), varC_MTTestLib3.ToMetadataReference(), varC_MTTestLib4.ToMetadataReference() }); var asm4 = c4.SourceAssembly().BoundReferences(); Assert.Same(asm4[0], asm_MTTestLib1_V1[0]); Assert.Same(asm4[1], asm_MTTestLib4[1]); Assert.Same(asm4[2], asm_MTTestLib4[2]); Assert.Same(asm4[3], asm_MTTestLib4[3]); Assert.Same(asm4[4], varC_MTTestLib4.SourceAssembly()); Assert.Equal("MTTestLib2", asm4[1].Identity.Name); Assert.NotSame(asm4[1], varC_MTTestLib2.SourceAssembly()); Assert.NotSame(asm4[1], asm2[1]); Assert.NotSame(asm4[1], asm3[1]); Assert.Same(((RetargetingAssemblySymbol)asm4[1]).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly()); Assert.Equal(2, (from a in asm4[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); var retval6 = asm4[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval6.Kind); Assert.Same(retval6, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm4[2].Identity.Name); Assert.NotSame(asm4[2], asm2[2]); Assert.NotSame(asm4[2], asm3[2]); Assert.NotSame(asm4[2].DeclaringCompilation, asm2[2].DeclaringCompilation); Assert.NotSame(asm4[2].DeclaringCompilation, asm3[2].DeclaringCompilation); Assert.Equal(3, asm4[2].Identity.Version.Major); Assert.Equal(1, (from a in asm4[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[2].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal("MTTestLib3", asm4[3].Identity.Name); Assert.NotSame(asm4[3], asm3[3]); Assert.Same(((RetargetingAssemblySymbol)asm4[3]).UnderlyingAssembly, asm3[3]); Assert.Equal(3, (from a in asm4[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); var type2 = asm4[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); var retval7 = type2.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval7.Kind); Assert.Same(retval7, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); var retval8 = type2.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval8.Kind); Assert.Same(retval8, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); var retval9 = type2.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval9.Kind); Assert.Same(retval9, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm4[4].Identity.Name); Assert.Equal(4, (from a in asm4[4].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[3]) select a).Count()); var type3 = asm4[4].GlobalNamespace.GetTypeMembers("Class6"). Single(); var retval10 = type3.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval10.Kind); Assert.Same(retval10, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); var retval11 = type3.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval11.Kind); Assert.Same(retval11, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); var retval12 = type3.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval12.Kind); Assert.Same(retval12, asm4[2].GlobalNamespace.GetMembers("Class3").Single()); var retval13 = type3.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval13.Kind); Assert.Same(retval13, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); var retval14 = type3.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval14.Kind); Assert.Same(retval14, asm4[3].GlobalNamespace.GetMembers("Class5").Single()); var c5 = CreateCompilation(new AssemblyIdentity("c5"), null, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib3.ToMetadataReference() }); var asm5 = c5.SourceAssembly().BoundReferences(); Assert.Same(asm5[0], asm2[0]); Assert.True(asm5[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm3[3])); var c6 = CreateCompilation(new AssemblyIdentity("c6"), null, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib2.ToMetadataReference() }); var asm6 = c6.SourceAssembly().BoundReferences(); Assert.Same(asm6[0], asm2[0]); Assert.True(asm6[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly())); var c7 = CreateCompilation(new AssemblyIdentity("c7"), null, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib2.ToMetadataReference(), varC_MTTestLib3.ToMetadataReference(), varC_MTTestLib4.ToMetadataReference() }); var asm7 = c7.SourceAssembly().BoundReferences(); Assert.Same(asm7[0], asm2[0]); Assert.True(asm7[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly())); Assert.NotSame(asm7[2], asm3[3]); Assert.NotSame(asm7[2], asm4[3]); Assert.NotSame(asm7[3], asm4[4]); Assert.Equal("MTTestLib3", asm7[2].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm7[2]).UnderlyingAssembly, asm3[3]); Assert.Equal(2, (from a in asm7[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(1, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); var type4 = asm7[2].GlobalNamespace.GetTypeMembers("Class5"). Single(); var retval15 = type4.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval15.ContainingAssembly.Name); Assert.Equal(0, (from a in asm7 where a != null && a.Name == "MTTestLib1" select a).Count()); var retval16 = type4.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval16.ContainingAssembly.Name); var retval17 = type4.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval17.Kind); Assert.Same(retval17, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm7[3].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm7[3]).UnderlyingAssembly, asm4[4]); Assert.Equal(3, (from a in asm7[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[2]) select a).Count()); var type5 = asm7[3].GlobalNamespace.GetTypeMembers("Class6"). Single(); var retval18 = type5.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval18.ContainingAssembly.Name); var retval19 = type5.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval19.ContainingAssembly.Name); var retval20 = type5.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval20.ContainingAssembly.Name); var retval21 = type5.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval21.Kind); Assert.Same(retval21, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); var retval22 = type5.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval22.Kind); Assert.Same(retval22, asm7[2].GlobalNamespace.GetMembers("Class5").Single()); // This test shows that simple reordering of references doesn't pick different set of assemblies var c8 = CreateCompilation(new AssemblyIdentity("c8"), null, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib4.ToMetadataReference(), varC_MTTestLib2.ToMetadataReference(), varC_MTTestLib3.ToMetadataReference() }); var asm8 = c8.SourceAssembly().BoundReferences(); Assert.Same(asm8[0], asm2[0]); Assert.True(asm8[2].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[1])); Assert.Same(asm8[2], asm7[1]); Assert.True(asm8[3].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[3])); Assert.Same(asm8[3], asm7[2]); Assert.True(asm8[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[4])); Assert.Same(asm8[1], asm7[3]); var c9 = CreateCompilation(new AssemblyIdentity("c9"), null, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib4.ToMetadataReference() }); var asm9 = c9.SourceAssembly().BoundReferences(); Assert.Same(asm9[0], asm2[0]); Assert.True(asm9[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[4])); var c10 = CreateCompilation(new AssemblyIdentity("c10"), null, new MetadataReference[] { Net451.mscorlib, varC_MTTestLib2.ToMetadataReference(), varC_MTTestLib1_V3.ToMetadataReference(), varC_MTTestLib3.ToMetadataReference(), varC_MTTestLib4.ToMetadataReference() }); var asm10 = c10.SourceAssembly().BoundReferences(); Assert.Same(asm10[0], asm2[0]); Assert.Same(asm10[1], asm4[1]); Assert.Same(asm10[2], asm4[2]); Assert.Same(asm10[3], asm4[3]); Assert.Same(asm10[4], asm4[4]); // Run the same tests again to make sure we didn't corrupt prior state by loading additional assemblies Assert.Same(asm2[0], asm_MTTestLib1_V1[0]); Assert.Equal("MTTestLib2", asm2[1].Identity.Name); Assert.Equal(2, (from a in asm2[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); Assert.Equal(1, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[2]) select a).Count()); retval1 = asm2[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval1.Kind); Assert.Same(retval1, asm2[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm2[2].Identity.Name); Assert.Equal(1, asm2[2].Identity.Version.Major); Assert.Equal(1, (from a in asm2[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[2].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); Assert.Same(asm_MTTestLib3[0], asm_MTTestLib1_V1[0]); Assert.NotSame(asm_MTTestLib3[1], varC_MTTestLib2.SourceAssembly()); Assert.NotSame(asm_MTTestLib3[2], varC_MTTestLib1_V1.SourceAssembly()); Assert.Same(asm3[0], asm_MTTestLib1_V1[0]); Assert.Same(asm3[1], asm_MTTestLib3[1]); Assert.Same(asm3[2], asm_MTTestLib3[2]); Assert.Same(asm3[3], varC_MTTestLib3.SourceAssembly()); Assert.Equal("MTTestLib2", asm3[1].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm3[1]).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly()); Assert.Equal(2, (from a in asm3[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(1, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); retval2 = asm3[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval2.Kind); Assert.Same(retval2, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm3[2].Identity.Name); Assert.NotSame(asm3[2], asm2[2]); Assert.NotSame(asm3[2].DeclaringCompilation, asm2[2].DeclaringCompilation); Assert.Equal(2, asm3[2].Identity.Version.Major); Assert.Equal(1, (from a in asm3[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[2].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal("MTTestLib3", asm3[3].Identity.Name); Assert.Equal(3, (from a in asm3[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[1]) select a).Count()); Assert.Equal(1, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); type1 = asm3[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); retval3 = type1.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval3.Kind); Assert.Same(retval3, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); retval4 = type1.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval4.Kind); Assert.Same(retval4, asm3[2].GlobalNamespace.GetMembers("Class2").Single()); retval5 = type1.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval5.Kind); Assert.Same(retval5, asm3[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Same(asm4[0], asm_MTTestLib1_V1[0]); Assert.Same(asm4[1], asm_MTTestLib4[1]); Assert.Same(asm4[2], asm_MTTestLib4[2]); Assert.Same(asm4[3], asm_MTTestLib4[3]); Assert.Same(asm4[4], varC_MTTestLib4.SourceAssembly()); Assert.Equal("MTTestLib2", asm4[1].Identity.Name); Assert.NotSame(asm4[1], varC_MTTestLib2.SourceAssembly()); Assert.NotSame(asm4[1], asm2[1]); Assert.NotSame(asm4[1], asm3[1]); Assert.Same(((RetargetingAssemblySymbol)asm4[1]).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly()); Assert.Equal(2, (from a in asm4[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); retval6 = asm4[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval6.Kind); Assert.Same(retval6, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm4[2].Identity.Name); Assert.NotSame(asm4[2], asm2[2]); Assert.NotSame(asm4[2], asm3[2]); Assert.NotSame(asm4[2].DeclaringCompilation, asm2[2].DeclaringCompilation); Assert.NotSame(asm4[2].DeclaringCompilation, asm3[2].DeclaringCompilation); Assert.Equal(3, asm4[2].Identity.Version.Major); Assert.Equal(1, (from a in asm4[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[2].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal("MTTestLib3", asm4[3].Identity.Name); Assert.NotSame(asm4[3], asm3[3]); Assert.Same(((RetargetingAssemblySymbol)asm4[3]).UnderlyingAssembly, asm3[3]); Assert.Equal(3, (from a in asm4[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(1, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); type2 = asm4[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); retval7 = type2.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval7.Kind); Assert.Same(retval7, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); retval8 = type2.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval8.Kind); Assert.Same(retval8, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); retval9 = type2.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval9.Kind); Assert.Same(retval9, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm4[4].Identity.Name); Assert.Equal(4, (from a in asm4[4].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); Assert.Equal(1, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[3]) select a).Count()); type3 = asm4[4].GlobalNamespace.GetTypeMembers("Class6"). Single(); retval10 = type3.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval10.Kind); Assert.Same(retval10, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); retval11 = type3.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval11.Kind); Assert.Same(retval11, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); retval12 = type3.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval12.Kind); Assert.Same(retval12, asm4[2].GlobalNamespace.GetMembers("Class3").Single()); retval13 = type3.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval13.Kind); Assert.Same(retval13, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); retval14 = type3.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval14.Kind); Assert.Same(retval14, asm4[3].GlobalNamespace.GetMembers("Class5").Single()); Assert.Same(asm5[0], asm2[0]); Assert.True(asm5[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm3[3])); Assert.Same(asm6[0], asm2[0]); Assert.True(asm6[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly())); Assert.Same(asm7[0], asm2[0]); Assert.True(asm7[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly())); Assert.NotSame(asm7[2], asm3[3]); Assert.NotSame(asm7[2], asm4[3]); Assert.NotSame(asm7[3], asm4[4]); Assert.Equal("MTTestLib3", asm7[2].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm7[2]).UnderlyingAssembly, asm3[3]); Assert.Equal(2, (from a in asm7[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(1, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); type4 = asm7[2].GlobalNamespace.GetTypeMembers("Class5"). Single(); retval15 = type4.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval15.ContainingAssembly.Name); Assert.Equal(0, (from a in asm7 where a != null && a.Name == "MTTestLib1" select a).Count()); retval16 = type4.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval16.ContainingAssembly.Name); retval17 = type4.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval17.Kind); Assert.Same(retval17, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm7[3].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm7[3]).UnderlyingAssembly, asm4[4]); Assert.Equal(3, (from a in asm7[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); Assert.Equal(1, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[2]) select a).Count()); type5 = asm7[3].GlobalNamespace.GetTypeMembers("Class6"). Single(); retval18 = type5.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval18.ContainingAssembly.Name); retval19 = type5.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval19.ContainingAssembly.Name); retval20 = type5.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", retval20.ContainingAssembly.Name); retval21 = type5.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval21.Kind); Assert.Same(retval21, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); retval22 = type5.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval22.Kind); Assert.Same(retval22, asm7[2].GlobalNamespace.GetMembers("Class5").Single()); } [Fact] public void MultiTargeting3() { var varMTTestLib2_Name = new AssemblyIdentity("MTTestLib2"); var varC_MTTestLib2 = CreateCompilation(varMTTestLib2_Name, (string[])null, new[] { Net451.mscorlib, TestReferences.SymbolsTests.V1.MTTestLib1.dll, TestReferences.SymbolsTests.V1.MTTestModule2.netmodule }); var asm_MTTestLib2 = varC_MTTestLib2.SourceAssembly().BoundReferences(); var c2 = CreateCompilation(new AssemblyIdentity("c2"), null, new MetadataReference[] { Net451.mscorlib, TestReferences.SymbolsTests.V1.MTTestLib1.dll, new CSharpCompilationReference(varC_MTTestLib2) }); var asm2Prime = c2.SourceAssembly().BoundReferences(); var asm2 = new AssemblySymbol[] { asm2Prime[0], asm2Prime[2], asm2Prime[1] }; Assert.Same(asm2[0], asm_MTTestLib2[0]); Assert.Same(asm2[1], varC_MTTestLib2.SourceAssembly()); Assert.Same(asm2[2], asm_MTTestLib2[1]); Assert.Equal("MTTestLib2", asm2[1].Identity.Name); Assert.Equal(4, (from a in asm2[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); Assert.Equal(2, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[2]) select a).Count()); var retval1 = asm2[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.Same(retval1, asm2[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Bar").OfType<FieldSymbol>().Single().Type); Assert.NotEqual(SymbolKind.ErrorType, retval1.Kind); Assert.Same(retval1, asm2[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm2[2].Identity.Name); Assert.Equal(1, asm2[2].Identity.Version.Major); Assert.Equal(1, (from a in asm2[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[2].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); var varMTTestLib3_Name = new AssemblyIdentity("MTTestLib3"); var varC_MTTestLib3 = CreateCompilation(varMTTestLib3_Name, null, new MetadataReference[] { Net451.mscorlib, TestReferences.SymbolsTests.V2.MTTestLib1.dll, new CSharpCompilationReference(varC_MTTestLib2), TestReferences.SymbolsTests.V2.MTTestModule3.netmodule }); var asm_MTTestLib3Prime = varC_MTTestLib3.SourceAssembly().BoundReferences(); var asm_MTTestLib3 = new AssemblySymbol[] { asm_MTTestLib3Prime[0], asm_MTTestLib3Prime[2], asm_MTTestLib3Prime[1] }; Assert.Same(asm_MTTestLib3[0], asm_MTTestLib2[0]); Assert.NotSame(asm_MTTestLib3[1], varC_MTTestLib2.SourceAssembly()); Assert.NotSame(asm_MTTestLib3[2], asm_MTTestLib2[1]); var c3 = CreateCompilation(new AssemblyIdentity("c3"), null, new MetadataReference[] { Net451.mscorlib, TestReferences.SymbolsTests.V2.MTTestLib1.dll, new CSharpCompilationReference(varC_MTTestLib2), new CSharpCompilationReference(varC_MTTestLib3) }); var asm3Prime = c3.SourceAssembly().BoundReferences(); var asm3 = new AssemblySymbol[] { asm3Prime[0], asm3Prime[2], asm3Prime[1], asm3Prime[3] }; Assert.Same(asm3[0], asm_MTTestLib2[0]); Assert.Same(asm3[1], asm_MTTestLib3[1]); Assert.Same(asm3[2], asm_MTTestLib3[2]); Assert.Same(asm3[3], varC_MTTestLib3.SourceAssembly()); Assert.Equal("MTTestLib2", asm3[1].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm3[1]).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly()); Assert.Equal(4, (from a in asm3[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(2, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); var retval2 = asm3[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.Same(retval2, asm3[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Bar").OfType<FieldSymbol>().Single().Type); Assert.NotEqual(SymbolKind.ErrorType, retval2.Kind); Assert.Same(retval2, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm3[2].Identity.Name); Assert.NotSame(asm3[2], asm2[2]); Assert.NotSame(asm3[2], asm2[2]); Assert.NotSame(((PEAssemblySymbol)asm3[2]).Assembly, ((PEAssemblySymbol)asm2[2]).Assembly); Assert.Equal(2, asm3[2].Identity.Version.Major); Assert.Equal(1, (from a in asm3[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[2].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal("MTTestLib3", asm3[3].Identity.Name); Assert.Equal(6, (from a in asm3[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(2, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[1]) select a).Count()); Assert.Equal(2, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); var type1 = asm3[3].GlobalNamespace.GetTypeMembers("Class5").Single(); var retval3 = type1.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval3.Kind); Assert.Same(retval3, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); var retval4 = type1.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval4.Kind); Assert.Same(retval4, asm3[2].GlobalNamespace.GetMembers("Class2").Single()); var retval5 = type1.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval5.Kind); Assert.Same(retval5, asm3[1].GlobalNamespace.GetMembers("Class4").Single()); var varMTTestLib4_Name = new AssemblyIdentity("MTTestLib4"); var varC_MTTestLib4 = CreateCompilation(varMTTestLib4_Name, null, new MetadataReference[] { Net451.mscorlib, TestReferences.SymbolsTests.V3.MTTestLib1.dll, new CSharpCompilationReference(varC_MTTestLib2), new CSharpCompilationReference(varC_MTTestLib3), TestReferences.SymbolsTests.V3.MTTestModule4.netmodule }); var asm_MTTestLib4Prime = varC_MTTestLib4.SourceAssembly().BoundReferences(); var asm_MTTestLib4 = new AssemblySymbol[] { asm_MTTestLib4Prime[0], asm_MTTestLib4Prime[2], asm_MTTestLib4Prime[1], asm_MTTestLib4Prime[3] }; Assert.Same(asm_MTTestLib4[0], asm_MTTestLib2[0]); Assert.NotSame(asm_MTTestLib4[1], varC_MTTestLib2.SourceAssembly()); Assert.NotSame(asm_MTTestLib4[2], asm3[2]); Assert.NotSame(asm_MTTestLib4[2], asm2[2]); Assert.NotSame(asm_MTTestLib4[3], varC_MTTestLib3.SourceAssembly()); var c4 = CreateCompilation(new AssemblyIdentity("c4"), null, new MetadataReference[] { Net451.mscorlib, TestReferences.SymbolsTests.V3.MTTestLib1.dll, new CSharpCompilationReference(varC_MTTestLib2), new CSharpCompilationReference(varC_MTTestLib3), new CSharpCompilationReference(varC_MTTestLib4) }); var asm4Prime = c4.SourceAssembly().BoundReferences(); var asm4 = new AssemblySymbol[] { asm4Prime[0], asm4Prime[2], asm4Prime[1], asm4Prime[3], asm4Prime[4] }; Assert.Same(asm4[0], asm_MTTestLib2[0]); Assert.Same(asm4[1], asm_MTTestLib4[1]); Assert.Same(asm4[2], asm_MTTestLib4[2]); Assert.Same(asm4[3], asm_MTTestLib4[3]); Assert.Same(asm4[4], varC_MTTestLib4.SourceAssembly()); Assert.Equal("MTTestLib2", asm4[1].Identity.Name); Assert.NotSame(asm4[1], varC_MTTestLib2.SourceAssembly()); Assert.NotSame(asm4[1], asm2[1]); Assert.NotSame(asm4[1], asm3[1]); Assert.Same(((RetargetingAssemblySymbol)asm4[1]).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly()); Assert.Equal(4, (from a in asm4[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(2, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); var retval6 = asm4[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval6.Kind); Assert.Same(retval6, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm4[2].Identity.Name); Assert.NotSame(asm4[2], asm2[2]); Assert.NotSame(asm4[2], asm3[2]); Assert.NotSame(((PEAssemblySymbol)asm4[2]).Assembly, ((PEAssemblySymbol)asm2[2]).Assembly); Assert.NotSame(((PEAssemblySymbol)asm4[2]).Assembly, ((PEAssemblySymbol)asm3[2]).Assembly); Assert.Equal(3, asm4[2].Identity.Version.Major); Assert.Equal(1, (from a in asm4[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[2].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal("MTTestLib3", asm4[3].Identity.Name); Assert.NotSame(asm4[3], asm3[3]); Assert.Same(((RetargetingAssemblySymbol)asm4[3]).UnderlyingAssembly, asm3[3]); Assert.Equal(6, (from a in asm4[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(2, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(2, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); var type2 = asm4[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); var retval7 = type2.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval7.Kind); Assert.Same(retval7, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); var retval8 = type2.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval8.Kind); Assert.Same(retval8, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); var retval9 = type2.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval9.Kind); Assert.Same(retval9, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm4[4].Identity.Name); Assert.Equal(8, (from a in asm4[4].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(2, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(2, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); Assert.Equal(2, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[3]) select a).Count()); var type3 = asm4[4].GlobalNamespace.GetTypeMembers("Class6"). Single(); var retval10 = type3.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval10.Kind); Assert.Same(retval10, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); var retval11 = type3.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval11.Kind); Assert.Same(retval11, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); var retval12 = type3.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval12.Kind); Assert.Same(retval12, asm4[2].GlobalNamespace.GetMembers("Class3").Single()); var retval13 = type3.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval13.Kind); Assert.Same(retval13, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); var retval14 = type3.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval14.Kind); Assert.Same(retval14, asm4[3].GlobalNamespace.GetMembers("Class5").Single()); var c5 = CreateCompilation(new AssemblyIdentity("c5"), null, new MetadataReference[] { Net451.mscorlib, new CSharpCompilationReference(varC_MTTestLib3) }); var asm5 = c5.SourceAssembly().BoundReferences(); Assert.Same(asm5[0], asm2[0]); Assert.True(asm5[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm3[3])); var c6 = CreateCompilation(new AssemblyIdentity("c6"), null, new MetadataReference[] { Net451.mscorlib, new CSharpCompilationReference(varC_MTTestLib2) }); var asm6 = c6.SourceAssembly().BoundReferences(); Assert.Same(asm6[0], asm2[0]); Assert.True(asm6[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly())); var c7 = CreateCompilation(new AssemblyIdentity("c7"), null, new MetadataReference[] { Net451.mscorlib, new CSharpCompilationReference(varC_MTTestLib2), new CSharpCompilationReference(varC_MTTestLib3), new CSharpCompilationReference(varC_MTTestLib4) }); var asm7 = c7.SourceAssembly().BoundReferences(); Assert.Same(asm7[0], asm2[0]); Assert.True(asm7[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly())); Assert.NotSame(asm7[2], asm3[3]); Assert.NotSame(asm7[2], asm4[3]); Assert.NotSame(asm7[3], asm4[4]); Assert.Equal("MTTestLib3", asm7[2].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm7[2]).UnderlyingAssembly, asm3[3]); Assert.Equal(4, (from a in asm7[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(2, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); var type4 = asm7[2].GlobalNamespace.GetTypeMembers("Class5"). Single(); var retval15 = type4.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; AssemblySymbol missingAssembly; missingAssembly = retval15.ContainingAssembly; Assert.True(missingAssembly.IsMissing); Assert.Equal("MTTestLib1", missingAssembly.Identity.Name); var retval16 = type4.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Same(missingAssembly, retval16.ContainingAssembly); var retval17 = type4.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval17.Kind); Assert.Same(retval17, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm7[3].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm7[3]).UnderlyingAssembly, asm4[4]); Assert.Equal(6, (from a in asm7[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(2, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); Assert.Equal(2, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[2]) select a).Count()); var type5 = asm7[3].GlobalNamespace.GetTypeMembers("Class6"). Single(); var retval18 = type5.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", ((MissingMetadataTypeSymbol)retval18).ContainingAssembly.Identity.Name); var retval19 = type5.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Same(retval18.ContainingAssembly, retval19.ContainingAssembly); var retval20 = type5.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.Same(retval18.ContainingAssembly, retval20.ContainingAssembly); var retval21 = type5.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval21.Kind); Assert.Same(retval21, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); var retval22 = type5.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval22.Kind); Assert.Same(retval22, asm7[2].GlobalNamespace.GetMembers("Class5").Single()); // This test shows that simple reordering of references doesn't pick different set of assemblies var c8 = CreateCompilation(new AssemblyIdentity("c8"), null, new MetadataReference[] { Net451.mscorlib, new CSharpCompilationReference(varC_MTTestLib4), new CSharpCompilationReference(varC_MTTestLib2), new CSharpCompilationReference(varC_MTTestLib3) }); var asm8 = c8.SourceAssembly().BoundReferences(); Assert.Same(asm8[0], asm2[0]); Assert.True(asm8[2].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[1])); Assert.Same(asm8[2], asm7[1]); Assert.True(asm8[3].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[3])); Assert.Same(asm8[3], asm7[2]); Assert.True(asm8[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[4])); Assert.Same(asm8[1], asm7[3]); var c9 = CreateCompilation(new AssemblyIdentity("c9"), null, new MetadataReference[] { Net451.mscorlib, new CSharpCompilationReference(varC_MTTestLib4) }); var asm9 = c9.SourceAssembly().BoundReferences(); Assert.Same(asm9[0], asm2[0]); Assert.True(asm9[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm4[4])); var c10 = CreateCompilation(new AssemblyIdentity("c10"), null, new MetadataReference[] { Net451.mscorlib, TestReferences.SymbolsTests.V3.MTTestLib1.dll, new CSharpCompilationReference(varC_MTTestLib2), new CSharpCompilationReference(varC_MTTestLib3), new CSharpCompilationReference(varC_MTTestLib4) }); var asm10Prime = c10.SourceAssembly().BoundReferences(); var asm10 = new AssemblySymbol[] { asm10Prime[0], asm10Prime[2], asm10Prime[1], asm10Prime[3], asm10Prime[4] }; Assert.Same(asm10[0], asm2[0]); Assert.Same(asm10[1], asm4[1]); Assert.Same(asm10[2], asm4[2]); Assert.Same(asm10[3], asm4[3]); Assert.Same(asm10[4], asm4[4]); // Run the same tests again to make sure we didn't corrupt prior state by loading additional assemblies Assert.Same(asm2[0], asm_MTTestLib2[0]); Assert.Equal("MTTestLib2", asm2[1].Identity.Name); Assert.Equal(4, (from a in asm2[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); Assert.Equal(2, (from a in asm2[1].BoundReferences() where object.ReferenceEquals(a, asm2[2]) select a).Count()); retval1 = asm2[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval1.Kind); Assert.Same(retval1, asm2[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm2[2].Identity.Name); Assert.Equal(1, asm2[2].Identity.Version.Major); Assert.Equal(1, (from a in asm2[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm2[2].BoundReferences() where object.ReferenceEquals(a, asm2[0]) select a).Count()); Assert.Same(asm_MTTestLib3[0], asm_MTTestLib2[0]); Assert.NotSame(asm_MTTestLib3[1], varC_MTTestLib2.SourceAssembly()); Assert.NotSame(asm_MTTestLib3[2], asm_MTTestLib2[1]); Assert.Same(asm3[0], asm_MTTestLib2[0]); Assert.Same(asm3[1], asm_MTTestLib3[1]); Assert.Same(asm3[2], asm_MTTestLib3[2]); Assert.Same(asm3[3], varC_MTTestLib3.SourceAssembly()); Assert.Equal("MTTestLib2", asm3[1].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm3[1]).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly()); Assert.Equal(4, (from a in asm3[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(2, (from a in asm3[1].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); retval2 = asm3[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval2.Kind); Assert.Same(retval2, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm3[2].Identity.Name); Assert.NotSame(asm3[2], asm2[2]); Assert.NotSame(((PEAssemblySymbol)asm3[2]).Assembly, ((PEAssemblySymbol)asm2[2]).Assembly); Assert.Equal(2, asm3[2].Identity.Version.Major); Assert.Equal(1, (from a in asm3[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm3[2].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal("MTTestLib3", asm3[3].Identity.Name); Assert.Equal(6, (from a in asm3[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[0]) select a).Count()); Assert.Equal(2, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[1]) select a).Count()); Assert.Equal(2, (from a in asm3[3].BoundReferences() where object.ReferenceEquals(a, asm3[2]) select a).Count()); type1 = asm3[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); retval3 = type1.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval3.Kind); Assert.Same(retval3, asm3[2].GlobalNamespace.GetMembers("Class1").Single()); retval4 = type1.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval4.Kind); Assert.Same(retval4, asm3[2].GlobalNamespace.GetMembers("Class2").Single()); retval5 = type1.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval5.Kind); Assert.Same(retval5, asm3[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Same(asm4[0], asm_MTTestLib2[0]); Assert.Same(asm4[1], asm_MTTestLib4[1]); Assert.Same(asm4[2], asm_MTTestLib4[2]); Assert.Same(asm4[3], asm_MTTestLib4[3]); Assert.Same(asm4[4], varC_MTTestLib4.SourceAssembly()); Assert.Equal("MTTestLib2", asm4[1].Identity.Name); Assert.NotSame(asm4[1], varC_MTTestLib2.SourceAssembly()); Assert.NotSame(asm4[1], asm2[1]); Assert.NotSame(asm4[1], asm3[1]); Assert.Same(((RetargetingAssemblySymbol)asm4[1]).UnderlyingAssembly, varC_MTTestLib2.SourceAssembly()); Assert.Equal(4, (from a in asm4[1].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(2, (from a in asm4[1].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); retval6 = asm4[1].GlobalNamespace.GetTypeMembers("Class4"). Single(). GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval6.Kind); Assert.Same(retval6, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); Assert.Equal("MTTestLib1", asm4[2].Identity.Name); Assert.NotSame(asm4[2], asm2[2]); Assert.NotSame(asm4[2], asm3[2]); Assert.NotSame(((PEAssemblySymbol)asm4[2]).Assembly, ((PEAssemblySymbol)asm2[2]).Assembly); Assert.NotSame(((PEAssemblySymbol)asm4[2]).Assembly, ((PEAssemblySymbol)asm3[2]).Assembly); Assert.Equal(3, asm4[2].Identity.Version.Major); Assert.Equal(1, (from a in asm4[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(1, (from a in asm4[2].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal("MTTestLib3", asm4[3].Identity.Name); Assert.NotSame(asm4[3], asm3[3]); Assert.Same(((RetargetingAssemblySymbol)asm4[3]).UnderlyingAssembly, asm3[3]); Assert.Equal(6, (from a in asm4[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(2, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(2, (from a in asm4[3].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); type2 = asm4[3].GlobalNamespace.GetTypeMembers("Class5"). Single(); retval7 = type2.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval7.Kind); Assert.Same(retval7, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); retval8 = type2.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval8.Kind); Assert.Same(retval8, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); retval9 = type2.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval9.Kind); Assert.Same(retval9, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm4[4].Identity.Name); Assert.Equal(8, (from a in asm4[4].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[0]) select a).Count()); Assert.Equal(2, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[1]) select a).Count()); Assert.Equal(2, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[2]) select a).Count()); Assert.Equal(2, (from a in asm4[4].BoundReferences() where object.ReferenceEquals(a, asm4[3]) select a).Count()); type3 = asm4[4].GlobalNamespace.GetTypeMembers("Class6"). Single(); retval10 = type3.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval10.Kind); Assert.Same(retval10, asm4[2].GlobalNamespace.GetMembers("Class1").Single()); retval11 = type3.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval11.Kind); Assert.Same(retval11, asm4[2].GlobalNamespace.GetMembers("Class2").Single()); retval12 = type3.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval12.Kind); Assert.Same(retval12, asm4[2].GlobalNamespace.GetMembers("Class3").Single()); retval13 = type3.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval13.Kind); Assert.Same(retval13, asm4[1].GlobalNamespace.GetMembers("Class4").Single()); retval14 = type3.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval14.Kind); Assert.Same(retval14, asm4[3].GlobalNamespace.GetMembers("Class5").Single()); Assert.Same(asm5[0], asm2[0]); Assert.True(asm5[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(asm3[3])); Assert.Same(asm6[0], asm2[0]); Assert.True(asm6[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly())); Assert.Same(asm7[0], asm2[0]); Assert.True(asm7[1].RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(varC_MTTestLib2.SourceAssembly())); Assert.NotSame(asm7[2], asm3[3]); Assert.NotSame(asm7[2], asm4[3]); Assert.NotSame(asm7[3], asm4[4]); Assert.Equal("MTTestLib3", asm7[2].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm7[2]).UnderlyingAssembly, asm3[3]); Assert.Equal(4, (from a in asm7[2].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(2, (from a in asm7[2].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); type4 = asm7[2].GlobalNamespace.GetTypeMembers("Class5"). Single(); retval15 = type4.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; missingAssembly = retval15.ContainingAssembly; Assert.True(missingAssembly.IsMissing); Assert.Equal("MTTestLib1", missingAssembly.Identity.Name); retval16 = type4.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Same(missingAssembly, retval16.ContainingAssembly); retval17 = type4.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval17.Kind); Assert.Same(retval17, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); Assert.Equal("MTTestLib4", asm7[3].Identity.Name); Assert.Same(((RetargetingAssemblySymbol)asm7[3]).UnderlyingAssembly, asm4[4]); Assert.Equal(6, (from a in asm7[3].BoundReferences() where !a.IsMissing select a).Count()); Assert.Equal(2, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[0]) select a).Count()); Assert.Equal(2, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[1]) select a).Count()); Assert.Equal(2, (from a in asm7[3].BoundReferences() where object.ReferenceEquals(a, asm7[2]) select a).Count()); type5 = asm7[3].GlobalNamespace.GetTypeMembers("Class6"). Single(); retval18 = type5.GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("MTTestLib1", ((MissingMetadataTypeSymbol)retval18).ContainingAssembly.Identity.Name); retval19 = type5.GetMembers("Foo2").OfType<MethodSymbol>().Single().ReturnType; Assert.Same(retval18.ContainingAssembly, retval19.ContainingAssembly); retval20 = type5.GetMembers("Foo3").OfType<MethodSymbol>().Single().ReturnType; Assert.Same(retval18.ContainingAssembly, retval20.ContainingAssembly); retval21 = type5.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval21.Kind); Assert.Same(retval21, asm7[1].GlobalNamespace.GetMembers("Class4").Single()); retval22 = type5.GetMembers("Foo5").OfType<MethodSymbol>().Single().ReturnType; Assert.NotEqual(SymbolKind.ErrorType, retval22.Kind); Assert.Same(retval22, asm7[2].GlobalNamespace.GetMembers("Class5").Single()); } [Fact] public void MultiTargeting4() { var localC1_V1_Name = new AssemblyIdentity("c1", new Version("1.0.0.0")); var localC1_V1 = CreateCompilation(localC1_V1_Name, new string[] { // AssemblyPaths.SymbolsTests.MultiTargeting.Source1Module.netmodule @" public class C1<T> { public class C2<S> { public C1<T>.C2<S> Foo() { return null; } } } " }, new[] { Net451.mscorlib }); var asm1_V1 = localC1_V1.SourceAssembly(); var localC1_V2_Name = new AssemblyIdentity("c1", new Version("2.0.0.0")); var localC1_V2 = CreateCompilation(localC1_V2_Name, new string[] { // AssemblyPaths.SymbolsTests.MultiTargeting.Source1Module.netmodule @" public class C1<T> { public class C2<S> { public C1<T>.C2<S> Foo() { return null; } } } " }, new MetadataReference[] { Net451.mscorlib }); var asm1_V2 = localC1_V2.SourceAssembly(); var localC4_V1_Name = new AssemblyIdentity("c4", new Version("1.0.0.0")); var localC4_V1 = CreateCompilation(localC4_V1_Name, new string[] { // AssemblyPaths.SymbolsTests.MultiTargeting.Source4Module.netmodule @" public class C4 { } " }, new MetadataReference[] { Net451.mscorlib }); var asm4_V1 = localC4_V1.SourceAssembly(); var localC4_V2_Name = new AssemblyIdentity("c4", new Version("2.0.0.0")); var localC4_V2 = CreateCompilation(localC4_V2_Name, new string[] { // AssemblyPaths.SymbolsTests.MultiTargeting.Source4Module.netmodule @" public class C4 { } " }, new MetadataReference[] { Net451.mscorlib }); var asm4_V2 = localC4_V2.SourceAssembly(); var c7 = CreateCompilation(new AssemblyIdentity("C7"), new string[] { // AssemblyPaths.SymbolsTests.MultiTargeting.Source7Module.netmodule @" public class C7 {} public class C8<T> { } " }, new MetadataReference[] { Net451.mscorlib }); var asm7 = c7.SourceAssembly(); var c3 = CreateCompilation(new AssemblyIdentity("C3"), new string[] { // AssemblyPaths.SymbolsTests.MultiTargeting.Source3Module.netmodule @" public class C3 { public C1<C3>.C2<C4> Foo() { return null; } public static C6<C4> Bar() { return null; } public C8<C7> Foo1() { return null; } public void Foo2(ref C300[,] x1, out C4 x2, ref C7[] x3, C4 x4 = null) { x2 = null; } internal virtual TFoo3 Foo3<TFoo3>() where TFoo3: C4 { return null; } public C8<C4> Foo4() { return null; } public abstract class C301 : I1 { } internal class C302 { } } public class C6<T> where T: new () {} public class C300 {} public interface I1 {} namespace ns1 { namespace ns2 { public class C303 {} } public class C304 { public class C305 {} } } " }, new MetadataReference[] { Net451.mscorlib, new CSharpCompilationReference(localC1_V1), new CSharpCompilationReference(localC4_V1), new CSharpCompilationReference(c7) }); var asm3 = c3.SourceAssembly(); var localC3Foo2 = asm3.GlobalNamespace.GetTypeMembers("C3"). Single().GetMembers("Foo2").OfType<MethodSymbol>().Single(); var c5 = CreateCompilation(new AssemblyIdentity("C5"), new string[] { // AssemblyPaths.SymbolsTests.MultiTargeting.Source5Module.netmodule @" public class C5 : ns1.C304.C305 {} " }, new MetadataReference[] { Net451.mscorlib, new CSharpCompilationReference(c3), new CSharpCompilationReference(localC1_V2), new CSharpCompilationReference(localC4_V2), new CSharpCompilationReference(c7) }); var asm5 = c5.SourceAssembly().BoundReferences(); Assert.NotSame(asm5[1], asm3); Assert.Same(((RetargetingAssemblySymbol)asm5[1]).UnderlyingAssembly, asm3); Assert.Same(asm5[2], asm1_V2); Assert.Same(asm5[3], asm4_V2); Assert.Same(asm5[4], asm7); var type3 = asm5[1].GlobalNamespace.GetTypeMembers("C3"). Single(); var type1 = asm1_V2.GlobalNamespace.GetTypeMembers("C1"). Single(); var type2 = type1.GetTypeMembers("C2"). Single(); var type4 = asm4_V2.GlobalNamespace.GetTypeMembers("C4"). Single(); var retval1 = (NamedTypeSymbol)type3.GetMembers("Foo").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("C1<C3>.C2<C4>", retval1.ToTestDisplayString()); Assert.Same(retval1.OriginalDefinition, type2); var args1 = retval1.ContainingType.TypeArguments().Concat(retval1.TypeArguments()); var params1 = retval1.ContainingType.TypeParameters.Concat(retval1.TypeParameters); Assert.Same(params1[0], type1.TypeParameters[0]); Assert.Same(params1[1].OriginalDefinition, type2.TypeParameters[0].OriginalDefinition); Assert.Same(args1[0], type3); Assert.Same(args1[0].ContainingAssembly, asm5[1]); Assert.Same(args1[1], type4); var retval2 = retval1.ContainingType; Assert.Equal("C1<C3>", retval2.ToTestDisplayString()); Assert.Same(retval2.OriginalDefinition, type1); var bar = type3.GetMembers("Bar").OfType<MethodSymbol>().Single(); var retval3 = (NamedTypeSymbol)bar.ReturnType; var type6 = asm5[1].GlobalNamespace.GetTypeMembers("C6"). Single(); Assert.Equal("C6<C4>", retval3.ToTestDisplayString()); Assert.Same(retval3.OriginalDefinition, type6); Assert.Same(retval3.ContainingAssembly, asm5[1]); var args3 = retval3.TypeArguments(); var params3 = retval3.TypeParameters; Assert.Same(params3[0], type6.TypeParameters[0]); Assert.Same(params3[0].ContainingAssembly, asm5[1]); Assert.Same(args3[0], type4); var foo1 = type3.GetMembers("Foo1").OfType<MethodSymbol>().Single(); var retval4 = foo1.ReturnType; Assert.Equal("C8<C7>", retval4.ToTestDisplayString()); Assert.Same(retval4, asm3.GlobalNamespace.GetTypeMembers("C3"). Single(). GetMembers("Foo1").OfType<MethodSymbol>().Single().ReturnType); var foo1Params = foo1.Parameters; Assert.Equal(0, foo1Params.Length); var foo2 = type3.GetMembers("Foo2").OfType<MethodSymbol>().Single(); Assert.NotEqual(localC3Foo2, foo2); Assert.Same(localC3Foo2, ((RetargetingMethodSymbol)foo2).UnderlyingMethod); Assert.Equal(1, ((RetargetingMethodSymbol)foo2).Locations.Length); var foo2Params = foo2.Parameters; Assert.Equal(4, foo2Params.Length); Assert.Same(localC3Foo2.Parameters[0], ((RetargetingParameterSymbol)foo2Params[0]).UnderlyingParameter); Assert.Same(localC3Foo2.Parameters[1], ((RetargetingParameterSymbol)foo2Params[1]).UnderlyingParameter); Assert.Same(localC3Foo2.Parameters[2], ((RetargetingParameterSymbol)foo2Params[2]).UnderlyingParameter); Assert.Same(localC3Foo2.Parameters[3], ((RetargetingParameterSymbol)foo2Params[3]).UnderlyingParameter); var x1 = foo2Params[0]; var x2 = foo2Params[1]; var x3 = foo2Params[2]; var x4 = foo2Params[3]; Assert.Equal("x1", x1.Name); Assert.NotEqual(localC3Foo2.Parameters[0].Type, x1.Type); Assert.Equal(localC3Foo2.Parameters[0].ToTestDisplayString(), x1.ToTestDisplayString()); Assert.Same(asm5[1], x1.ContainingAssembly); Assert.Same(foo2, x1.ContainingSymbol); Assert.False(x1.HasExplicitDefaultValue); Assert.False(x1.IsOptional); Assert.Equal(RefKind.Ref, x1.RefKind); Assert.Equal(2, ((ArrayTypeSymbol)x1.Type).Rank); Assert.Equal("x2", x2.Name); Assert.NotEqual(localC3Foo2.Parameters[1].Type, x2.Type); Assert.Equal(RefKind.Out, x2.RefKind); Assert.Equal("x3", x3.Name); Assert.Same(localC3Foo2.Parameters[2].Type, x3.Type); Assert.Equal("x4", x4.Name); Assert.True(x4.HasExplicitDefaultValue); Assert.True(x4.IsOptional); Assert.Equal("Foo2", foo2.Name); Assert.Equal(localC3Foo2.ToTestDisplayString(), foo2.ToTestDisplayString()); Assert.Same(asm5[1], foo2.ContainingAssembly); Assert.Same(type3, foo2.ContainingSymbol); Assert.Equal(Accessibility.Public, foo2.DeclaredAccessibility); Assert.False(foo2.HidesBaseMethodsByName); Assert.False(foo2.IsAbstract); Assert.False(foo2.IsExtern); Assert.False(foo2.IsGenericMethod); Assert.False(foo2.IsOverride); Assert.False(foo2.IsSealed); Assert.False(foo2.IsStatic); Assert.False(foo2.IsVararg); Assert.False(foo2.IsVirtual); Assert.True(foo2.ReturnsVoid); Assert.Equal(0, foo2.TypeParameters.Length); Assert.Equal(0, foo2.TypeArgumentsWithAnnotations.Length); Assert.True(bar.IsStatic); Assert.False(bar.ReturnsVoid); var foo3 = type3.GetMembers("Foo3").OfType<MethodSymbol>().Single(); Assert.Equal(Accessibility.Internal, foo3.DeclaredAccessibility); Assert.True(foo3.IsGenericMethod); Assert.True(foo3.IsVirtual); var foo3TypeParams = foo3.TypeParameters; Assert.Equal(1, foo3TypeParams.Length); Assert.Equal(1, foo3.TypeArgumentsWithAnnotations.Length); Assert.Same(foo3TypeParams[0], foo3.TypeArgumentsWithAnnotations[0].Type); var typeC301 = type3.GetTypeMembers("C301").Single(); var typeC302 = type3.GetTypeMembers("C302").Single(); var typeC6 = asm5[1].GlobalNamespace.GetTypeMembers("C6").Single(); Assert.Equal(typeC301.ToTestDisplayString(), asm3.GlobalNamespace.GetTypeMembers("C3").Single(). GetTypeMembers("C301").Single().ToTestDisplayString()); Assert.Equal(typeC6.ToTestDisplayString(), asm3.GlobalNamespace.GetTypeMembers("C6").Single().ToTestDisplayString()); Assert.Equal(typeC301.ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat), asm3.GlobalNamespace.GetTypeMembers("C3").Single(). GetTypeMembers("C301").Single().ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat)); Assert.Equal(typeC6.ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat), asm3.GlobalNamespace.GetTypeMembers("C6").Single().ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat)); Assert.Equal(type3.GetMembers().Length, asm3.GlobalNamespace.GetTypeMembers("C3").Single().GetMembers().Length); Assert.Equal(type3.GetTypeMembers().Length, asm3.GlobalNamespace.GetTypeMembers("C3").Single().GetTypeMembers().Length); Assert.Same(typeC301, type3.GetTypeMembers("C301", 0).Single()); Assert.Equal(0, type3.Arity); Assert.Equal(1, typeC6.Arity); Assert.NotNull(type3.BaseType()); Assert.Equal("System.Object", type3.BaseType().ToTestDisplayString()); Assert.Equal(Accessibility.Public, type3.DeclaredAccessibility); Assert.Equal(Accessibility.Internal, typeC302.DeclaredAccessibility); Assert.Equal(0, type3.Interfaces().Length); Assert.Equal(1, typeC301.Interfaces().Length); Assert.Equal("I1", typeC301.Interfaces().Single().Name); Assert.False(type3.IsAbstract); Assert.True(typeC301.IsAbstract); Assert.False(type3.IsSealed); Assert.False(type3.IsStatic); Assert.Equal(0, type3.TypeArguments().Length); Assert.Equal(0, type3.TypeParameters.Length); var localC6Params = typeC6.TypeParameters; Assert.Equal(1, localC6Params.Length); Assert.Equal(1, typeC6.TypeArguments().Length); Assert.Same(localC6Params[0], typeC6.TypeArguments()[0]); Assert.Same(((RetargetingNamedTypeSymbol)type3).UnderlyingNamedType, asm3.GlobalNamespace.GetTypeMembers("C3").Single()); Assert.Equal(1, ((RetargetingNamedTypeSymbol)type3).Locations.Length); Assert.Equal(TypeKind.Class, type3.TypeKind); Assert.Equal(TypeKind.Interface, asm5[1].GlobalNamespace.GetTypeMembers("I1").Single().TypeKind); var localC6_T = localC6Params[0]; var foo3TypeParam = foo3TypeParams[0]; Assert.Equal(0, localC6_T.ConstraintTypes().Length); Assert.Equal(1, foo3TypeParam.ConstraintTypes().Length); Assert.Same(type4, foo3TypeParam.ConstraintTypes().Single()); Assert.Same(typeC6, localC6_T.ContainingSymbol); Assert.False(foo3TypeParam.HasConstructorConstraint); Assert.True(localC6_T.HasConstructorConstraint); Assert.False(foo3TypeParam.HasReferenceTypeConstraint); Assert.False(foo3TypeParam.HasValueTypeConstraint); Assert.Equal("TFoo3", foo3TypeParam.Name); Assert.Equal("T", localC6_T.Name); Assert.Equal(0, foo3TypeParam.Ordinal); Assert.Equal(0, localC6_T.Ordinal); Assert.Equal(VarianceKind.None, foo3TypeParam.Variance); Assert.Same(((RetargetingTypeParameterSymbol)localC6_T).UnderlyingTypeParameter, asm3.GlobalNamespace.GetTypeMembers("C6").Single().TypeParameters[0]); var ns1 = asm5[1].GlobalNamespace.GetMembers("ns1").OfType<NamespaceSymbol>().Single(); var ns2 = ns1.GetMembers("ns2").OfType<NamespaceSymbol>().Single(); Assert.Equal("ns1.ns2", ns2.ToTestDisplayString()); Assert.Equal(2, ns1.GetMembers().Length); Assert.Equal(1, ns1.GetTypeMembers().Length); Assert.Same(ns1.GetTypeMembers("C304").Single(), ns1.GetTypeMembers("C304", 0).Single()); Assert.Same(asm5[1].Modules[0], asm5[1].Modules[0].GlobalNamespace.ContainingSymbol); Assert.Same(asm5[1].Modules[0].GlobalNamespace, ns1.ContainingSymbol); Assert.Same(asm5[1].Modules[0], ns1.Extent.Module); Assert.Equal(1, ns1.ConstituentNamespaces.Length); Assert.Same(ns1, ns1.ConstituentNamespaces[0]); Assert.False(ns1.IsGlobalNamespace); Assert.True(asm5[1].Modules[0].GlobalNamespace.IsGlobalNamespace); Assert.Same(asm3.Modules[0].GlobalNamespace, ((RetargetingNamespaceSymbol)asm5[1].Modules[0].GlobalNamespace).UnderlyingNamespace); Assert.Same(asm3.Modules[0].GlobalNamespace.GetMembers("ns1").Single(), ((RetargetingNamespaceSymbol)ns1).UnderlyingNamespace); var module3 = (RetargetingModuleSymbol)asm5[1].Modules[0]; Assert.Equal("C3.dll", module3.ToTestDisplayString()); Assert.Equal("C3.dll", module3.Name); Assert.Same(asm5[1], module3.ContainingSymbol); Assert.Same(asm5[1], module3.ContainingAssembly); Assert.Null(module3.ContainingType); var retval5 = type3.GetMembers("Foo4").OfType<MethodSymbol>().Single().ReturnType; Assert.Equal("C8<C4>", retval5.ToTestDisplayString()); var typeC5 = c5.Assembly.GlobalNamespace.GetTypeMembers("C5").Single(); Assert.Same(asm5[1], typeC5.BaseType().ContainingAssembly); Assert.Equal("ns1.C304.C305", typeC5.BaseType().ToTestDisplayString()); Assert.NotEqual(SymbolKind.ErrorType, typeC5.Kind); } [Fact] public void MultiTargeting5() { var c1_Name = new AssemblyIdentity("c1"); var text = @" class Module1 { Class4 M1() {} Class4.Class4_1 M2() {} Class4 M3() {} } "; var c1 = CreateEmptyCompilation(text, new MetadataReference[] { MscorlibRef, TestReferences.SymbolsTests.V1.MTTestLib1.dll, TestReferences.SymbolsTests.V1.MTTestModule2.netmodule }); var c2_Name = new AssemblyIdentity("MTTestLib2"); var c2 = CreateCompilation(c2_Name, null, new MetadataReference[] { Net451.mscorlib, TestReferences.SymbolsTests.V2.MTTestLib1.dll, new CSharpCompilationReference(c1) }); SourceAssemblySymbol c1AsmSource = (SourceAssemblySymbol)c1.Assembly; PEAssemblySymbol Lib1_V1 = (PEAssemblySymbol)c1AsmSource.Modules[0].GetReferencedAssemblySymbols()[1]; PEModuleSymbol module1 = (PEModuleSymbol)c1AsmSource.Modules[1]; Assert.Equal(LocationKind.MetadataFile, ((MetadataLocation)Lib1_V1.Locations[0]).Kind); SourceAssemblySymbol c2AsmSource = (SourceAssemblySymbol)c2.Assembly; RetargetingAssemblySymbol c1AsmRef = (RetargetingAssemblySymbol)c2AsmSource.Modules[0].GetReferencedAssemblySymbols()[2]; PEAssemblySymbol Lib1_V2 = (PEAssemblySymbol)c2AsmSource.Modules[0].GetReferencedAssemblySymbols()[1]; PEModuleSymbol module2 = (PEModuleSymbol)c1AsmRef.Modules[1]; Assert.Equal(1, Lib1_V1.Identity.Version.Major); Assert.Equal(2, Lib1_V2.Identity.Version.Major); Assert.NotEqual(module1, module2); Assert.Same(module1.Module, module2.Module); NamedTypeSymbol classModule1 = c1AsmRef.Modules[0].GlobalNamespace.GetTypeMembers("Module1").Single(); MethodSymbol m1 = classModule1.GetMembers("M1").OfType<MethodSymbol>().Single(); MethodSymbol m2 = classModule1.GetMembers("M2").OfType<MethodSymbol>().Single(); MethodSymbol m3 = classModule1.GetMembers("M3").OfType<MethodSymbol>().Single(); Assert.Same(module2, m1.ReturnType.ContainingModule); Assert.Same(module2, m2.ReturnType.ContainingModule); Assert.Same(module2, m3.ReturnType.ContainingModule); } // Very simplistic test if a compilation has a single type with the given full name. Does NOT handle generics. private bool HasSingleTypeOfKind(CSharpCompilation c, TypeKind kind, string fullName) { string[] names = fullName.Split('.'); NamespaceOrTypeSymbol current = c.GlobalNamespace; foreach (string name in names) { var matchingSym = current.GetMembers(name); if (matchingSym.Length != 1) { return false; } current = (NamespaceOrTypeSymbol)matchingSym.First(); } return current is TypeSymbol && ((TypeSymbol)current).TypeKind == kind; } [Fact] public void AddRemoveReferences() { var mscorlibRef = Net451.mscorlib; var systemCoreRef = Net451.SystemCore; var systemRef = Net451.System; CSharpCompilation c = CSharpCompilation.Create("Test"); Assert.False(HasSingleTypeOfKind(c, TypeKind.Struct, "System.Int32")); c = c.AddReferences(mscorlibRef); Assert.True(HasSingleTypeOfKind(c, TypeKind.Struct, "System.Int32")); Assert.False(HasSingleTypeOfKind(c, TypeKind.Class, "System.Linq.Enumerable")); c = c.AddReferences(systemCoreRef); Assert.True(HasSingleTypeOfKind(c, TypeKind.Class, "System.Linq.Enumerable")); Assert.False(HasSingleTypeOfKind(c, TypeKind.Class, "System.Uri")); c = c.ReplaceReference(systemCoreRef, systemRef); Assert.False(HasSingleTypeOfKind(c, TypeKind.Class, "System.Linq.Enumerable")); Assert.True(HasSingleTypeOfKind(c, TypeKind.Class, "System.Uri")); c = c.RemoveReferences(systemRef); Assert.False(HasSingleTypeOfKind(c, TypeKind.Class, "System.Uri")); Assert.True(HasSingleTypeOfKind(c, TypeKind.Struct, "System.Int32")); c = c.RemoveReferences(mscorlibRef); Assert.False(HasSingleTypeOfKind(c, TypeKind.Struct, "System.Int32")); } private sealed class Resolver : MetadataReferenceResolver { private readonly string _data, _core, _system; public Resolver(string data, string core, string system) { _data = data; _core = core; _system = system; } public override ImmutableArray<PortableExecutableReference> ResolveReference(string reference, string baseFilePath, MetadataReferenceProperties properties) { switch (reference) { case "System.Data": return ImmutableArray.Create(MetadataReference.CreateFromFile(_data)); case "System.Core": return ImmutableArray.Create(MetadataReference.CreateFromFile(_core)); case "System": return ImmutableArray.Create(MetadataReference.CreateFromFile(_system)); default: if (File.Exists(reference)) { return ImmutableArray.Create(MetadataReference.CreateFromFile(reference)); } return ImmutableArray<PortableExecutableReference>.Empty; } } public override bool Equals(object other) => true; public override int GetHashCode() => 1; } [Fact] public void CompilationWithReferenceDirectives() { var data = Temp.CreateFile().WriteAllBytes(ResourcesNet451.SystemData).Path; var core = Temp.CreateFile().WriteAllBytes(ResourcesNet451.SystemCore).Path; var xml = Temp.CreateFile().WriteAllBytes(ResourcesNet451.SystemXml).Path; var system = Temp.CreateFile().WriteAllBytes(ResourcesNet451.System).Path; var trees = new[] { SyntaxFactory.ParseSyntaxTree($@" #r ""System.Data"" #r ""{xml}"" #r ""{core}"" ", options: TestOptions.Script), SyntaxFactory.ParseSyntaxTree(@" #r ""System"" ", options: TestOptions.Script), SyntaxFactory.ParseSyntaxTree(@" new System.Data.DataSet(); System.Linq.Expressions.Expression.Constant(123); System.Diagnostics.Process.GetCurrentProcess(); ", options: TestOptions.Script) }; var compilation = CreateCompilationWithMscorlib45( trees, options: TestOptions.ReleaseDll.WithMetadataReferenceResolver(new Resolver(data, core, system))); compilation.VerifyDiagnostics(); var boundRefs = compilation.Assembly.BoundReferences(); AssertEx.Equal(new[] { "System.Data", "System.Xml", "System.Core", "System", "mscorlib" }, boundRefs.Select(r => r.Name)); } [Fact] public void CompilationWithReferenceDirectives_Errors() { var data = Temp.CreateFile().WriteAllBytes(ResourcesNet451.SystemData).Path; var core = Temp.CreateFile().WriteAllBytes(ResourcesNet451.SystemCore).Path; var system = Temp.CreateFile().WriteAllBytes(ResourcesNet451.System).Path; var trees = new[] { SyntaxFactory.ParseSyntaxTree(@" #r System #r ""~!@#$%^&*():\?/"" #r ""non-existing-reference"" ", options: TestOptions.Script), SyntaxFactory.ParseSyntaxTree(@" #r ""System.Core"" ", TestOptions.Regular) }; var compilation = CreateCompilationWithMscorlib45( trees, options: TestOptions.ReleaseDll.WithMetadataReferenceResolver(new Resolver(data, core, system))); compilation.VerifyDiagnostics( // (3,1): error CS0006: Metadata file '~!@#$%^&*():\?/' could not be found Diagnostic(ErrorCode.ERR_NoMetadataFile, @"#r ""~!@#$%^&*():\?/""").WithArguments(@"~!@#$%^&*():\?/"), // (4,1): error CS0006: Metadata file 'non-existing-reference' could not be found Diagnostic(ErrorCode.ERR_NoMetadataFile, @"#r ""non-existing-reference""").WithArguments("non-existing-reference"), // (2,4): error CS7010: Quoted file name expected Diagnostic(ErrorCode.ERR_ExpectedPPFile, "System"), // (2,1): error CS7011: #r is only allowed in scripts Diagnostic(ErrorCode.ERR_ReferenceDirectiveOnlyAllowedInScripts, "r")); } private class DummyReferenceResolver : MetadataReferenceResolver { private readonly string _targetDll; public DummyReferenceResolver(string targetDll) { _targetDll = targetDll; } public override ImmutableArray<PortableExecutableReference> ResolveReference(string reference, string baseFilePath, MetadataReferenceProperties properties) { var path = reference.EndsWith("-resolve", StringComparison.Ordinal) ? _targetDll : reference; return ImmutableArray.Create(MetadataReference.CreateFromFile(path, properties)); } public override bool Equals(object other) => true; public override int GetHashCode() => 1; } [Fact] public void MetadataReferenceProvider() { var csClasses01 = Temp.CreateFile().WriteAllBytes(TestResources.MetadataTests.InterfaceAndClass.CSClasses01).Path; var csInterfaces01 = Temp.CreateFile().WriteAllBytes(TestResources.MetadataTests.InterfaceAndClass.CSInterfaces01).Path; var source = @" #r """ + "!@#$%^/&*-resolve" + @""" #r """ + csInterfaces01 + @""" class C : Metadata.ICSPropImpl { }"; var compilation = CreateCompilationWithMscorlib45( new[] { Parse(source, options: TestOptions.Script) }, options: TestOptions.ReleaseDll.WithMetadataReferenceResolver(new DummyReferenceResolver(csClasses01))); compilation.VerifyDiagnostics(); } [Fact] public void CompilationWithReferenceDirective_NoResolver() { var compilation = CreateCompilationWithMscorlib45( new[] { SyntaxFactory.ParseSyntaxTree(@"#r ""bar""", TestOptions.Script, "a.csx", Encoding.UTF8) }, options: TestOptions.ReleaseDll.WithMetadataReferenceResolver(null)); compilation.VerifyDiagnostics( // a.csx(1,1): error CS7099: Metadata references not supported. // #r "bar" Diagnostic(ErrorCode.ERR_MetadataReferencesNotSupported, @"#r ""bar""")); } [Fact] public void GlobalUsings1() { var trees = new[] { SyntaxFactory.ParseSyntaxTree(@" WriteLine(1); Console.WriteLine(2); ", options: TestOptions.Script), SyntaxFactory.ParseSyntaxTree(@" class C { void Foo() { Console.WriteLine(3); } } ", TestOptions.Regular) }; var compilation = CreateCompilationWithMscorlib45( trees, options: TestOptions.ReleaseDll.WithUsings(ImmutableArray.Create("System.Console", "System"))); var diagnostics = compilation.GetDiagnostics().ToArray(); // global usings are only visible in script code: DiagnosticsUtils.VerifyErrorCodes(diagnostics, // (4,18): error CS0103: The name 'Console' does not exist in the current context new ErrorDescription() { Code = (int)ErrorCode.ERR_NameNotInContext, Line = 4, Column = 18 }); } [Fact] public void GlobalUsings_Errors() { var trees = new[] { SyntaxFactory.ParseSyntaxTree(@" WriteLine(1); Console.WriteLine(2); ", options: TestOptions.Script) }; var compilation = CreateCompilationWithMscorlib45( trees, options: TestOptions.ReleaseDll.WithUsings("System.Console!", "Blah")); compilation.VerifyDiagnostics( // error CS0234: The type or namespace name 'Console!' does not exist in the namespace 'System' (are you missing an assembly reference?) Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS).WithArguments("Console!", "System"), // error CS0246: The type or namespace name 'Blah' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound).WithArguments("Blah"), // (2,1): error CS0103: The name 'WriteLine' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "WriteLine").WithArguments("WriteLine"), // (3,1): error CS0103: The name 'Console' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "Console").WithArguments("Console")); } [Fact] public void ReferenceToAssemblyWithSpecialCharactersInName() { var r = TestReferences.SymbolsTests.Metadata.InvalidCharactersInAssemblyName; var st = SyntaxFactory.ParseSyntaxTree("class C { static void Main() { new lib.Class1(); } }"); var compilation = CSharpCompilation.Create("foo", references: new[] { MscorlibRef, r }, syntaxTrees: new[] { st }); var diags = compilation.GetDiagnostics().ToArray(); Assert.Equal(0, diags.Length); using (var stream = new MemoryStream()) { compilation.Emit(stream); } } [Fact] public void SyntaxTreeOrderConstruct() { var tree1 = CreateSyntaxTree("A"); var tree2 = CreateSyntaxTree("B"); SyntaxTree[] treeOrder1 = new[] { tree1, tree2 }; var compilation1 = CSharpCompilation.Create("Compilation1", syntaxTrees: treeOrder1); CheckCompilationSyntaxTrees(compilation1, treeOrder1); SyntaxTree[] treeOrder2 = new[] { tree2, tree1 }; var compilation2 = CSharpCompilation.Create("Compilation2", syntaxTrees: treeOrder2); CheckCompilationSyntaxTrees(compilation2, treeOrder2); } [Fact] public void SyntaxTreeOrderAdd() { var tree1 = CreateSyntaxTree("A"); var tree2 = CreateSyntaxTree("B"); var tree3 = CreateSyntaxTree("C"); var tree4 = CreateSyntaxTree("D"); SyntaxTree[] treeList1 = new[] { tree1, tree2 }; var compilation1 = CSharpCompilation.Create("Compilation1", syntaxTrees: treeList1); CheckCompilationSyntaxTrees(compilation1, treeList1); SyntaxTree[] treeList2 = new[] { tree3, tree4 }; var compilation2 = compilation1.AddSyntaxTrees(treeList2); CheckCompilationSyntaxTrees(compilation1, treeList1); //compilation1 untouched CheckCompilationSyntaxTrees(compilation2, treeList1.Concat(treeList2).ToArray()); SyntaxTree[] treeList3 = new[] { tree4, tree3 }; var compilation3 = CSharpCompilation.Create("Compilation3", syntaxTrees: treeList3); CheckCompilationSyntaxTrees(compilation3, treeList3); SyntaxTree[] treeList4 = new[] { tree2, tree1 }; var compilation4 = compilation3.AddSyntaxTrees(treeList4); CheckCompilationSyntaxTrees(compilation3, treeList3); //compilation3 untouched CheckCompilationSyntaxTrees(compilation4, treeList3.Concat(treeList4).ToArray()); } [Fact] public void SyntaxTreeOrderRemove() { var tree1 = CreateSyntaxTree("A"); var tree2 = CreateSyntaxTree("B"); var tree3 = CreateSyntaxTree("C"); var tree4 = CreateSyntaxTree("D"); SyntaxTree[] treeList1 = new[] { tree1, tree2, tree3, tree4 }; var compilation1 = CSharpCompilation.Create("Compilation1", syntaxTrees: treeList1); CheckCompilationSyntaxTrees(compilation1, treeList1); SyntaxTree[] treeList2 = new[] { tree3, tree1 }; var compilation2 = compilation1.RemoveSyntaxTrees(treeList2); CheckCompilationSyntaxTrees(compilation1, treeList1); //compilation1 untouched CheckCompilationSyntaxTrees(compilation2, tree2, tree4); SyntaxTree[] treeList3 = new[] { tree4, tree3, tree2, tree1 }; var compilation3 = CSharpCompilation.Create("Compilation3", syntaxTrees: treeList3); CheckCompilationSyntaxTrees(compilation3, treeList3); SyntaxTree[] treeList4 = new[] { tree3, tree1 }; var compilation4 = compilation3.RemoveSyntaxTrees(treeList4); CheckCompilationSyntaxTrees(compilation3, treeList3); //compilation3 untouched CheckCompilationSyntaxTrees(compilation4, tree4, tree2); } [Fact] public void SyntaxTreeOrderReplace() { var tree1 = CreateSyntaxTree("A"); var tree2 = CreateSyntaxTree("B"); var tree3 = CreateSyntaxTree("C"); SyntaxTree[] treeList1 = new[] { tree1, tree2 }; var compilation1 = CSharpCompilation.Create("Compilation1", syntaxTrees: treeList1); CheckCompilationSyntaxTrees(compilation1, treeList1); var compilation2 = compilation1.ReplaceSyntaxTree(tree1, tree3); CheckCompilationSyntaxTrees(compilation1, treeList1); //compilation1 untouched CheckCompilationSyntaxTrees(compilation2, tree3, tree2); SyntaxTree[] treeList3 = new[] { tree2, tree1 }; var compilation3 = CSharpCompilation.Create("Compilation3", syntaxTrees: treeList3); CheckCompilationSyntaxTrees(compilation3, treeList3); var compilation4 = compilation3.ReplaceSyntaxTree(tree1, tree3); CheckCompilationSyntaxTrees(compilation3, treeList3); //compilation3 untouched CheckCompilationSyntaxTrees(compilation4, tree2, tree3); } [WorkItem(578706, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578706")] [Fact] public void DeclaringCompilationOfAddedModule() { var source1 = "public class C1 { }"; var source2 = "public class C2 { }"; var lib1 = CreateCompilation(source1, assemblyName: "Lib1", options: TestOptions.ReleaseModule); var ref1 = lib1.EmitToImageReference(); // NOTE: can't use a compilation reference for a module. var lib2 = CreateCompilation(source2, new[] { ref1 }, assemblyName: "Lib2"); lib2.VerifyDiagnostics(); var sourceAssembly = lib2.Assembly; var sourceModule = sourceAssembly.Modules[0]; var sourceType = sourceModule.GlobalNamespace.GetMember<NamedTypeSymbol>("C2"); Assert.IsType<SourceAssemblySymbol>(sourceAssembly); Assert.Equal(lib2, sourceAssembly.DeclaringCompilation); Assert.IsType<SourceModuleSymbol>(sourceModule); Assert.Equal(lib2, sourceModule.DeclaringCompilation); Assert.IsType<SourceNamedTypeSymbol>(sourceType); Assert.Equal(lib2, sourceType.DeclaringCompilation); var addedModule = sourceAssembly.Modules[1]; var addedModuleAssembly = addedModule.ContainingAssembly; var addedModuleType = addedModule.GlobalNamespace.GetMember<NamedTypeSymbol>("C1"); Assert.IsType<SourceAssemblySymbol>(addedModuleAssembly); Assert.Equal(lib2, addedModuleAssembly.DeclaringCompilation); //NB: not lib1, not null Assert.IsType<PEModuleSymbol>(addedModule); Assert.Null(addedModule.DeclaringCompilation); Assert.IsAssignableFrom<PENamedTypeSymbol>(addedModuleType); Assert.Null(addedModuleType.DeclaringCompilation); } } }
-1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/Test/MetadataAsSource/MetadataAsSourceTests.CSharp.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.Editor.CSharp; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.MetadataAsSource { public partial class MetadataAsSourceTests { public class CSharp : AbstractMetadataAsSourceTests { [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void ExtractXMLFromDocComment() { var docCommentText = @"/// <summary> /// I am the very model of a modern major general. /// </summary>"; var expectedXMLFragment = @" <summary> I am the very model of a modern major general. </summary>"; var extractedXMLFragment = DocumentationCommentUtilities.ExtractXMLFragment(docCommentText, "///"); Assert.Equal(expectedXMLFragment, extractedXMLFragment); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] [WorkItem(42986, "https://github.com/dotnet/roslyn/issues/42986")] public async Task TestNativeInteger(bool allowDecompilation) { var metadataSource = "public class C { public nint i; public nuint i2; }"; var symbolName = "C"; var expected = allowDecompilation switch { false => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class [|C|] {{ public nint i; public nuint i2; public C(); }}", true => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|C|] {{ public nint i; public nuint i2; }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, languageVersion: "Preview", metadataLanguageVersion: "Preview", expected: expected, allowDecompilation: allowDecompilation); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestInitOnlyProperty(bool allowDecompilation) { var metadataSource = @"public class C { public int Property { get; init; } } namespace System.Runtime.CompilerServices { public sealed class IsExternalInit { } } "; var symbolName = "C"; var expected = allowDecompilation switch { false => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class [|C|] {{ public C(); public int Property {{ get; init; }} }}", true => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|C|] {{ public int Property {{ get; set; }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, languageVersion: "Preview", metadataLanguageVersion: "Preview", expected: expected, allowDecompilation: allowDecompilation); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestTupleWithNames(bool allowDecompilation) { var metadataSource = "public class C { public (int a, int b) t; }"; var symbolName = "C"; var expected = allowDecompilation switch { false => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System.Runtime.CompilerServices; public class [|C|] {{ [TupleElementNames(new[] {{ ""a"", ""b"" }})] public (int a, int b) t; public C(); }}", true => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|C|] {{ public (int a, int b) t; }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51")} {string.Format(CSharpEditorResources.Load_from_0, "System.ValueTuple.dll")} #endif", }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, expected: expected, allowDecompilation: allowDecompilation); } [Theory, CombinatorialData, WorkItem(26605, "https://github.com/dotnet/roslyn/issues/26605")] public async Task TestValueTuple(bool allowDecompilation) { using var context = TestContext.Create(LanguageNames.CSharp); var expected = allowDecompilation switch { false => $@"#region {FeaturesResources.Assembly} System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51 // System.ValueTuple.dll #endregion using System.Collections; namespace System {{ public struct [|ValueTuple|] : IEquatable<ValueTuple>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple>, ITupleInternal {{ public static ValueTuple Create(); public static ValueTuple<T1> Create<T1>(T1 item1); public static (T1, T2) Create<T1, T2>(T1 item1, T2 item2); public static (T1, T2, T3) Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3); public static (T1, T2, T3, T4) Create<T1, T2, T3, T4>(T1 item1, T2 item2, T3 item3, T4 item4); public static (T1, T2, T3, T4, T5) Create<T1, T2, T3, T4, T5>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5); public static (T1, T2, T3, T4, T5, T6) Create<T1, T2, T3, T4, T5, T6>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6); public static (T1, T2, T3, T4, T5, T6, T7) Create<T1, T2, T3, T4, T5, T6, T7>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7); public static (T1, T2, T3, T4, T5, T6, T7, T8) Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8); public int CompareTo(ValueTuple other); public override bool Equals(object obj); public bool Equals(ValueTuple other); public override int GetHashCode(); public override string ToString(); }} }}", true => $@"#region {FeaturesResources.Assembly} System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51 // System.ValueTuple.dll // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Collections; using System.Runtime.InteropServices; namespace System {{ [StructLayout(LayoutKind.Sequential, Size = 1)] public struct [|ValueTuple|] : IEquatable<ValueTuple>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple>, ITupleInternal {{ int ITupleInternal.Size => 0; public override bool Equals(object obj) {{ return obj is ValueTuple; }} public bool Equals(ValueTuple other) {{ return true; }} bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) {{ return other is ValueTuple; }} int IComparable.CompareTo(object other) {{ if (other == null) {{ return 1; }} if (!(other is ValueTuple)) {{ throw new ArgumentException(SR.ArgumentException_ValueTupleIncorrectType, ""other""); }} return 0; }} public int CompareTo(ValueTuple other) {{ return 0; }} int IStructuralComparable.CompareTo(object other, IComparer comparer) {{ if (other == null) {{ return 1; }} if (!(other is ValueTuple)) {{ throw new ArgumentException(SR.ArgumentException_ValueTupleIncorrectType, ""other""); }} return 0; }} public override int GetHashCode() {{ return 0; }} int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) {{ return 0; }} int ITupleInternal.GetHashCode(IEqualityComparer comparer) {{ return 0; }} public override string ToString() {{ return ""()""; }} string ITupleInternal.ToStringEnd() {{ return "")""; }} public static ValueTuple Create() {{ return default(ValueTuple); }} public static ValueTuple<T1> Create<T1>(T1 item1) {{ return new ValueTuple<T1>(item1); }} public static (T1, T2) Create<T1, T2>(T1 item1, T2 item2) {{ return (item1, item2); }} public static (T1, T2, T3) Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3) {{ return (item1, item2, item3); }} public static (T1, T2, T3, T4) Create<T1, T2, T3, T4>(T1 item1, T2 item2, T3 item3, T4 item4) {{ return (item1, item2, item3, item4); }} public static (T1, T2, T3, T4, T5) Create<T1, T2, T3, T4, T5>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) {{ return (item1, item2, item3, item4, item5); }} public static (T1, T2, T3, T4, T5, T6) Create<T1, T2, T3, T4, T5, T6>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) {{ return (item1, item2, item3, item4, item5, item6); }} public static (T1, T2, T3, T4, T5, T6, T7) Create<T1, T2, T3, T4, T5, T6, T7>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) {{ return (item1, item2, item3, item4, item5, item6, item7); }} public static (T1, T2, T3, T4, T5, T6, T7, T8) Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8) {{ return new ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>>(item1, item2, item3, item4, item5, item6, item7, Create(item8)); }} internal static int CombineHashCodes(int h1, int h2) {{ return ((h1 << 5) + h1) ^ h2; }} internal static int CombineHashCodes(int h1, int h2, int h3) {{ return CombineHashCodes(CombineHashCodes(h1, h2), h3); }} internal static int CombineHashCodes(int h1, int h2, int h3, int h4) {{ return CombineHashCodes(CombineHashCodes(h1, h2), CombineHashCodes(h3, h4)); }} internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5) {{ return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), h5); }} internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6) {{ return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6)); }} internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7) {{ return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6, h7)); }} internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7, int h8) {{ return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6, h7, h8)); }} }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "System.Runtime, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")} {string.Format(CSharpEditorResources.WARN_Version_mismatch_Expected_0_Got_1, "4.0.0.0", "4.0.10.0")} {string.Format(CSharpEditorResources.Load_from_0, "System.Runtime.dll")} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "System.Resources.ResourceManager, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")} {string.Format(CSharpEditorResources.Could_not_find_by_name_0, "System.Resources.ResourceManager, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "System.Collections, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")} {string.Format(CSharpEditorResources.Could_not_find_by_name_0, "System.Collections, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "System.Core.v4_0_30319_17929.dll")} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "System.v4_6_1038_0.dll")} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "System.ComponentModel.Composition, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Could_not_find_by_name_0, "System.ComponentModel.Composition, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} #endif", }; await context.GenerateAndVerifySourceAsync("System.ValueTuple", expected, allowDecompilation: allowDecompilation); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestExtendedPartialMethod1(bool allowDecompilation) { var metadataSource = "public partial class C { public partial void F(); public partial void F() { } }"; var symbolName = "C"; var expected = allowDecompilation switch { false => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class [|C|] {{ public C(); public void F(); }}", true => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|C|] {{ public void F() {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, languageVersion: "Preview", metadataLanguageVersion: "Preview", expected: expected, allowDecompilation: allowDecompilation); } } } }
// Licensed to the .NET Foundation under one or more 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.Editor.CSharp; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.MetadataAsSource { public partial class MetadataAsSourceTests { public class CSharp : AbstractMetadataAsSourceTests { [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void ExtractXMLFromDocComment() { var docCommentText = @"/// <summary> /// I am the very model of a modern major general. /// </summary>"; var expectedXMLFragment = @" <summary> I am the very model of a modern major general. </summary>"; var extractedXMLFragment = DocumentationCommentUtilities.ExtractXMLFragment(docCommentText, "///"); Assert.Equal(expectedXMLFragment, extractedXMLFragment); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] [WorkItem(42986, "https://github.com/dotnet/roslyn/issues/42986")] public async Task TestNativeInteger(bool allowDecompilation) { var metadataSource = "public class C { public nint i; public nuint i2; }"; var symbolName = "C"; var expected = allowDecompilation switch { false => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class [|C|] {{ public nint i; public nuint i2; public C(); }}", true => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|C|] {{ public nint i; public nuint i2; }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, languageVersion: "Preview", metadataLanguageVersion: "Preview", expected: expected, allowDecompilation: allowDecompilation); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestInitOnlyProperty(bool allowDecompilation) { var metadataSource = @"public class C { public int Property { get; init; } } namespace System.Runtime.CompilerServices { public sealed class IsExternalInit { } } "; var symbolName = "C"; var expected = allowDecompilation switch { false => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class [|C|] {{ public C(); public int Property {{ get; init; }} }}", true => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|C|] {{ public int Property {{ get; set; }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, languageVersion: "Preview", metadataLanguageVersion: "Preview", expected: expected, allowDecompilation: allowDecompilation); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestTupleWithNames(bool allowDecompilation) { var metadataSource = "public class C { public (int a, int b) t; }"; var symbolName = "C"; var expected = allowDecompilation switch { false => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System.Runtime.CompilerServices; public class [|C|] {{ [TupleElementNames(new[] {{ ""a"", ""b"" }})] public (int a, int b) t; public C(); }}", true => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|C|] {{ public (int a, int b) t; }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51")} {string.Format(CSharpEditorResources.Load_from_0, "System.ValueTuple.dll")} #endif", }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, expected: expected, allowDecompilation: allowDecompilation); } [Theory, CombinatorialData, WorkItem(26605, "https://github.com/dotnet/roslyn/issues/26605")] public async Task TestValueTuple(bool allowDecompilation) { using var context = TestContext.Create(LanguageNames.CSharp); var expected = allowDecompilation switch { false => $@"#region {FeaturesResources.Assembly} System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51 // System.ValueTuple.dll #endregion using System.Collections; namespace System {{ public struct [|ValueTuple|] : IEquatable<ValueTuple>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple>, ITupleInternal {{ public static ValueTuple Create(); public static ValueTuple<T1> Create<T1>(T1 item1); public static (T1, T2) Create<T1, T2>(T1 item1, T2 item2); public static (T1, T2, T3) Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3); public static (T1, T2, T3, T4) Create<T1, T2, T3, T4>(T1 item1, T2 item2, T3 item3, T4 item4); public static (T1, T2, T3, T4, T5) Create<T1, T2, T3, T4, T5>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5); public static (T1, T2, T3, T4, T5, T6) Create<T1, T2, T3, T4, T5, T6>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6); public static (T1, T2, T3, T4, T5, T6, T7) Create<T1, T2, T3, T4, T5, T6, T7>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7); public static (T1, T2, T3, T4, T5, T6, T7, T8) Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8); public int CompareTo(ValueTuple other); public override bool Equals(object obj); public bool Equals(ValueTuple other); public override int GetHashCode(); public override string ToString(); }} }}", true => $@"#region {FeaturesResources.Assembly} System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51 // System.ValueTuple.dll // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion using System.Collections; using System.Runtime.InteropServices; namespace System {{ [StructLayout(LayoutKind.Sequential, Size = 1)] public struct [|ValueTuple|] : IEquatable<ValueTuple>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple>, ITupleInternal {{ int ITupleInternal.Size => 0; public override bool Equals(object obj) {{ return obj is ValueTuple; }} public bool Equals(ValueTuple other) {{ return true; }} bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) {{ return other is ValueTuple; }} int IComparable.CompareTo(object other) {{ if (other == null) {{ return 1; }} if (!(other is ValueTuple)) {{ throw new ArgumentException(SR.ArgumentException_ValueTupleIncorrectType, ""other""); }} return 0; }} public int CompareTo(ValueTuple other) {{ return 0; }} int IStructuralComparable.CompareTo(object other, IComparer comparer) {{ if (other == null) {{ return 1; }} if (!(other is ValueTuple)) {{ throw new ArgumentException(SR.ArgumentException_ValueTupleIncorrectType, ""other""); }} return 0; }} public override int GetHashCode() {{ return 0; }} int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) {{ return 0; }} int ITupleInternal.GetHashCode(IEqualityComparer comparer) {{ return 0; }} public override string ToString() {{ return ""()""; }} string ITupleInternal.ToStringEnd() {{ return "")""; }} public static ValueTuple Create() {{ return default(ValueTuple); }} public static ValueTuple<T1> Create<T1>(T1 item1) {{ return new ValueTuple<T1>(item1); }} public static (T1, T2) Create<T1, T2>(T1 item1, T2 item2) {{ return (item1, item2); }} public static (T1, T2, T3) Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3) {{ return (item1, item2, item3); }} public static (T1, T2, T3, T4) Create<T1, T2, T3, T4>(T1 item1, T2 item2, T3 item3, T4 item4) {{ return (item1, item2, item3, item4); }} public static (T1, T2, T3, T4, T5) Create<T1, T2, T3, T4, T5>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) {{ return (item1, item2, item3, item4, item5); }} public static (T1, T2, T3, T4, T5, T6) Create<T1, T2, T3, T4, T5, T6>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) {{ return (item1, item2, item3, item4, item5, item6); }} public static (T1, T2, T3, T4, T5, T6, T7) Create<T1, T2, T3, T4, T5, T6, T7>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) {{ return (item1, item2, item3, item4, item5, item6, item7); }} public static (T1, T2, T3, T4, T5, T6, T7, T8) Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8) {{ return new ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>>(item1, item2, item3, item4, item5, item6, item7, Create(item8)); }} internal static int CombineHashCodes(int h1, int h2) {{ return ((h1 << 5) + h1) ^ h2; }} internal static int CombineHashCodes(int h1, int h2, int h3) {{ return CombineHashCodes(CombineHashCodes(h1, h2), h3); }} internal static int CombineHashCodes(int h1, int h2, int h3, int h4) {{ return CombineHashCodes(CombineHashCodes(h1, h2), CombineHashCodes(h3, h4)); }} internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5) {{ return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), h5); }} internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6) {{ return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6)); }} internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7) {{ return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6, h7)); }} internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7, int h8) {{ return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6, h7, h8)); }} }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "System.Runtime, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")} {string.Format(CSharpEditorResources.WARN_Version_mismatch_Expected_0_Got_1, "4.0.0.0", "4.0.10.0")} {string.Format(CSharpEditorResources.Load_from_0, "System.Runtime.dll")} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "System.Resources.ResourceManager, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")} {string.Format(CSharpEditorResources.Could_not_find_by_name_0, "System.Resources.ResourceManager, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "System.Collections, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")} {string.Format(CSharpEditorResources.Could_not_find_by_name_0, "System.Collections, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "System.Core.v4_0_30319_17929.dll")} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "System.v4_6_1038_0.dll")} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "System.ComponentModel.Composition, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Could_not_find_by_name_0, "System.ComponentModel.Composition, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} #endif", }; await context.GenerateAndVerifySourceAsync("System.ValueTuple", expected, allowDecompilation: allowDecompilation); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task TestExtendedPartialMethod1(bool allowDecompilation) { var metadataSource = "public partial class C { public partial void F(); public partial void F() { } }"; var symbolName = "C"; var expected = allowDecompilation switch { false => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class [|C|] {{ public C(); public void F(); }}", true => $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} // Decompiled with ICSharpCode.Decompiler 6.1.0.5902 #endregion public class [|C|] {{ public void F() {{ }} }} #if false // {CSharpEditorResources.Decompilation_log} {string.Format(CSharpEditorResources._0_items_in_cache, 6)} ------------------ {string.Format(CSharpEditorResources.Resolve_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Found_single_assembly_0, "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")} {string.Format(CSharpEditorResources.Load_from_0, "mscorlib.v4_6_1038_0.dll")} #endif", }; await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.CSharp, languageVersion: "Preview", metadataLanguageVersion: "Preview", expected: expected, allowDecompilation: allowDecompilation); } } } }
-1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/Symbols/InterfaceOverriddenOrHiddenMembersTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.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.Symbols { /// <summary> /// Test interface member hiding. /// </summary> public class InterfaceOverriddenOrHiddenMembersTests : CSharpTestBase { [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void Repro581173() { var source = @" interface I3 { int goo { get; set; } } interface I1 : I3 { } interface I2 : I3 { new void goo(); } interface I0 : I1, I2 { new void goo(int x); } "; CreateCompilation(source).VerifyDiagnostics( // (13,14): warning CS0109: The member 'I0.goo(int)' does not hide an accessible member. The new keyword is not required. // new void goo(int x); Diagnostic(ErrorCode.WRN_NewNotRequired, "goo").WithArguments("I0.goo(int)")); } /// <summary> /// For this series of tests, we're going to use a fixed type hierarchy and a single member signature "void M()". /// We will start with the signature in all interfaces, and then remove it from various subsets. /// /// ITop /// / \ /// ILeft IRight /// \ / /// IBottom /// /// All have method. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Method_1() { var source = @" public interface ITop { void M(); } public interface ILeft : ITop { void M(); } public interface IRight : ITop { void M(); } public interface IBottom : ILeft, IRight { void M(); } "; CreateCompilation(source).VerifyDiagnostics( // (9,10): warning CS0108: 'ILeft.M()' hides inherited member 'ITop.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("ILeft.M()", "ITop.M()"), // (14,10): warning CS0108: 'IRight.M()' hides inherited member 'ITop.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IRight.M()", "ITop.M()"), // (19,10): warning CS0108: 'IBottom.M()' hides inherited member 'ILeft.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IBottom.M()", "ILeft.M()")); } /// <summary> /// All have method but IRight. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Method_2() { var source = @" public interface ITop { void M(); } public interface ILeft : ITop { void M(); } public interface IRight : ITop { // void M(); } public interface IBottom : ILeft, IRight { void M(); } "; CreateCompilation(source).VerifyDiagnostics( // (9,10): warning CS0108: 'ILeft.M()' hides inherited member 'ITop.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("ILeft.M()", "ITop.M()"), // (19,10): warning CS0108: 'IBottom.M()' hides inherited member 'ILeft.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IBottom.M()", "ILeft.M()")); } /// <summary> /// All have method but ILeft and IRight. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Method_3() { var source = @" public interface ITop { void M(); } public interface ILeft : ITop { // void M(); } public interface IRight : ITop { // void M(); } public interface IBottom : ILeft, IRight { void M(); } "; CreateCompilation(source).VerifyDiagnostics( // (19,10): warning CS0108: 'IBottom.M()' hides inherited member 'ITop.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IBottom.M()", "ITop.M()")); } /// <summary> /// All have method but ITop. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Method_4() { var source = @" public interface ITop { // void M(); } public interface ILeft : ITop { void M(); } public interface IRight : ITop { void M(); } public interface IBottom : ILeft, IRight { void M(); } "; // Also hides IRight.M, but not reported. CreateCompilation(source).VerifyDiagnostics( // (19,10): warning CS0108: 'IBottom.M()' hides inherited member 'ILeft.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IBottom.M()", "ILeft.M()")); } /// <summary> /// All have method but ITop and IRight. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Method_5() { var source = @" public interface ITop { // void M(); } public interface ILeft : ITop { void M(); } public interface IRight : ITop { // void M(); } public interface IBottom : ILeft, IRight { void M(); } "; CreateCompilation(source).VerifyDiagnostics( // (19,10): warning CS0108: 'IBottom.M()' hides inherited member 'ILeft.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IBottom.M()", "ILeft.M()")); } /// <summary> /// These tests are the same as the TestDiamond_Method tests except that, instead of removing the method /// from some interfaces, we'll change its parameter list in those interfaces. /// /// ITop /// / \ /// ILeft IRight /// \ / /// IBottom /// /// All have unmodified method. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Overload_1() { // Identical to TestDiamond_Method_1, so omitted. } /// <summary> /// All have unmodified method but IRight. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Overload_2() { var source = @" public interface ITop { void M(); } public interface ILeft : ITop { void M(); } public interface IRight : ITop { void M(int x); } public interface IBottom : ILeft, IRight { void M(); } "; CreateCompilation(source).VerifyDiagnostics( // (9,10): warning CS0108: 'ILeft.M()' hides inherited member 'ITop.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("ILeft.M()", "ITop.M()"), // (19,10): warning CS0108: 'IBottom.M()' hides inherited member 'ILeft.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IBottom.M()", "ILeft.M()")); } /// <summary> /// All have unmodified method but ILeft and IRight. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Overload_3() { var source = @" public interface ITop { void M(); } public interface ILeft : ITop { void M(int x); } public interface IRight : ITop { void M(int x); } public interface IBottom : ILeft, IRight { void M(); } "; CreateCompilation(source).VerifyDiagnostics( // (19,10): warning CS0108: 'IBottom.M()' hides inherited member 'ITop.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IBottom.M()", "ITop.M()")); } /// <summary> /// All have unmodified method but ITop. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Overload_4() { var source = @" public interface ITop { void M(int x); } public interface ILeft : ITop { void M(); } public interface IRight : ITop { void M(); } public interface IBottom : ILeft, IRight { void M(); } "; // Also hides IRight.M, but not reported. CreateCompilation(source).VerifyDiagnostics( // (19,10): warning CS0108: 'IBottom.M()' hides inherited member 'ILeft.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IBottom.M()", "ILeft.M()")); } /// <summary> /// All have unmodified method but ITop and IRight. /// Unlike the other TestDiamond_Overload tests, this one reports different diagnostics than its TestDiamond_Method counterpart. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Overload_5() { var source = @" public interface ITop { void M(int x); } public interface ILeft : ITop { void M(); } public interface IRight : ITop { void M(int x); } public interface IBottom : ILeft, IRight { void M(); } "; CreateCompilation(source).VerifyDiagnostics( // (19,10): warning CS0108: 'IBottom.M()' hides inherited member 'ILeft.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IBottom.M()", "ILeft.M()"), // (14,10): warning CS0108: 'IRight.M(int)' hides inherited member 'ITop.M(int)'. Use the new keyword if hiding was intended. // void M(int x); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IRight.M(int)", "ITop.M(int)")); } /// <summary> /// These tests are the same as the TestDiamond_Method tests except that, instead of removing the method /// from some interfaces, we'll change its type parameter list in those interfaces. /// /// ITop /// / \ /// ILeft IRight /// \ / /// IBottom /// /// All have unmodified method. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Arity_1() { // Identical to TestDiamond_Method_1, so omitted. } /// <summary> /// All have unmodified method but IRight. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Arity_2() { var source = @" public interface ITop { void M(); } public interface ILeft : ITop { void M(); } public interface IRight : ITop { void M<T>(); } public interface IBottom : ILeft, IRight { void M(); } "; CreateCompilation(source).VerifyDiagnostics( // (9,10): warning CS0108: 'ILeft.M()' hides inherited member 'ITop.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("ILeft.M()", "ITop.M()"), // (19,10): warning CS0108: 'IBottom.M()' hides inherited member 'ILeft.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IBottom.M()", "ILeft.M()")); } /// <summary> /// All have unmodified method but ILeft and IRight. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Arity_3() { var source = @" public interface ITop { void M(); } public interface ILeft : ITop { void M<T>(); } public interface IRight : ITop { void M<T>(); } public interface IBottom : ILeft, IRight { void M(); } "; CreateCompilation(source).VerifyDiagnostics( // (19,10): warning CS0108: 'IBottom.M()' hides inherited member 'ITop.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IBottom.M()", "ITop.M()")); } /// <summary> /// All have unmodified method but ITop. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Arity_4() { var source = @" public interface ITop { void M<T>(); } public interface ILeft : ITop { void M(); } public interface IRight : ITop { void M(); } public interface IBottom : ILeft, IRight { void M(); } "; // Also hides IRight.M, but not reported. CreateCompilation(source).VerifyDiagnostics( // (19,10): warning CS0108: 'IBottom.M()' hides inherited member 'ILeft.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IBottom.M()", "ILeft.M()")); } /// <summary> /// All have unmodified method but ITop and IRight. /// Unlike the other TestDiamond_Overload tests, this one reports different diagnostics than its TestDiamond_Method counterpart. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Arity_5() { var source = @" public interface ITop { void M<T>(); } public interface ILeft : ITop { void M(); } public interface IRight : ITop { void M<T>(); } public interface IBottom : ILeft, IRight { void M(); } "; CreateCompilation(source).VerifyDiagnostics( // (19,10): warning CS0108: 'IBottom.M()' hides inherited member 'ILeft.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IBottom.M()", "ILeft.M()"), // (14,10): warning CS0108: 'IRight.M<T>()' hides inherited member 'ITop.M<T>()'. Use the new keyword if hiding was intended. // void M<T>(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IRight.M<T>()", "ITop.M<T>()")); } /// <summary> /// These tests are the same as the TestDiamond_Method tests except that, instead of removing the method /// from some interfaces, we'll change its member kind (to Property) in those interfaces. /// /// ITop /// / \ /// ILeft IRight /// \ / /// IBottom /// /// All have unmodified method. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Kind_1() { // Identical to TestDiamond_Method_1, so omitted. } /// <summary> /// All have unmodified method but IRight. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Kind_2() { var source = @" public interface ITop { void M(); } public interface ILeft : ITop { void M(); } public interface IRight : ITop { int M { get; set; } } public interface IBottom : ILeft, IRight { void M(); } "; CreateCompilation(source).VerifyDiagnostics( // (9,10): warning CS0108: 'ILeft.M()' hides inherited member 'ITop.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("ILeft.M()", "ITop.M()"), // (19,10): warning CS0108: 'IBottom.M()' hides inherited member 'ILeft.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IBottom.M()", "ILeft.M()"), // (14,9): warning CS0108: 'IRight.M' hides inherited member 'ITop.M()'. Use the new keyword if hiding was intended. // int M { get; set; } Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IRight.M", "ITop.M()")); } /// <summary> /// All have unmodified method but ILeft and IRight. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Kind_3() { var source = @" public interface ITop { void M(); } public interface ILeft : ITop { int M { get; set; } } public interface IRight : ITop { int M { get; set; } } public interface IBottom : ILeft, IRight { void M(); } "; CreateCompilation(source).VerifyDiagnostics( // (19,10): warning CS0108: 'IBottom.M()' hides inherited member 'ILeft.M'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IBottom.M()", "ILeft.M"), // (9,9): warning CS0108: 'ILeft.M' hides inherited member 'ITop.M()'. Use the new keyword if hiding was intended. // int M { get; set; } Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("ILeft.M", "ITop.M()"), // (14,9): warning CS0108: 'IRight.M' hides inherited member 'ITop.M()'. Use the new keyword if hiding was intended. // int M { get; set; } Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IRight.M", "ITop.M()")); } /// <summary> /// All have unmodified method but ITop. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Kind_4() { var source = @" public interface ITop { int M { get; set; } } public interface ILeft : ITop { void M(); } public interface IRight : ITop { void M(); } public interface IBottom : ILeft, IRight { void M(); } "; // Also hides IRight.M, but not reported. CreateCompilation(source).VerifyDiagnostics( // (14,10): warning CS0108: 'IRight.M()' hides inherited member 'ITop.M'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IRight.M()", "ITop.M"), // (9,10): warning CS0108: 'ILeft.M()' hides inherited member 'ITop.M'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("ILeft.M()", "ITop.M"), // (19,10): warning CS0108: 'IBottom.M()' hides inherited member 'ILeft.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IBottom.M()", "ILeft.M()")); } /// <summary> /// All have unmodified method but ITop and IRight. /// Unlike the other TestDiamond_Overload tests, this one reports different diagnostics than its TestDiamond_Method counterpart. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Kind_5() { var source = @" public interface ITop { int M { get; set; } } public interface ILeft : ITop { void M(); } public interface IRight : ITop { int M { get; set; } } public interface IBottom : ILeft, IRight { void M(); } "; CreateCompilation(source).VerifyDiagnostics( // (14,9): warning CS0108: 'IRight.M' hides inherited member 'ITop.M'. Use the new keyword if hiding was intended. // int M { get; set; } Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IRight.M", "ITop.M"), // (19,10): warning CS0108: 'IBottom.M()' hides inherited member 'ILeft.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IBottom.M()", "ILeft.M()"), // (9,10): warning CS0108: 'ILeft.M()' hides inherited member 'ITop.M'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("ILeft.M()", "ITop.M")); } [Fact] [WorkItem(661370, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/661370")] public void HideAndOverride() { var source = @" public interface Base { void M(); int M { get; set; } // NOTE: illegal, since there's already a method M. } public interface Derived1 : Base { void M(); } public interface Derived2 : Base { int M { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,9): error CS0102: The type 'Base' already contains a definition for 'M' // int M { get; set; } // NOTE: illegal, since there's already a method M. Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "M").WithArguments("Base", "M"), // (15,10): warning CS0108: 'Derived2.M' hides inherited member 'Base.M'. Use the new keyword if hiding was intended. // int M { get; set; } Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("Derived2.M", "Base.M"), // (10,11): warning CS0108: 'Derived1.M()' hides inherited member 'Base.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("Derived1.M()", "Base.M()")); var global = comp.GlobalNamespace; var baseInterface = global.GetMember<NamedTypeSymbol>("Base"); var baseMethod = baseInterface.GetMembers("M").OfType<MethodSymbol>().Single(); var baseProperty = baseInterface.GetMembers("M").OfType<PropertySymbol>().Single(); var derivedInterface1 = global.GetMember<NamedTypeSymbol>("Derived1"); var derivedMethod = derivedInterface1.GetMember<MethodSymbol>("M"); var overriddenOrHidden1 = derivedMethod.OverriddenOrHiddenMembers; AssertEx.SetEqual(overriddenOrHidden1.HiddenMembers, baseMethod, baseProperty); var derivedInterface2 = global.GetMember<NamedTypeSymbol>("Derived2"); var derivedProperty = derivedInterface2.GetMember<PropertySymbol>("M"); var overriddenOrHidden2 = derivedProperty.OverriddenOrHiddenMembers; AssertEx.SetEqual(overriddenOrHidden2.HiddenMembers, baseMethod, baseProperty); } [Fact] [WorkItem(667278, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/667278")] public void FalseIdentificationOfCircularDependency() { var source = @" public class ITest : ITest.Test{ public interface Test { } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void HidingMethodWithInParameter() { var code = @" interface A { void M(in int x); } interface B : A { void M(in int x); }"; var comp = CreateCompilation(code).VerifyDiagnostics( // (8,10): warning CS0108: 'B.M(in int)' hides inherited member 'A.M(in int)'. Use the new keyword if hiding was intended. // void M(in int x); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("B.M(in int)", "A.M(in int)").WithLocation(8, 10)); var aMethod = comp.GetMember<MethodSymbol>("A.M"); var bMethod = comp.GetMember<MethodSymbol>("B.M"); Assert.Empty(aMethod.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Empty(aMethod.OverriddenOrHiddenMembers.HiddenMembers); Assert.Empty(bMethod.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Equal(aMethod, bMethod.OverriddenOrHiddenMembers.HiddenMembers.Single()); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void HidingMethodWithRefReadOnlyReturnType_RefReadOnly_RefReadOnly() { var code = @" interface A { ref readonly int M(); } interface B : A { ref readonly int M(); }"; var comp = CreateCompilation(code).VerifyDiagnostics( // (8,22): warning CS0108: 'B.M()' hides inherited member 'A.M()'. Use the new keyword if hiding was intended. // ref readonly int M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("B.M()", "A.M()").WithLocation(8, 22)); var aMethod = comp.GetMember<MethodSymbol>("A.M"); var bMethod = comp.GetMember<MethodSymbol>("B.M"); Assert.Empty(aMethod.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Empty(aMethod.OverriddenOrHiddenMembers.HiddenMembers); Assert.Empty(bMethod.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Equal(aMethod, bMethod.OverriddenOrHiddenMembers.HiddenMembers.Single()); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void HidingMethodWithRefReadOnlyReturnType_Ref_RefReadOnly() { var code = @" interface A { ref int M(); } interface B : A { ref readonly int M(); }"; var comp = CreateCompilation(code).VerifyDiagnostics( // (8,22): warning CS0108: 'B.M()' hides inherited member 'A.M()'. Use the new keyword if hiding was intended. // ref readonly int M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("B.M()", "A.M()").WithLocation(8, 22)); var aMethod = comp.GetMember<MethodSymbol>("A.M"); var bMethod = comp.GetMember<MethodSymbol>("B.M"); Assert.Empty(aMethod.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Empty(aMethod.OverriddenOrHiddenMembers.HiddenMembers); Assert.Empty(bMethod.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Equal(aMethod, bMethod.OverriddenOrHiddenMembers.HiddenMembers.Single()); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void HidingMethodWithRefReadOnlyReturnType_RefReadOnly_Ref() { var code = @" interface A { ref readonly int M(); } interface B : A { ref int M(); }"; var comp = CreateCompilation(code).VerifyDiagnostics( // (8,13): warning CS0108: 'B.M()' hides inherited member 'A.M()'. Use the new keyword if hiding was intended. // ref readonly int M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("B.M()", "A.M()").WithLocation(8, 13)); var aMethod = comp.GetMember<MethodSymbol>("A.M"); var bMethod = comp.GetMember<MethodSymbol>("B.M"); Assert.Empty(aMethod.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Empty(aMethod.OverriddenOrHiddenMembers.HiddenMembers); Assert.Empty(bMethod.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Equal(aMethod, bMethod.OverriddenOrHiddenMembers.HiddenMembers.Single()); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void HidingPropertyWithRefReadOnlyReturnType_RefReadonly_RefReadonly() { var code = @" interface A { ref readonly int Property { get; } } interface B : A { ref readonly int Property { get; } }"; var comp = CreateCompilation(code).VerifyDiagnostics( // (8,22): warning CS0108: 'B.Property' hides inherited member 'A.Property'. Use the new keyword if hiding was intended. // ref readonly int Property { get; } Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("B.Property", "A.Property").WithLocation(8, 22)); var aProperty = comp.GetMember<PropertySymbol>("A.Property"); var bProperty = comp.GetMember<PropertySymbol>("B.Property"); Assert.Empty(aProperty.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Empty(aProperty.OverriddenOrHiddenMembers.HiddenMembers); Assert.Empty(bProperty.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Equal(aProperty, bProperty.OverriddenOrHiddenMembers.HiddenMembers.Single()); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void HidingPropertyWithRefReadOnlyReturnType_RefReadonly_Ref() { var code = @" interface A { ref readonly int Property { get; } } interface B : A { ref int Property { get; } }"; var comp = CreateCompilation(code).VerifyDiagnostics( // (8,13): warning CS0108: 'B.Property' hides inherited member 'A.Property'. Use the new keyword if hiding was intended. // ref int Property { get; } Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("B.Property", "A.Property").WithLocation(8, 13)); var aProperty = comp.GetMember<PropertySymbol>("A.Property"); var bProperty = comp.GetMember<PropertySymbol>("B.Property"); Assert.Empty(aProperty.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Empty(aProperty.OverriddenOrHiddenMembers.HiddenMembers); Assert.Empty(bProperty.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Equal(aProperty, bProperty.OverriddenOrHiddenMembers.HiddenMembers.Single()); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void HidingPropertyWithRefReadOnlyReturnType_Ref_RefReadonly() { var code = @" interface A { ref int Property { get; } } interface B : A { ref readonly int Property { get; } }"; var comp = CreateCompilation(code).VerifyDiagnostics( // (8,22): warning CS0108: 'B.Property' hides inherited member 'A.Property'. Use the new keyword if hiding was intended. // ref readonly int Property { get; } Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("B.Property", "A.Property").WithLocation(8, 22)); var aProperty = comp.GetMember<PropertySymbol>("A.Property"); var bProperty = comp.GetMember<PropertySymbol>("B.Property"); Assert.Empty(aProperty.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Empty(aProperty.OverriddenOrHiddenMembers.HiddenMembers); Assert.Empty(bProperty.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Equal(aProperty, bProperty.OverriddenOrHiddenMembers.HiddenMembers.Single()); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void HidingMethodWithInParameterAndNewKeyword() { var code = @" interface A { void M(in int x); } interface B : A { new void M(in int x); }"; var comp = CreateCompilation(code).VerifyDiagnostics(); var aMethod = comp.GetMember<MethodSymbol>("A.M"); var bMethod = comp.GetMember<MethodSymbol>("B.M"); Assert.Empty(aMethod.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Empty(aMethod.OverriddenOrHiddenMembers.HiddenMembers); Assert.Empty(bMethod.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Equal(aMethod, bMethod.OverriddenOrHiddenMembers.HiddenMembers.Single()); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void HidingMethodWithRefReadOnlyReturnTypeAndNewKeyword() { var code = @" interface A { ref readonly int M(); } interface B : A { new ref readonly int M(); }"; var comp = CreateCompilation(code).VerifyDiagnostics(); var aMethod = comp.GetMember<MethodSymbol>("A.M"); var bMethod = comp.GetMember<MethodSymbol>("B.M"); Assert.Empty(aMethod.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Empty(aMethod.OverriddenOrHiddenMembers.HiddenMembers); Assert.Empty(bMethod.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Equal(aMethod, bMethod.OverriddenOrHiddenMembers.HiddenMembers.Single()); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void HidingPropertyWithRefReadOnlyReturnTypeAndNewKeyword() { var code = @" interface A { ref readonly int Property { get ; } } interface B : A { new ref readonly int Property { get; } }"; var comp = CreateCompilation(code).VerifyDiagnostics(); var aProperty = comp.GetMember<PropertySymbol>("A.Property"); var bProperty = comp.GetMember<PropertySymbol>("B.Property"); Assert.Empty(aProperty.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Empty(aProperty.OverriddenOrHiddenMembers.HiddenMembers); Assert.Empty(bProperty.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Equal(aProperty, bProperty.OverriddenOrHiddenMembers.HiddenMembers.Single()); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void ImplementingMethodWithInParameter() { var code = @" interface A { void M(in int x); } class B : A { public void M(in int x) { } }"; var comp = CreateCompilation(code).VerifyDiagnostics(); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void ImplementingMethodWithRefReadOnlyReturnType() { var code = @" interface A { ref readonly int M(); } class B : A { protected int x = 0; public ref readonly int M() { return ref x; } }"; var comp = CreateCompilation(code).VerifyDiagnostics(); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void ImplementingPropertyWithRefReadOnlyReturnType() { var code = @" interface A { ref readonly int Property { get; } } class B : A { protected int x = 0; public ref readonly int Property { get { return ref x; } } }"; var comp = CreateCompilation(code).VerifyDiagnostics(); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void ImplementingMethodWithDifferentParameterRefness() { var code = @" interface A { void M(in int x); } class B : A { public void M(ref int x) { } }"; var comp = CreateCompilation(code).VerifyDiagnostics( // (6,11): error CS0535: 'B' does not implement interface member 'A.M(in int)' // class B : A Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "A").WithArguments("B", "A.M(in int)").WithLocation(6, 11)); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void ImplementingRefReadOnlyMembersWillOverwriteTheCorrectSlot() { var text = @" interface BaseInterface { ref readonly int Method1(in int a); ref readonly int Property1 { get; } ref readonly int this[int a] { get; } } class DerivedClass : BaseInterface { protected int field; public ref readonly int Method1(in int a) { return ref field; } public ref readonly int Property1 { get { return ref field; } } public ref readonly int this[int a] { get { return ref field; } } }"; var comp = CreateCompilation(text).VerifyDiagnostics(); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void MethodImplementationsShouldPreserveRefKindInParameters() { var text = @" interface BaseInterface { void Method1(ref int x); void Method2(in int x); } class ChildClass : BaseInterface { public void Method1(in int x) { } public void Method2(ref int x) { } }"; var comp = CreateCompilation(text).VerifyDiagnostics( // (7,20): error CS0535: 'ChildClass' does not implement interface member 'BaseInterface.Method2(in int)' // class ChildClass : BaseInterface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "BaseInterface").WithArguments("ChildClass", "BaseInterface.Method2(in int)").WithLocation(7, 20), // (7,20): error CS0535: 'ChildClass' does not implement interface member 'BaseInterface.Method1(ref int)' // class ChildClass : BaseInterface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "BaseInterface").WithArguments("ChildClass", "BaseInterface.Method1(ref int)").WithLocation(7, 20)); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void MethodImplementationsShouldPreserveReadOnlyRefnessInReturnTypes() { var text = @" interface BaseInterface { ref int Method1(); ref readonly int Method2(); } class ChildClass : BaseInterface { protected int x = 0 ; public ref readonly int Method1() { return ref x; } public ref int Method2() { return ref x; } }"; var comp = CreateCompilation(text).VerifyDiagnostics( // (7,20): error CS8152: 'ChildClass' does not implement interface member 'BaseInterface.Method2()'. 'ChildClass.Method2()' cannot implement 'BaseInterface.Method2()' because it does not have matching return by reference. // class ChildClass : BaseInterface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongRefReturn, "BaseInterface").WithArguments("ChildClass", "BaseInterface.Method2()", "ChildClass.Method2()").WithLocation(7, 20), // (7,20): error CS8152: 'ChildClass' does not implement interface member 'BaseInterface.Method1()'. 'ChildClass.Method1()' cannot implement 'BaseInterface.Method1()' because it does not have matching return by reference. // class ChildClass : BaseInterface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongRefReturn, "BaseInterface").WithArguments("ChildClass", "BaseInterface.Method1()", "ChildClass.Method1()").WithLocation(7, 20)); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void PropertyImplementationsShouldPreserveReadOnlyRefnessInReturnTypes() { var code = @" interface A { ref int Property1 { get; } ref readonly int Property2 { get; } } class B : A { protected int x = 0; public ref readonly int Property1 { get { return ref x; } } public ref int Property2 { get { return ref x; } } }"; var comp = CreateCompilation(code).VerifyDiagnostics( // (7,11): error CS8152: 'B' does not implement interface member 'A.Property2'. 'B.Property2' cannot implement 'A.Property2' because it does not have matching return by reference. // class B : A Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongRefReturn, "A").WithArguments("B", "A.Property2", "B.Property2").WithLocation(7, 11), // (7,11): error CS8152: 'B' does not implement interface member 'A.Property1'. 'B.Property1' cannot implement 'A.Property1' because it does not have matching return by reference. // class B : A Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongRefReturn, "A").WithArguments("B", "A.Property1", "B.Property1").WithLocation(7, 11)); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void IndexerImplementationsShouldPreserveReadOnlyRefnessInReturnTypes_Ref_RefReadOnly() { var code = @" interface A { ref int this[int p] { get; } } class B : A { protected int x = 0; public ref readonly int this[int p] { get { return ref x; } } }"; var comp = CreateCompilation(code).VerifyDiagnostics( // (6,11): error CS8152: 'B' does not implement interface member 'A.this[int]'. 'B.this[int]' cannot implement 'A.this[int]' because it does not have matching return by reference. // class B : A Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongRefReturn, "A").WithArguments("B", "A.this[int]", "B.this[int]").WithLocation(6, 11)); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void IndexerImplementationsShouldPreserveReadOnlyRefnessInReturnTypes_RefReadOnly_Ref() { var code = @" interface A { ref readonly int this[int p] { get; } } class B : A { protected int x = 0; public ref int this[int p] { get { return ref x; } } }"; var comp = CreateCompilation(code).VerifyDiagnostics( // (6,11): error CS8152: 'B' does not implement interface member 'A.this[int]'. 'B.this[int]' cannot implement 'A.this[int]' because it does not have matching return by reference. // class B : A Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongRefReturn, "A").WithArguments("B", "A.this[int]", "B.this[int]").WithLocation(6, 11)); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void IndexerImplementationsShouldPreserveReadOnlyRefnessInIndexes_Valid() { var code = @" interface A { int this[in int p] { get; } } class B : A { public int this[in int p] { get { return p; } } }"; var comp = CreateCompilation(code).VerifyDiagnostics(); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void IndexerImplementationsShouldPreserveReadOnlyRefnessInIndexes_Source() { var code = @" interface A { int this[in int p] { get; } } class B : A { public int this[int p] { get { return p; } } }"; var comp = CreateCompilation(code).VerifyDiagnostics( // (6,11): error CS0535: 'B' does not implement interface member 'A.this[in int]' // class B : A Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "A").WithArguments("B", "A.this[in int]").WithLocation(6, 11)); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void IndexerImplementationsShouldPreserveReadOnlyRefnessInIndexes_Destination() { var code = @" interface A { int this[int p] { get; } } class B : A { public int this[in int p] { get { return p; } } }"; var comp = CreateCompilation(code).VerifyDiagnostics( // (6,11): error CS0535: 'B' does not implement interface member 'A.this[int]' // class B : A Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "A").WithArguments("B", "A.this[int]").WithLocation(6, 11)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.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.Symbols { /// <summary> /// Test interface member hiding. /// </summary> public class InterfaceOverriddenOrHiddenMembersTests : CSharpTestBase { [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void Repro581173() { var source = @" interface I3 { int goo { get; set; } } interface I1 : I3 { } interface I2 : I3 { new void goo(); } interface I0 : I1, I2 { new void goo(int x); } "; CreateCompilation(source).VerifyDiagnostics( // (13,14): warning CS0109: The member 'I0.goo(int)' does not hide an accessible member. The new keyword is not required. // new void goo(int x); Diagnostic(ErrorCode.WRN_NewNotRequired, "goo").WithArguments("I0.goo(int)")); } /// <summary> /// For this series of tests, we're going to use a fixed type hierarchy and a single member signature "void M()". /// We will start with the signature in all interfaces, and then remove it from various subsets. /// /// ITop /// / \ /// ILeft IRight /// \ / /// IBottom /// /// All have method. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Method_1() { var source = @" public interface ITop { void M(); } public interface ILeft : ITop { void M(); } public interface IRight : ITop { void M(); } public interface IBottom : ILeft, IRight { void M(); } "; CreateCompilation(source).VerifyDiagnostics( // (9,10): warning CS0108: 'ILeft.M()' hides inherited member 'ITop.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("ILeft.M()", "ITop.M()"), // (14,10): warning CS0108: 'IRight.M()' hides inherited member 'ITop.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IRight.M()", "ITop.M()"), // (19,10): warning CS0108: 'IBottom.M()' hides inherited member 'ILeft.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IBottom.M()", "ILeft.M()")); } /// <summary> /// All have method but IRight. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Method_2() { var source = @" public interface ITop { void M(); } public interface ILeft : ITop { void M(); } public interface IRight : ITop { // void M(); } public interface IBottom : ILeft, IRight { void M(); } "; CreateCompilation(source).VerifyDiagnostics( // (9,10): warning CS0108: 'ILeft.M()' hides inherited member 'ITop.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("ILeft.M()", "ITop.M()"), // (19,10): warning CS0108: 'IBottom.M()' hides inherited member 'ILeft.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IBottom.M()", "ILeft.M()")); } /// <summary> /// All have method but ILeft and IRight. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Method_3() { var source = @" public interface ITop { void M(); } public interface ILeft : ITop { // void M(); } public interface IRight : ITop { // void M(); } public interface IBottom : ILeft, IRight { void M(); } "; CreateCompilation(source).VerifyDiagnostics( // (19,10): warning CS0108: 'IBottom.M()' hides inherited member 'ITop.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IBottom.M()", "ITop.M()")); } /// <summary> /// All have method but ITop. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Method_4() { var source = @" public interface ITop { // void M(); } public interface ILeft : ITop { void M(); } public interface IRight : ITop { void M(); } public interface IBottom : ILeft, IRight { void M(); } "; // Also hides IRight.M, but not reported. CreateCompilation(source).VerifyDiagnostics( // (19,10): warning CS0108: 'IBottom.M()' hides inherited member 'ILeft.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IBottom.M()", "ILeft.M()")); } /// <summary> /// All have method but ITop and IRight. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Method_5() { var source = @" public interface ITop { // void M(); } public interface ILeft : ITop { void M(); } public interface IRight : ITop { // void M(); } public interface IBottom : ILeft, IRight { void M(); } "; CreateCompilation(source).VerifyDiagnostics( // (19,10): warning CS0108: 'IBottom.M()' hides inherited member 'ILeft.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IBottom.M()", "ILeft.M()")); } /// <summary> /// These tests are the same as the TestDiamond_Method tests except that, instead of removing the method /// from some interfaces, we'll change its parameter list in those interfaces. /// /// ITop /// / \ /// ILeft IRight /// \ / /// IBottom /// /// All have unmodified method. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Overload_1() { // Identical to TestDiamond_Method_1, so omitted. } /// <summary> /// All have unmodified method but IRight. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Overload_2() { var source = @" public interface ITop { void M(); } public interface ILeft : ITop { void M(); } public interface IRight : ITop { void M(int x); } public interface IBottom : ILeft, IRight { void M(); } "; CreateCompilation(source).VerifyDiagnostics( // (9,10): warning CS0108: 'ILeft.M()' hides inherited member 'ITop.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("ILeft.M()", "ITop.M()"), // (19,10): warning CS0108: 'IBottom.M()' hides inherited member 'ILeft.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IBottom.M()", "ILeft.M()")); } /// <summary> /// All have unmodified method but ILeft and IRight. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Overload_3() { var source = @" public interface ITop { void M(); } public interface ILeft : ITop { void M(int x); } public interface IRight : ITop { void M(int x); } public interface IBottom : ILeft, IRight { void M(); } "; CreateCompilation(source).VerifyDiagnostics( // (19,10): warning CS0108: 'IBottom.M()' hides inherited member 'ITop.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IBottom.M()", "ITop.M()")); } /// <summary> /// All have unmodified method but ITop. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Overload_4() { var source = @" public interface ITop { void M(int x); } public interface ILeft : ITop { void M(); } public interface IRight : ITop { void M(); } public interface IBottom : ILeft, IRight { void M(); } "; // Also hides IRight.M, but not reported. CreateCompilation(source).VerifyDiagnostics( // (19,10): warning CS0108: 'IBottom.M()' hides inherited member 'ILeft.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IBottom.M()", "ILeft.M()")); } /// <summary> /// All have unmodified method but ITop and IRight. /// Unlike the other TestDiamond_Overload tests, this one reports different diagnostics than its TestDiamond_Method counterpart. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Overload_5() { var source = @" public interface ITop { void M(int x); } public interface ILeft : ITop { void M(); } public interface IRight : ITop { void M(int x); } public interface IBottom : ILeft, IRight { void M(); } "; CreateCompilation(source).VerifyDiagnostics( // (19,10): warning CS0108: 'IBottom.M()' hides inherited member 'ILeft.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IBottom.M()", "ILeft.M()"), // (14,10): warning CS0108: 'IRight.M(int)' hides inherited member 'ITop.M(int)'. Use the new keyword if hiding was intended. // void M(int x); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IRight.M(int)", "ITop.M(int)")); } /// <summary> /// These tests are the same as the TestDiamond_Method tests except that, instead of removing the method /// from some interfaces, we'll change its type parameter list in those interfaces. /// /// ITop /// / \ /// ILeft IRight /// \ / /// IBottom /// /// All have unmodified method. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Arity_1() { // Identical to TestDiamond_Method_1, so omitted. } /// <summary> /// All have unmodified method but IRight. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Arity_2() { var source = @" public interface ITop { void M(); } public interface ILeft : ITop { void M(); } public interface IRight : ITop { void M<T>(); } public interface IBottom : ILeft, IRight { void M(); } "; CreateCompilation(source).VerifyDiagnostics( // (9,10): warning CS0108: 'ILeft.M()' hides inherited member 'ITop.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("ILeft.M()", "ITop.M()"), // (19,10): warning CS0108: 'IBottom.M()' hides inherited member 'ILeft.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IBottom.M()", "ILeft.M()")); } /// <summary> /// All have unmodified method but ILeft and IRight. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Arity_3() { var source = @" public interface ITop { void M(); } public interface ILeft : ITop { void M<T>(); } public interface IRight : ITop { void M<T>(); } public interface IBottom : ILeft, IRight { void M(); } "; CreateCompilation(source).VerifyDiagnostics( // (19,10): warning CS0108: 'IBottom.M()' hides inherited member 'ITop.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IBottom.M()", "ITop.M()")); } /// <summary> /// All have unmodified method but ITop. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Arity_4() { var source = @" public interface ITop { void M<T>(); } public interface ILeft : ITop { void M(); } public interface IRight : ITop { void M(); } public interface IBottom : ILeft, IRight { void M(); } "; // Also hides IRight.M, but not reported. CreateCompilation(source).VerifyDiagnostics( // (19,10): warning CS0108: 'IBottom.M()' hides inherited member 'ILeft.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IBottom.M()", "ILeft.M()")); } /// <summary> /// All have unmodified method but ITop and IRight. /// Unlike the other TestDiamond_Overload tests, this one reports different diagnostics than its TestDiamond_Method counterpart. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Arity_5() { var source = @" public interface ITop { void M<T>(); } public interface ILeft : ITop { void M(); } public interface IRight : ITop { void M<T>(); } public interface IBottom : ILeft, IRight { void M(); } "; CreateCompilation(source).VerifyDiagnostics( // (19,10): warning CS0108: 'IBottom.M()' hides inherited member 'ILeft.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IBottom.M()", "ILeft.M()"), // (14,10): warning CS0108: 'IRight.M<T>()' hides inherited member 'ITop.M<T>()'. Use the new keyword if hiding was intended. // void M<T>(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IRight.M<T>()", "ITop.M<T>()")); } /// <summary> /// These tests are the same as the TestDiamond_Method tests except that, instead of removing the method /// from some interfaces, we'll change its member kind (to Property) in those interfaces. /// /// ITop /// / \ /// ILeft IRight /// \ / /// IBottom /// /// All have unmodified method. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Kind_1() { // Identical to TestDiamond_Method_1, so omitted. } /// <summary> /// All have unmodified method but IRight. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Kind_2() { var source = @" public interface ITop { void M(); } public interface ILeft : ITop { void M(); } public interface IRight : ITop { int M { get; set; } } public interface IBottom : ILeft, IRight { void M(); } "; CreateCompilation(source).VerifyDiagnostics( // (9,10): warning CS0108: 'ILeft.M()' hides inherited member 'ITop.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("ILeft.M()", "ITop.M()"), // (19,10): warning CS0108: 'IBottom.M()' hides inherited member 'ILeft.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IBottom.M()", "ILeft.M()"), // (14,9): warning CS0108: 'IRight.M' hides inherited member 'ITop.M()'. Use the new keyword if hiding was intended. // int M { get; set; } Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IRight.M", "ITop.M()")); } /// <summary> /// All have unmodified method but ILeft and IRight. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Kind_3() { var source = @" public interface ITop { void M(); } public interface ILeft : ITop { int M { get; set; } } public interface IRight : ITop { int M { get; set; } } public interface IBottom : ILeft, IRight { void M(); } "; CreateCompilation(source).VerifyDiagnostics( // (19,10): warning CS0108: 'IBottom.M()' hides inherited member 'ILeft.M'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IBottom.M()", "ILeft.M"), // (9,9): warning CS0108: 'ILeft.M' hides inherited member 'ITop.M()'. Use the new keyword if hiding was intended. // int M { get; set; } Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("ILeft.M", "ITop.M()"), // (14,9): warning CS0108: 'IRight.M' hides inherited member 'ITop.M()'. Use the new keyword if hiding was intended. // int M { get; set; } Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IRight.M", "ITop.M()")); } /// <summary> /// All have unmodified method but ITop. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Kind_4() { var source = @" public interface ITop { int M { get; set; } } public interface ILeft : ITop { void M(); } public interface IRight : ITop { void M(); } public interface IBottom : ILeft, IRight { void M(); } "; // Also hides IRight.M, but not reported. CreateCompilation(source).VerifyDiagnostics( // (14,10): warning CS0108: 'IRight.M()' hides inherited member 'ITop.M'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IRight.M()", "ITop.M"), // (9,10): warning CS0108: 'ILeft.M()' hides inherited member 'ITop.M'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("ILeft.M()", "ITop.M"), // (19,10): warning CS0108: 'IBottom.M()' hides inherited member 'ILeft.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IBottom.M()", "ILeft.M()")); } /// <summary> /// All have unmodified method but ITop and IRight. /// Unlike the other TestDiamond_Overload tests, this one reports different diagnostics than its TestDiamond_Method counterpart. /// </summary> [WorkItem(581173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581173")] [Fact] public void TestDiamond_Kind_5() { var source = @" public interface ITop { int M { get; set; } } public interface ILeft : ITop { void M(); } public interface IRight : ITop { int M { get; set; } } public interface IBottom : ILeft, IRight { void M(); } "; CreateCompilation(source).VerifyDiagnostics( // (14,9): warning CS0108: 'IRight.M' hides inherited member 'ITop.M'. Use the new keyword if hiding was intended. // int M { get; set; } Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IRight.M", "ITop.M"), // (19,10): warning CS0108: 'IBottom.M()' hides inherited member 'ILeft.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("IBottom.M()", "ILeft.M()"), // (9,10): warning CS0108: 'ILeft.M()' hides inherited member 'ITop.M'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("ILeft.M()", "ITop.M")); } [Fact] [WorkItem(661370, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/661370")] public void HideAndOverride() { var source = @" public interface Base { void M(); int M { get; set; } // NOTE: illegal, since there's already a method M. } public interface Derived1 : Base { void M(); } public interface Derived2 : Base { int M { get; set; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,9): error CS0102: The type 'Base' already contains a definition for 'M' // int M { get; set; } // NOTE: illegal, since there's already a method M. Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "M").WithArguments("Base", "M"), // (15,10): warning CS0108: 'Derived2.M' hides inherited member 'Base.M'. Use the new keyword if hiding was intended. // int M { get; set; } Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("Derived2.M", "Base.M"), // (10,11): warning CS0108: 'Derived1.M()' hides inherited member 'Base.M()'. Use the new keyword if hiding was intended. // void M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("Derived1.M()", "Base.M()")); var global = comp.GlobalNamespace; var baseInterface = global.GetMember<NamedTypeSymbol>("Base"); var baseMethod = baseInterface.GetMembers("M").OfType<MethodSymbol>().Single(); var baseProperty = baseInterface.GetMembers("M").OfType<PropertySymbol>().Single(); var derivedInterface1 = global.GetMember<NamedTypeSymbol>("Derived1"); var derivedMethod = derivedInterface1.GetMember<MethodSymbol>("M"); var overriddenOrHidden1 = derivedMethod.OverriddenOrHiddenMembers; AssertEx.SetEqual(overriddenOrHidden1.HiddenMembers, baseMethod, baseProperty); var derivedInterface2 = global.GetMember<NamedTypeSymbol>("Derived2"); var derivedProperty = derivedInterface2.GetMember<PropertySymbol>("M"); var overriddenOrHidden2 = derivedProperty.OverriddenOrHiddenMembers; AssertEx.SetEqual(overriddenOrHidden2.HiddenMembers, baseMethod, baseProperty); } [Fact] [WorkItem(667278, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/667278")] public void FalseIdentificationOfCircularDependency() { var source = @" public class ITest : ITest.Test{ public interface Test { } }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void HidingMethodWithInParameter() { var code = @" interface A { void M(in int x); } interface B : A { void M(in int x); }"; var comp = CreateCompilation(code).VerifyDiagnostics( // (8,10): warning CS0108: 'B.M(in int)' hides inherited member 'A.M(in int)'. Use the new keyword if hiding was intended. // void M(in int x); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("B.M(in int)", "A.M(in int)").WithLocation(8, 10)); var aMethod = comp.GetMember<MethodSymbol>("A.M"); var bMethod = comp.GetMember<MethodSymbol>("B.M"); Assert.Empty(aMethod.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Empty(aMethod.OverriddenOrHiddenMembers.HiddenMembers); Assert.Empty(bMethod.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Equal(aMethod, bMethod.OverriddenOrHiddenMembers.HiddenMembers.Single()); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void HidingMethodWithRefReadOnlyReturnType_RefReadOnly_RefReadOnly() { var code = @" interface A { ref readonly int M(); } interface B : A { ref readonly int M(); }"; var comp = CreateCompilation(code).VerifyDiagnostics( // (8,22): warning CS0108: 'B.M()' hides inherited member 'A.M()'. Use the new keyword if hiding was intended. // ref readonly int M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("B.M()", "A.M()").WithLocation(8, 22)); var aMethod = comp.GetMember<MethodSymbol>("A.M"); var bMethod = comp.GetMember<MethodSymbol>("B.M"); Assert.Empty(aMethod.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Empty(aMethod.OverriddenOrHiddenMembers.HiddenMembers); Assert.Empty(bMethod.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Equal(aMethod, bMethod.OverriddenOrHiddenMembers.HiddenMembers.Single()); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void HidingMethodWithRefReadOnlyReturnType_Ref_RefReadOnly() { var code = @" interface A { ref int M(); } interface B : A { ref readonly int M(); }"; var comp = CreateCompilation(code).VerifyDiagnostics( // (8,22): warning CS0108: 'B.M()' hides inherited member 'A.M()'. Use the new keyword if hiding was intended. // ref readonly int M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("B.M()", "A.M()").WithLocation(8, 22)); var aMethod = comp.GetMember<MethodSymbol>("A.M"); var bMethod = comp.GetMember<MethodSymbol>("B.M"); Assert.Empty(aMethod.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Empty(aMethod.OverriddenOrHiddenMembers.HiddenMembers); Assert.Empty(bMethod.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Equal(aMethod, bMethod.OverriddenOrHiddenMembers.HiddenMembers.Single()); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void HidingMethodWithRefReadOnlyReturnType_RefReadOnly_Ref() { var code = @" interface A { ref readonly int M(); } interface B : A { ref int M(); }"; var comp = CreateCompilation(code).VerifyDiagnostics( // (8,13): warning CS0108: 'B.M()' hides inherited member 'A.M()'. Use the new keyword if hiding was intended. // ref readonly int M(); Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("B.M()", "A.M()").WithLocation(8, 13)); var aMethod = comp.GetMember<MethodSymbol>("A.M"); var bMethod = comp.GetMember<MethodSymbol>("B.M"); Assert.Empty(aMethod.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Empty(aMethod.OverriddenOrHiddenMembers.HiddenMembers); Assert.Empty(bMethod.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Equal(aMethod, bMethod.OverriddenOrHiddenMembers.HiddenMembers.Single()); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void HidingPropertyWithRefReadOnlyReturnType_RefReadonly_RefReadonly() { var code = @" interface A { ref readonly int Property { get; } } interface B : A { ref readonly int Property { get; } }"; var comp = CreateCompilation(code).VerifyDiagnostics( // (8,22): warning CS0108: 'B.Property' hides inherited member 'A.Property'. Use the new keyword if hiding was intended. // ref readonly int Property { get; } Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("B.Property", "A.Property").WithLocation(8, 22)); var aProperty = comp.GetMember<PropertySymbol>("A.Property"); var bProperty = comp.GetMember<PropertySymbol>("B.Property"); Assert.Empty(aProperty.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Empty(aProperty.OverriddenOrHiddenMembers.HiddenMembers); Assert.Empty(bProperty.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Equal(aProperty, bProperty.OverriddenOrHiddenMembers.HiddenMembers.Single()); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void HidingPropertyWithRefReadOnlyReturnType_RefReadonly_Ref() { var code = @" interface A { ref readonly int Property { get; } } interface B : A { ref int Property { get; } }"; var comp = CreateCompilation(code).VerifyDiagnostics( // (8,13): warning CS0108: 'B.Property' hides inherited member 'A.Property'. Use the new keyword if hiding was intended. // ref int Property { get; } Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("B.Property", "A.Property").WithLocation(8, 13)); var aProperty = comp.GetMember<PropertySymbol>("A.Property"); var bProperty = comp.GetMember<PropertySymbol>("B.Property"); Assert.Empty(aProperty.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Empty(aProperty.OverriddenOrHiddenMembers.HiddenMembers); Assert.Empty(bProperty.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Equal(aProperty, bProperty.OverriddenOrHiddenMembers.HiddenMembers.Single()); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void HidingPropertyWithRefReadOnlyReturnType_Ref_RefReadonly() { var code = @" interface A { ref int Property { get; } } interface B : A { ref readonly int Property { get; } }"; var comp = CreateCompilation(code).VerifyDiagnostics( // (8,22): warning CS0108: 'B.Property' hides inherited member 'A.Property'. Use the new keyword if hiding was intended. // ref readonly int Property { get; } Diagnostic(ErrorCode.WRN_NewRequired, "Property").WithArguments("B.Property", "A.Property").WithLocation(8, 22)); var aProperty = comp.GetMember<PropertySymbol>("A.Property"); var bProperty = comp.GetMember<PropertySymbol>("B.Property"); Assert.Empty(aProperty.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Empty(aProperty.OverriddenOrHiddenMembers.HiddenMembers); Assert.Empty(bProperty.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Equal(aProperty, bProperty.OverriddenOrHiddenMembers.HiddenMembers.Single()); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void HidingMethodWithInParameterAndNewKeyword() { var code = @" interface A { void M(in int x); } interface B : A { new void M(in int x); }"; var comp = CreateCompilation(code).VerifyDiagnostics(); var aMethod = comp.GetMember<MethodSymbol>("A.M"); var bMethod = comp.GetMember<MethodSymbol>("B.M"); Assert.Empty(aMethod.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Empty(aMethod.OverriddenOrHiddenMembers.HiddenMembers); Assert.Empty(bMethod.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Equal(aMethod, bMethod.OverriddenOrHiddenMembers.HiddenMembers.Single()); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void HidingMethodWithRefReadOnlyReturnTypeAndNewKeyword() { var code = @" interface A { ref readonly int M(); } interface B : A { new ref readonly int M(); }"; var comp = CreateCompilation(code).VerifyDiagnostics(); var aMethod = comp.GetMember<MethodSymbol>("A.M"); var bMethod = comp.GetMember<MethodSymbol>("B.M"); Assert.Empty(aMethod.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Empty(aMethod.OverriddenOrHiddenMembers.HiddenMembers); Assert.Empty(bMethod.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Equal(aMethod, bMethod.OverriddenOrHiddenMembers.HiddenMembers.Single()); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void HidingPropertyWithRefReadOnlyReturnTypeAndNewKeyword() { var code = @" interface A { ref readonly int Property { get ; } } interface B : A { new ref readonly int Property { get; } }"; var comp = CreateCompilation(code).VerifyDiagnostics(); var aProperty = comp.GetMember<PropertySymbol>("A.Property"); var bProperty = comp.GetMember<PropertySymbol>("B.Property"); Assert.Empty(aProperty.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Empty(aProperty.OverriddenOrHiddenMembers.HiddenMembers); Assert.Empty(bProperty.OverriddenOrHiddenMembers.OverriddenMembers); Assert.Equal(aProperty, bProperty.OverriddenOrHiddenMembers.HiddenMembers.Single()); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void ImplementingMethodWithInParameter() { var code = @" interface A { void M(in int x); } class B : A { public void M(in int x) { } }"; var comp = CreateCompilation(code).VerifyDiagnostics(); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void ImplementingMethodWithRefReadOnlyReturnType() { var code = @" interface A { ref readonly int M(); } class B : A { protected int x = 0; public ref readonly int M() { return ref x; } }"; var comp = CreateCompilation(code).VerifyDiagnostics(); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void ImplementingPropertyWithRefReadOnlyReturnType() { var code = @" interface A { ref readonly int Property { get; } } class B : A { protected int x = 0; public ref readonly int Property { get { return ref x; } } }"; var comp = CreateCompilation(code).VerifyDiagnostics(); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void ImplementingMethodWithDifferentParameterRefness() { var code = @" interface A { void M(in int x); } class B : A { public void M(ref int x) { } }"; var comp = CreateCompilation(code).VerifyDiagnostics( // (6,11): error CS0535: 'B' does not implement interface member 'A.M(in int)' // class B : A Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "A").WithArguments("B", "A.M(in int)").WithLocation(6, 11)); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void ImplementingRefReadOnlyMembersWillOverwriteTheCorrectSlot() { var text = @" interface BaseInterface { ref readonly int Method1(in int a); ref readonly int Property1 { get; } ref readonly int this[int a] { get; } } class DerivedClass : BaseInterface { protected int field; public ref readonly int Method1(in int a) { return ref field; } public ref readonly int Property1 { get { return ref field; } } public ref readonly int this[int a] { get { return ref field; } } }"; var comp = CreateCompilation(text).VerifyDiagnostics(); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void MethodImplementationsShouldPreserveRefKindInParameters() { var text = @" interface BaseInterface { void Method1(ref int x); void Method2(in int x); } class ChildClass : BaseInterface { public void Method1(in int x) { } public void Method2(ref int x) { } }"; var comp = CreateCompilation(text).VerifyDiagnostics( // (7,20): error CS0535: 'ChildClass' does not implement interface member 'BaseInterface.Method2(in int)' // class ChildClass : BaseInterface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "BaseInterface").WithArguments("ChildClass", "BaseInterface.Method2(in int)").WithLocation(7, 20), // (7,20): error CS0535: 'ChildClass' does not implement interface member 'BaseInterface.Method1(ref int)' // class ChildClass : BaseInterface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "BaseInterface").WithArguments("ChildClass", "BaseInterface.Method1(ref int)").WithLocation(7, 20)); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void MethodImplementationsShouldPreserveReadOnlyRefnessInReturnTypes() { var text = @" interface BaseInterface { ref int Method1(); ref readonly int Method2(); } class ChildClass : BaseInterface { protected int x = 0 ; public ref readonly int Method1() { return ref x; } public ref int Method2() { return ref x; } }"; var comp = CreateCompilation(text).VerifyDiagnostics( // (7,20): error CS8152: 'ChildClass' does not implement interface member 'BaseInterface.Method2()'. 'ChildClass.Method2()' cannot implement 'BaseInterface.Method2()' because it does not have matching return by reference. // class ChildClass : BaseInterface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongRefReturn, "BaseInterface").WithArguments("ChildClass", "BaseInterface.Method2()", "ChildClass.Method2()").WithLocation(7, 20), // (7,20): error CS8152: 'ChildClass' does not implement interface member 'BaseInterface.Method1()'. 'ChildClass.Method1()' cannot implement 'BaseInterface.Method1()' because it does not have matching return by reference. // class ChildClass : BaseInterface Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongRefReturn, "BaseInterface").WithArguments("ChildClass", "BaseInterface.Method1()", "ChildClass.Method1()").WithLocation(7, 20)); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void PropertyImplementationsShouldPreserveReadOnlyRefnessInReturnTypes() { var code = @" interface A { ref int Property1 { get; } ref readonly int Property2 { get; } } class B : A { protected int x = 0; public ref readonly int Property1 { get { return ref x; } } public ref int Property2 { get { return ref x; } } }"; var comp = CreateCompilation(code).VerifyDiagnostics( // (7,11): error CS8152: 'B' does not implement interface member 'A.Property2'. 'B.Property2' cannot implement 'A.Property2' because it does not have matching return by reference. // class B : A Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongRefReturn, "A").WithArguments("B", "A.Property2", "B.Property2").WithLocation(7, 11), // (7,11): error CS8152: 'B' does not implement interface member 'A.Property1'. 'B.Property1' cannot implement 'A.Property1' because it does not have matching return by reference. // class B : A Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongRefReturn, "A").WithArguments("B", "A.Property1", "B.Property1").WithLocation(7, 11)); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void IndexerImplementationsShouldPreserveReadOnlyRefnessInReturnTypes_Ref_RefReadOnly() { var code = @" interface A { ref int this[int p] { get; } } class B : A { protected int x = 0; public ref readonly int this[int p] { get { return ref x; } } }"; var comp = CreateCompilation(code).VerifyDiagnostics( // (6,11): error CS8152: 'B' does not implement interface member 'A.this[int]'. 'B.this[int]' cannot implement 'A.this[int]' because it does not have matching return by reference. // class B : A Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongRefReturn, "A").WithArguments("B", "A.this[int]", "B.this[int]").WithLocation(6, 11)); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void IndexerImplementationsShouldPreserveReadOnlyRefnessInReturnTypes_RefReadOnly_Ref() { var code = @" interface A { ref readonly int this[int p] { get; } } class B : A { protected int x = 0; public ref int this[int p] { get { return ref x; } } }"; var comp = CreateCompilation(code).VerifyDiagnostics( // (6,11): error CS8152: 'B' does not implement interface member 'A.this[int]'. 'B.this[int]' cannot implement 'A.this[int]' because it does not have matching return by reference. // class B : A Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongRefReturn, "A").WithArguments("B", "A.this[int]", "B.this[int]").WithLocation(6, 11)); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void IndexerImplementationsShouldPreserveReadOnlyRefnessInIndexes_Valid() { var code = @" interface A { int this[in int p] { get; } } class B : A { public int this[in int p] { get { return p; } } }"; var comp = CreateCompilation(code).VerifyDiagnostics(); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void IndexerImplementationsShouldPreserveReadOnlyRefnessInIndexes_Source() { var code = @" interface A { int this[in int p] { get; } } class B : A { public int this[int p] { get { return p; } } }"; var comp = CreateCompilation(code).VerifyDiagnostics( // (6,11): error CS0535: 'B' does not implement interface member 'A.this[in int]' // class B : A Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "A").WithArguments("B", "A.this[in int]").WithLocation(6, 11)); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void IndexerImplementationsShouldPreserveReadOnlyRefnessInIndexes_Destination() { var code = @" interface A { int this[int p] { get; } } class B : A { public int this[in int p] { get { return p; } } }"; var comp = CreateCompilation(code).VerifyDiagnostics( // (6,11): error CS0535: 'B' does not implement interface member 'A.this[int]' // class B : A Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "A").WithArguments("B", "A.this[int]").WithLocation(6, 11)); } } }
-1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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.Cocoa/Preview/PreviewPaneService.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.Composition; using System.Globalization; using AppKit; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Core.Imaging; using Microsoft.VisualStudio.Imaging; namespace Microsoft.CodeAnalysis.Editor.Implementation.Preview { [ExportWorkspaceServiceFactory(typeof(IPreviewPaneService), ServiceLayer.Host), Shared] internal class PreviewPaneService : ForegroundThreadAffinitizedObject, IPreviewPaneService, IWorkspaceServiceFactory { private readonly IImageService imageService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PreviewPaneService(IThreadingContext threadingContext, IImageService imageService) : base(threadingContext) { this.imageService = imageService; } IWorkspaceService IWorkspaceServiceFactory.CreateService(HostWorkspaceServices workspaceServices) { return this; } #pragma warning disable IDE0051 // Remove unused private members private NSImage GetSeverityIconForDiagnostic(DiagnosticData diagnostic) #pragma warning restore IDE0051 // Remove unused private members { int? moniker = null; switch (diagnostic.Severity) { case DiagnosticSeverity.Error: moniker = KnownImageIds.StatusError; break; case DiagnosticSeverity.Warning: moniker = KnownImageIds.StatusWarning; break; case DiagnosticSeverity.Info: moniker = KnownImageIds.StatusInformation; break; case DiagnosticSeverity.Hidden: moniker = KnownImageIds.StatusHidden; break; } if (moniker.HasValue) { return (NSImage)imageService.GetImage(new ImageId(KnownImageIds.ImageCatalogGuid, moniker.Value)); } return null; } object IPreviewPaneService.GetPreviewPane( DiagnosticData data, IReadOnlyList<object> previewContent) { var title = data?.Message; if (string.IsNullOrWhiteSpace(title)) { if (previewContent == null) { // Bail out in cases where there is nothing to put in the header section // of the preview pane and no preview content (i.e. no diff view) either. return null; } return new PreviewPane( severityIcon: null, id: null, title: null, description: null, helpLink: null, helpLinkToolTipText: null, previewContent: previewContent, logIdVerbatimInTelemetry: false); } else { if (previewContent == null) { // TODO: Mac, if we have title but no content, we should still display title/help link... return null; } } var helpLinkUri = BrowserHelper.GetHelpLink(data); var helpLinkToolTip = BrowserHelper.GetHelpLinkToolTip(data.Id, helpLinkUri); return new PreviewPane( severityIcon: null,//TODO: Mac GetSeverityIconForDiagnostic(diagnostic), id: data.Id, title: title, description: data.Description.ToString(CultureInfo.CurrentUICulture), helpLink: helpLinkUri, helpLinkToolTipText: helpLinkToolTip, previewContent: previewContent, logIdVerbatimInTelemetry: data.CustomTags.Contains(WellKnownDiagnosticTags.Telemetry)); } } }
// Licensed to the .NET Foundation under one or more 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.Composition; using System.Globalization; using AppKit; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Core.Imaging; using Microsoft.VisualStudio.Imaging; namespace Microsoft.CodeAnalysis.Editor.Implementation.Preview { [ExportWorkspaceServiceFactory(typeof(IPreviewPaneService), ServiceLayer.Host), Shared] internal class PreviewPaneService : ForegroundThreadAffinitizedObject, IPreviewPaneService, IWorkspaceServiceFactory { private readonly IImageService imageService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PreviewPaneService(IThreadingContext threadingContext, IImageService imageService) : base(threadingContext) { this.imageService = imageService; } IWorkspaceService IWorkspaceServiceFactory.CreateService(HostWorkspaceServices workspaceServices) { return this; } #pragma warning disable IDE0051 // Remove unused private members private NSImage GetSeverityIconForDiagnostic(DiagnosticData diagnostic) #pragma warning restore IDE0051 // Remove unused private members { int? moniker = null; switch (diagnostic.Severity) { case DiagnosticSeverity.Error: moniker = KnownImageIds.StatusError; break; case DiagnosticSeverity.Warning: moniker = KnownImageIds.StatusWarning; break; case DiagnosticSeverity.Info: moniker = KnownImageIds.StatusInformation; break; case DiagnosticSeverity.Hidden: moniker = KnownImageIds.StatusHidden; break; } if (moniker.HasValue) { return (NSImage)imageService.GetImage(new ImageId(KnownImageIds.ImageCatalogGuid, moniker.Value)); } return null; } object IPreviewPaneService.GetPreviewPane( DiagnosticData data, IReadOnlyList<object> previewContent) { var title = data?.Message; if (string.IsNullOrWhiteSpace(title)) { if (previewContent == null) { // Bail out in cases where there is nothing to put in the header section // of the preview pane and no preview content (i.e. no diff view) either. return null; } return new PreviewPane( severityIcon: null, id: null, title: null, description: null, helpLink: null, helpLinkToolTipText: null, previewContent: previewContent, logIdVerbatimInTelemetry: false); } else { if (previewContent == null) { // TODO: Mac, if we have title but no content, we should still display title/help link... return null; } } var helpLinkUri = BrowserHelper.GetHelpLink(data); var helpLinkToolTip = BrowserHelper.GetHelpLinkToolTip(data.Id, helpLinkUri); return new PreviewPane( severityIcon: null,//TODO: Mac GetSeverityIconForDiagnostic(diagnostic), id: data.Id, title: title, description: data.Description.ToString(CultureInfo.CurrentUICulture), helpLink: helpLinkUri, helpLinkToolTipText: helpLinkToolTip, previewContent: previewContent, logIdVerbatimInTelemetry: data.CustomTags.Contains(WellKnownDiagnosticTags.Telemetry)); } } }
-1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/Diagnostics/DiagnosticAnalyzerInfoCache.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.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Provides and caches information about diagnostic analyzers such as <see cref="AnalyzerReference"/>, /// <see cref="DiagnosticAnalyzer"/> instance, <see cref="DiagnosticDescriptor"/>s. /// Thread-safe. /// </summary> internal sealed partial class DiagnosticAnalyzerInfoCache { /// <summary> /// Supported descriptors of each <see cref="DiagnosticAnalyzer"/>. /// </summary> /// <remarks> /// Holds on <see cref="DiagnosticAnalyzer"/> instances weakly so that we don't keep analyzers coming from package references alive. /// They need to be released when the project stops referencing the analyzer. /// /// The purpose of this map is to avoid multiple calls to <see cref="DiagnosticAnalyzer.SupportedDiagnostics"/> that might return different values /// (they should not but we need a guarantee to function correctly). /// </remarks> private readonly ConditionalWeakTable<DiagnosticAnalyzer, DiagnosticDescriptorsInfo> _descriptorsInfo; private sealed class DiagnosticDescriptorsInfo { public readonly ImmutableArray<DiagnosticDescriptor> SupportedDescriptors; public readonly bool TelemetryAllowed; public readonly bool HasCompilationEndDescriptor; public DiagnosticDescriptorsInfo(ImmutableArray<DiagnosticDescriptor> supportedDescriptors, bool telemetryAllowed) { SupportedDescriptors = supportedDescriptors; TelemetryAllowed = telemetryAllowed; HasCompilationEndDescriptor = supportedDescriptors.Any(DiagnosticDescriptorExtensions.IsCompilationEnd); } } internal DiagnosticAnalyzerInfoCache() { _descriptorsInfo = new ConditionalWeakTable<DiagnosticAnalyzer, DiagnosticDescriptorsInfo>(); } /// <summary> /// Returns <see cref="DiagnosticAnalyzer.SupportedDiagnostics"/> of given <paramref name="analyzer"/>. /// </summary> public ImmutableArray<DiagnosticDescriptor> GetDiagnosticDescriptors(DiagnosticAnalyzer analyzer) => GetOrCreateDescriptorsInfo(analyzer).SupportedDescriptors; /// <summary> /// Returns <see cref="DiagnosticAnalyzer.SupportedDiagnostics"/> of given <paramref name="analyzer"/> /// that are not compilation end descriptors. /// </summary> public ImmutableArray<DiagnosticDescriptor> GetNonCompilationEndDiagnosticDescriptors(DiagnosticAnalyzer analyzer) { var descriptorInfo = GetOrCreateDescriptorsInfo(analyzer); return !descriptorInfo.HasCompilationEndDescriptor ? descriptorInfo.SupportedDescriptors : descriptorInfo.SupportedDescriptors.WhereAsArray(d => !d.IsCompilationEnd()); } /// <summary> /// Returns true if given <paramref name="analyzer"/> has a compilation end descriptor /// that is reported in the Compilation end action. /// </summary> public bool IsCompilationEndAnalyzer(DiagnosticAnalyzer analyzer) => GetOrCreateDescriptorsInfo(analyzer).HasCompilationEndDescriptor; /// <summary> /// Determine whether collection of telemetry is allowed for given <paramref name="analyzer"/>. /// </summary> public bool IsTelemetryCollectionAllowed(DiagnosticAnalyzer analyzer) => GetOrCreateDescriptorsInfo(analyzer).TelemetryAllowed; private DiagnosticDescriptorsInfo GetOrCreateDescriptorsInfo(DiagnosticAnalyzer analyzer) => _descriptorsInfo.GetValue(analyzer, CalculateDescriptorsInfo); private DiagnosticDescriptorsInfo CalculateDescriptorsInfo(DiagnosticAnalyzer analyzer) { ImmutableArray<DiagnosticDescriptor> descriptors; try { // SupportedDiagnostics is user code and can throw an exception. descriptors = analyzer.SupportedDiagnostics.NullToEmpty(); } catch { // No need to report the exception to the user. // Eventually, when the analyzer runs the compiler analyzer driver will report a diagnostic. descriptors = ImmutableArray<DiagnosticDescriptor>.Empty; } var telemetryAllowed = IsTelemetryCollectionAllowed(analyzer, descriptors); return new DiagnosticDescriptorsInfo(descriptors, telemetryAllowed); } private static bool IsTelemetryCollectionAllowed(DiagnosticAnalyzer analyzer, ImmutableArray<DiagnosticDescriptor> descriptors) => analyzer.IsCompilerAnalyzer() || analyzer is IBuiltInAnalyzer || descriptors.Length > 0 && descriptors[0].CustomTags.Any(t => t == WellKnownDiagnosticTags.Telemetry); /// <summary> /// Return true if the given <paramref name="analyzer"/> is suppressed for the given project. /// NOTE: This API is intended to be used only for performance optimization. /// </summary> public bool IsAnalyzerSuppressed(DiagnosticAnalyzer analyzer, Project project) { var options = project.CompilationOptions; if (options == null || analyzer == FileContentLoadAnalyzer.Instance || analyzer.IsCompilerAnalyzer()) { return false; } // If user has disabled analyzer execution for this project, we only want to execute required analyzers // that report diagnostics with category "Compiler". if (!project.State.RunAnalyzers && GetDiagnosticDescriptors(analyzer).All(d => d.Category != DiagnosticCategory.Compiler)) { return true; } // NOTE: Previously we used to return "CompilationWithAnalyzers.IsDiagnosticAnalyzerSuppressed(options)" // on this code path, which returns true if analyzer is suppressed through compilation options. // However, this check is no longer correct as analyzers can be enabled/disabled for individual // documents through .editorconfig files. So we pessimistically assume analyzer is not suppressed // and let the core analyzer driver in the compiler layer handle skipping redundant analysis callbacks. 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.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Provides and caches information about diagnostic analyzers such as <see cref="AnalyzerReference"/>, /// <see cref="DiagnosticAnalyzer"/> instance, <see cref="DiagnosticDescriptor"/>s. /// Thread-safe. /// </summary> internal sealed partial class DiagnosticAnalyzerInfoCache { /// <summary> /// Supported descriptors of each <see cref="DiagnosticAnalyzer"/>. /// </summary> /// <remarks> /// Holds on <see cref="DiagnosticAnalyzer"/> instances weakly so that we don't keep analyzers coming from package references alive. /// They need to be released when the project stops referencing the analyzer. /// /// The purpose of this map is to avoid multiple calls to <see cref="DiagnosticAnalyzer.SupportedDiagnostics"/> that might return different values /// (they should not but we need a guarantee to function correctly). /// </remarks> private readonly ConditionalWeakTable<DiagnosticAnalyzer, DiagnosticDescriptorsInfo> _descriptorsInfo; private sealed class DiagnosticDescriptorsInfo { public readonly ImmutableArray<DiagnosticDescriptor> SupportedDescriptors; public readonly bool TelemetryAllowed; public readonly bool HasCompilationEndDescriptor; public DiagnosticDescriptorsInfo(ImmutableArray<DiagnosticDescriptor> supportedDescriptors, bool telemetryAllowed) { SupportedDescriptors = supportedDescriptors; TelemetryAllowed = telemetryAllowed; HasCompilationEndDescriptor = supportedDescriptors.Any(DiagnosticDescriptorExtensions.IsCompilationEnd); } } internal DiagnosticAnalyzerInfoCache() { _descriptorsInfo = new ConditionalWeakTable<DiagnosticAnalyzer, DiagnosticDescriptorsInfo>(); } /// <summary> /// Returns <see cref="DiagnosticAnalyzer.SupportedDiagnostics"/> of given <paramref name="analyzer"/>. /// </summary> public ImmutableArray<DiagnosticDescriptor> GetDiagnosticDescriptors(DiagnosticAnalyzer analyzer) => GetOrCreateDescriptorsInfo(analyzer).SupportedDescriptors; /// <summary> /// Returns <see cref="DiagnosticAnalyzer.SupportedDiagnostics"/> of given <paramref name="analyzer"/> /// that are not compilation end descriptors. /// </summary> public ImmutableArray<DiagnosticDescriptor> GetNonCompilationEndDiagnosticDescriptors(DiagnosticAnalyzer analyzer) { var descriptorInfo = GetOrCreateDescriptorsInfo(analyzer); return !descriptorInfo.HasCompilationEndDescriptor ? descriptorInfo.SupportedDescriptors : descriptorInfo.SupportedDescriptors.WhereAsArray(d => !d.IsCompilationEnd()); } /// <summary> /// Returns true if given <paramref name="analyzer"/> has a compilation end descriptor /// that is reported in the Compilation end action. /// </summary> public bool IsCompilationEndAnalyzer(DiagnosticAnalyzer analyzer) => GetOrCreateDescriptorsInfo(analyzer).HasCompilationEndDescriptor; /// <summary> /// Determine whether collection of telemetry is allowed for given <paramref name="analyzer"/>. /// </summary> public bool IsTelemetryCollectionAllowed(DiagnosticAnalyzer analyzer) => GetOrCreateDescriptorsInfo(analyzer).TelemetryAllowed; private DiagnosticDescriptorsInfo GetOrCreateDescriptorsInfo(DiagnosticAnalyzer analyzer) => _descriptorsInfo.GetValue(analyzer, CalculateDescriptorsInfo); private DiagnosticDescriptorsInfo CalculateDescriptorsInfo(DiagnosticAnalyzer analyzer) { ImmutableArray<DiagnosticDescriptor> descriptors; try { // SupportedDiagnostics is user code and can throw an exception. descriptors = analyzer.SupportedDiagnostics.NullToEmpty(); } catch { // No need to report the exception to the user. // Eventually, when the analyzer runs the compiler analyzer driver will report a diagnostic. descriptors = ImmutableArray<DiagnosticDescriptor>.Empty; } var telemetryAllowed = IsTelemetryCollectionAllowed(analyzer, descriptors); return new DiagnosticDescriptorsInfo(descriptors, telemetryAllowed); } private static bool IsTelemetryCollectionAllowed(DiagnosticAnalyzer analyzer, ImmutableArray<DiagnosticDescriptor> descriptors) => analyzer.IsCompilerAnalyzer() || analyzer is IBuiltInAnalyzer || descriptors.Length > 0 && descriptors[0].CustomTags.Any(t => t == WellKnownDiagnosticTags.Telemetry); /// <summary> /// Return true if the given <paramref name="analyzer"/> is suppressed for the given project. /// NOTE: This API is intended to be used only for performance optimization. /// </summary> public bool IsAnalyzerSuppressed(DiagnosticAnalyzer analyzer, Project project) { var options = project.CompilationOptions; if (options == null || analyzer == FileContentLoadAnalyzer.Instance || analyzer.IsCompilerAnalyzer()) { return false; } // If user has disabled analyzer execution for this project, we only want to execute required analyzers // that report diagnostics with category "Compiler". if (!project.State.RunAnalyzers && GetDiagnosticDescriptors(analyzer).All(d => d.Category != DiagnosticCategory.Compiler)) { return true; } // NOTE: Previously we used to return "CompilationWithAnalyzers.IsDiagnosticAnalyzerSuppressed(options)" // on this code path, which returns true if analyzer is suppressed through compilation options. // However, this check is no longer correct as analyzers can be enabled/disabled for individual // documents through .editorconfig files. So we pessimistically assume analyzer is not suppressed // and let the core analyzer driver in the compiler layer handle skipping redundant analysis callbacks. return false; } } }
-1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/Text/StringBuilderText.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.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Text { /// <summary> /// Implementation of <see cref="SourceText"/> based on a <see cref="StringBuilder"/> input /// </summary> internal sealed partial class StringBuilderText : SourceText { /// <summary> /// Underlying string on which this SourceText instance is based /// </summary> private readonly StringBuilder _builder; private readonly Encoding? _encodingOpt; public StringBuilderText(StringBuilder builder, Encoding? encodingOpt, SourceHashAlgorithm checksumAlgorithm) : base(checksumAlgorithm: checksumAlgorithm) { RoslynDebug.Assert(builder != null); _builder = builder; _encodingOpt = encodingOpt; } public override Encoding? Encoding { get { return _encodingOpt; } } /// <summary> /// Underlying string which is the source of this SourceText instance /// </summary> internal StringBuilder Builder { get { return _builder; } } /// <summary> /// The length of the text represented by <see cref="StringBuilderText"/>. /// </summary> public override int Length { get { return _builder.Length; } } /// <summary> /// Returns a character at given position. /// </summary> /// <param name="position">The position to get the character from.</param> /// <returns>The character.</returns> /// <exception cref="ArgumentOutOfRangeException">When position is negative or /// greater than <see cref="Length"/>.</exception> public override char this[int position] { get { if (position < 0 || position >= _builder.Length) { throw new ArgumentOutOfRangeException(nameof(position)); } return _builder[position]; } } /// <summary> /// Provides a string representation of the StringBuilderText located within given span. /// </summary> /// <exception cref="ArgumentOutOfRangeException">When given span is outside of the text range.</exception> public override string ToString(TextSpan span) { if (span.End > _builder.Length) { throw new ArgumentOutOfRangeException(nameof(span)); } return _builder.ToString(span.Start, span.Length); } public override void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) { _builder.CopyTo(sourceIndex, destination, destinationIndex, count); } } }
// Licensed to the .NET Foundation under one or more 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.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Text { /// <summary> /// Implementation of <see cref="SourceText"/> based on a <see cref="StringBuilder"/> input /// </summary> internal sealed partial class StringBuilderText : SourceText { /// <summary> /// Underlying string on which this SourceText instance is based /// </summary> private readonly StringBuilder _builder; private readonly Encoding? _encodingOpt; public StringBuilderText(StringBuilder builder, Encoding? encodingOpt, SourceHashAlgorithm checksumAlgorithm) : base(checksumAlgorithm: checksumAlgorithm) { RoslynDebug.Assert(builder != null); _builder = builder; _encodingOpt = encodingOpt; } public override Encoding? Encoding { get { return _encodingOpt; } } /// <summary> /// Underlying string which is the source of this SourceText instance /// </summary> internal StringBuilder Builder { get { return _builder; } } /// <summary> /// The length of the text represented by <see cref="StringBuilderText"/>. /// </summary> public override int Length { get { return _builder.Length; } } /// <summary> /// Returns a character at given position. /// </summary> /// <param name="position">The position to get the character from.</param> /// <returns>The character.</returns> /// <exception cref="ArgumentOutOfRangeException">When position is negative or /// greater than <see cref="Length"/>.</exception> public override char this[int position] { get { if (position < 0 || position >= _builder.Length) { throw new ArgumentOutOfRangeException(nameof(position)); } return _builder[position]; } } /// <summary> /// Provides a string representation of the StringBuilderText located within given span. /// </summary> /// <exception cref="ArgumentOutOfRangeException">When given span is outside of the text range.</exception> public override string ToString(TextSpan span) { if (span.End > _builder.Length) { throw new ArgumentOutOfRangeException(nameof(span)); } return _builder.ToString(span.Start, span.Length); } public override void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) { _builder.CopyTo(sourceIndex, destination, destinationIndex, count); } } }
-1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/MakeMemberStatic/AbstractMakeMemberStaticCodeFixProvider.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.MakeMemberStatic { internal abstract class AbstractMakeMemberStaticCodeFixProvider : SyntaxEditorBasedCodeFixProvider { internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.Compile; protected abstract bool IsValidMemberNode([NotNullWhen(true)] SyntaxNode? node); public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { if (context.Diagnostics.Length == 1 && IsValidMemberNode(context.Diagnostics[0].Location?.FindNode(context.CancellationToken))) { context.RegisterCodeFix( new MyCodeAction(c => FixAsync(context.Document, context.Diagnostics[0], c)), context.Diagnostics); } return Task.CompletedTask; } protected sealed override Task FixAllAsync(Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { for (var i = 0; i < diagnostics.Length; i++) { var declaration = diagnostics[i].Location?.FindNode(cancellationToken); if (IsValidMemberNode(declaration)) { editor.ReplaceNode(declaration, (currentDeclaration, generator) => generator.WithModifiers(currentDeclaration, DeclarationModifiers.Static)); } } return Task.CompletedTask; } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(FeaturesResources.Make_member_static, createChangedDocument, nameof(AbstractMakeMemberStaticCodeFixProvider)) { } } } }
// Licensed to the .NET Foundation under one or more 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.MakeMemberStatic { internal abstract class AbstractMakeMemberStaticCodeFixProvider : SyntaxEditorBasedCodeFixProvider { internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.Compile; protected abstract bool IsValidMemberNode([NotNullWhen(true)] SyntaxNode? node); public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { if (context.Diagnostics.Length == 1 && IsValidMemberNode(context.Diagnostics[0].Location?.FindNode(context.CancellationToken))) { context.RegisterCodeFix( new MyCodeAction(c => FixAsync(context.Document, context.Diagnostics[0], c)), context.Diagnostics); } return Task.CompletedTask; } protected sealed override Task FixAllAsync(Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { for (var i = 0; i < diagnostics.Length; i++) { var declaration = diagnostics[i].Location?.FindNode(cancellationToken); if (IsValidMemberNode(declaration)) { editor.ReplaceNode(declaration, (currentDeclaration, generator) => generator.WithModifiers(currentDeclaration, DeclarationModifiers.Static)); } } return Task.CompletedTask; } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(FeaturesResources.Make_member_static, createChangedDocument, nameof(AbstractMakeMemberStaticCodeFixProvider)) { } } } }
-1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/Binder.WithQueryLambdaParametersBinder.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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class Binder { // A binder that finds query variables (BoundRangeVariableSymbol) and can bind them // to the appropriate rewriting involving lambda parameters when transparent identifiers are involved. private sealed class WithQueryLambdaParametersBinder : WithLambdaParametersBinder { private readonly RangeVariableMap _rangeVariableMap; private readonly MultiDictionary<string, RangeVariableSymbol> _parameterMap; public WithQueryLambdaParametersBinder(LambdaSymbol lambdaSymbol, RangeVariableMap rangeVariableMap, Binder next) : base(lambdaSymbol, next) { _rangeVariableMap = rangeVariableMap; _parameterMap = new MultiDictionary<string, RangeVariableSymbol>(); foreach (var qv in rangeVariableMap.Keys) { _parameterMap.Add(qv.Name, qv); } } protected override BoundExpression BindRangeVariable(SimpleNameSyntax node, RangeVariableSymbol qv, BindingDiagnosticBag diagnostics) { Debug.Assert(!qv.IsTransparent); BoundExpression translation; ImmutableArray<string> path; if (_rangeVariableMap.TryGetValue(qv, out path)) { if (path.IsEmpty) { // the range variable maps directly to a use of the parameter of that name var value = base.parameterMap[qv.Name]; Debug.Assert(value.Count == 1); translation = new BoundParameter(node, value.Single()); } else { // if the query variable map for this variable is non empty, we always start with the current // lambda's first parameter, which is a transparent identifier. Debug.Assert(base.lambdaSymbol.Parameters[0].Name.StartsWith(transparentIdentifierPrefix, StringComparison.Ordinal)); translation = new BoundParameter(node, base.lambdaSymbol.Parameters[0]); for (int i = path.Length - 1; i >= 0; i--) { translation.WasCompilerGenerated = true; var nextField = path[i]; translation = SelectField(node, translation, nextField, diagnostics); } } return new BoundRangeVariable(node, qv, translation, translation.Type); } return base.BindRangeVariable(node, qv, diagnostics); } private BoundExpression SelectField(SimpleNameSyntax node, BoundExpression receiver, string name, BindingDiagnosticBag diagnostics) { var receiverType = receiver.Type as NamedTypeSymbol; if ((object)receiverType == null || !receiverType.IsAnonymousType) { // We only construct transparent query variables using anonymous types, so if we're trying to navigate through // some other type, we must have some query API where the types don't match up as expected. var info = new CSDiagnosticInfo(ErrorCode.ERR_UnsupportedTransparentIdentifierAccess, name, receiver.ExpressionSymbol ?? receiverType); if (receiver.Type?.IsErrorType() != true) { Error(diagnostics, info, node); } return new BoundBadExpression( node, LookupResultKind.Empty, ImmutableArray.Create<Symbol>(receiver.ExpressionSymbol), ImmutableArray.Create(BindToTypeForErrorRecovery(receiver)), new ExtendedErrorTypeSymbol(this.Compilation, "", 0, info)); } LookupResult lookupResult = LookupResult.GetInstance(); LookupOptions options = LookupOptions.MustBeInstance; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); LookupMembersWithFallback(lookupResult, receiver.Type, name, 0, ref useSiteInfo, basesBeingResolved: null, options: options); diagnostics.Add(node, useSiteInfo); var result = BindMemberOfType(node, node, name, 0, indexed: false, receiver, default(SeparatedSyntaxList<TypeSyntax>), default(ImmutableArray<TypeWithAnnotations>), lookupResult, BoundMethodGroupFlags.None, diagnostics); lookupResult.Free(); return result; } internal override void LookupSymbolsInSingleBinder( LookupResult result, string name, int arity, ConsList<TypeSymbol> basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(result.IsClear); if ((options & LookupOptions.NamespaceAliasesOnly) != 0) { return; } foreach (var rangeVariable in _parameterMap[name]) { result.MergeEqual(originalBinder.CheckViability(rangeVariable, arity, options, null, diagnose, ref useSiteInfo)); } } protected override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo result, LookupOptions options, Binder originalBinder) { if (options.CanConsiderMembers()) { foreach (var kvp in _parameterMap) { result.AddSymbol(null, kvp.Key, 0); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class Binder { // A binder that finds query variables (BoundRangeVariableSymbol) and can bind them // to the appropriate rewriting involving lambda parameters when transparent identifiers are involved. private sealed class WithQueryLambdaParametersBinder : WithLambdaParametersBinder { private readonly RangeVariableMap _rangeVariableMap; private readonly MultiDictionary<string, RangeVariableSymbol> _parameterMap; public WithQueryLambdaParametersBinder(LambdaSymbol lambdaSymbol, RangeVariableMap rangeVariableMap, Binder next) : base(lambdaSymbol, next) { _rangeVariableMap = rangeVariableMap; _parameterMap = new MultiDictionary<string, RangeVariableSymbol>(); foreach (var qv in rangeVariableMap.Keys) { _parameterMap.Add(qv.Name, qv); } } protected override BoundExpression BindRangeVariable(SimpleNameSyntax node, RangeVariableSymbol qv, BindingDiagnosticBag diagnostics) { Debug.Assert(!qv.IsTransparent); BoundExpression translation; ImmutableArray<string> path; if (_rangeVariableMap.TryGetValue(qv, out path)) { if (path.IsEmpty) { // the range variable maps directly to a use of the parameter of that name var value = base.parameterMap[qv.Name]; Debug.Assert(value.Count == 1); translation = new BoundParameter(node, value.Single()); } else { // if the query variable map for this variable is non empty, we always start with the current // lambda's first parameter, which is a transparent identifier. Debug.Assert(base.lambdaSymbol.Parameters[0].Name.StartsWith(transparentIdentifierPrefix, StringComparison.Ordinal)); translation = new BoundParameter(node, base.lambdaSymbol.Parameters[0]); for (int i = path.Length - 1; i >= 0; i--) { translation.WasCompilerGenerated = true; var nextField = path[i]; translation = SelectField(node, translation, nextField, diagnostics); } } return new BoundRangeVariable(node, qv, translation, translation.Type); } return base.BindRangeVariable(node, qv, diagnostics); } private BoundExpression SelectField(SimpleNameSyntax node, BoundExpression receiver, string name, BindingDiagnosticBag diagnostics) { var receiverType = receiver.Type as NamedTypeSymbol; if ((object)receiverType == null || !receiverType.IsAnonymousType) { // We only construct transparent query variables using anonymous types, so if we're trying to navigate through // some other type, we must have some query API where the types don't match up as expected. var info = new CSDiagnosticInfo(ErrorCode.ERR_UnsupportedTransparentIdentifierAccess, name, receiver.ExpressionSymbol ?? receiverType); if (receiver.Type?.IsErrorType() != true) { Error(diagnostics, info, node); } return new BoundBadExpression( node, LookupResultKind.Empty, ImmutableArray.Create<Symbol>(receiver.ExpressionSymbol), ImmutableArray.Create(BindToTypeForErrorRecovery(receiver)), new ExtendedErrorTypeSymbol(this.Compilation, "", 0, info)); } LookupResult lookupResult = LookupResult.GetInstance(); LookupOptions options = LookupOptions.MustBeInstance; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); LookupMembersWithFallback(lookupResult, receiver.Type, name, 0, ref useSiteInfo, basesBeingResolved: null, options: options); diagnostics.Add(node, useSiteInfo); var result = BindMemberOfType(node, node, name, 0, indexed: false, receiver, default(SeparatedSyntaxList<TypeSyntax>), default(ImmutableArray<TypeWithAnnotations>), lookupResult, BoundMethodGroupFlags.None, diagnostics); lookupResult.Free(); return result; } internal override void LookupSymbolsInSingleBinder( LookupResult result, string name, int arity, ConsList<TypeSymbol> basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(result.IsClear); if ((options & LookupOptions.NamespaceAliasesOnly) != 0) { return; } foreach (var rangeVariable in _parameterMap[name]) { result.MergeEqual(originalBinder.CheckViability(rangeVariable, arity, options, null, diagnose, ref useSiteInfo)); } } protected override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo result, LookupOptions options, Binder originalBinder) { if (options.CanConsiderMembers()) { foreach (var kvp in _parameterMap) { result.AddSymbol(null, kvp.Key, 0); } } } } } }
-1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/AddParameter/CodeFixData.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.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.AddParameter { internal readonly struct CodeFixData { public CodeFixData( IMethodSymbol method, Func<CancellationToken, Task<Solution>> createChangedSolutionNonCascading, Func<CancellationToken, Task<Solution>> createChangedSolutionCascading) { Method = method ?? throw new ArgumentNullException(nameof(method)); CreateChangedSolutionNonCascading = createChangedSolutionNonCascading ?? throw new ArgumentNullException(nameof(createChangedSolutionNonCascading)); CreateChangedSolutionCascading = createChangedSolutionCascading; } /// <summary> /// The overload to fix. /// </summary> public IMethodSymbol Method { get; } /// <summary> /// A mandatory fix for the overload without cascading. /// </summary> public Func<CancellationToken, Task<Solution>> CreateChangedSolutionNonCascading { get; } /// <summary> /// An optional fix for the overload with cascading. /// </summary> public Func<CancellationToken, Task<Solution>> CreateChangedSolutionCascading { 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. #nullable disable using System; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.AddParameter { internal readonly struct CodeFixData { public CodeFixData( IMethodSymbol method, Func<CancellationToken, Task<Solution>> createChangedSolutionNonCascading, Func<CancellationToken, Task<Solution>> createChangedSolutionCascading) { Method = method ?? throw new ArgumentNullException(nameof(method)); CreateChangedSolutionNonCascading = createChangedSolutionNonCascading ?? throw new ArgumentNullException(nameof(createChangedSolutionNonCascading)); CreateChangedSolutionCascading = createChangedSolutionCascading; } /// <summary> /// The overload to fix. /// </summary> public IMethodSymbol Method { get; } /// <summary> /// A mandatory fix for the overload without cascading. /// </summary> public Func<CancellationToken, Task<Solution>> CreateChangedSolutionNonCascading { get; } /// <summary> /// An optional fix for the overload with cascading. /// </summary> public Func<CancellationToken, Task<Solution>> CreateChangedSolutionCascading { get; } } }
-1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/Completion/CompletionProviders/PartialMethodCompletionProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportCompletionProvider(nameof(PartialMethodCompletionProvider), LanguageNames.CSharp)] [ExtensionOrder(After = nameof(OverrideCompletionProvider))] [Shared] internal partial class PartialMethodCompletionProvider : AbstractPartialMethodCompletionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PartialMethodCompletionProvider() { } protected override bool IncludeAccessibility(IMethodSymbol method, CancellationToken cancellationToken) { var declaration = (MethodDeclarationSyntax)method.DeclaringSyntaxReferences[0].GetSyntax(cancellationToken); foreach (var mod in declaration.Modifiers) { switch (mod.Kind()) { case SyntaxKind.PublicKeyword: case SyntaxKind.ProtectedKeyword: case SyntaxKind.InternalKeyword: case SyntaxKind.PrivateKeyword: return true; } } return false; } protected override SyntaxNode GetSyntax(SyntaxToken token) { return token.GetAncestor<EventFieldDeclarationSyntax>() ?? token.GetAncestor<EventDeclarationSyntax>() ?? token.GetAncestor<PropertyDeclarationSyntax>() ?? token.GetAncestor<IndexerDeclarationSyntax>() ?? (SyntaxNode)token.GetAncestor<MethodDeclarationSyntax>(); } protected override int GetTargetCaretPosition(SyntaxNode caretTarget) { var methodDeclaration = (MethodDeclarationSyntax)caretTarget; return CompletionUtilities.GetTargetCaretPositionForMethod(methodDeclaration); } protected override SyntaxToken GetToken(CompletionItem completionItem, SyntaxTree tree, CancellationToken cancellationToken) { var tokenSpanEnd = MemberInsertionCompletionItem.GetTokenSpanEnd(completionItem); return tree.FindTokenOnLeftOfPosition(tokenSpanEnd, cancellationToken); } public override bool IsInsertionTrigger(SourceText text, int characterPosition, OptionSet options) { var ch = text[characterPosition]; return ch == ' ' || (CompletionUtilities.IsStartingNewWord(text, characterPosition) && options.GetOption(CompletionOptions.TriggerOnTypingLetters2, LanguageNames.CSharp)); } public override ImmutableHashSet<char> TriggerCharacters { get; } = CompletionUtilities.SpaceTriggerCharacter; protected override bool IsPartial(IMethodSymbol method) { var declarations = method.DeclaringSyntaxReferences.Select(r => r.GetSyntax()).OfType<MethodDeclarationSyntax>(); return declarations.Any(d => d.Body == null && d.Modifiers.Any(SyntaxKind.PartialKeyword)); } protected override bool IsPartialMethodCompletionContext(SyntaxTree tree, int position, CancellationToken cancellationToken, out DeclarationModifiers modifiers, out SyntaxToken token) { var touchingToken = tree.FindTokenOnLeftOfPosition(position, cancellationToken); var targetToken = touchingToken.GetPreviousTokenIfTouchingWord(position); var text = tree.GetText(cancellationToken); token = targetToken; modifiers = default; if (targetToken.IsKind(SyntaxKind.VoidKeyword, SyntaxKind.PartialKeyword) || (targetToken.Kind() == SyntaxKind.IdentifierToken && targetToken.HasMatchingText(SyntaxKind.PartialKeyword))) { return !IsOnSameLine(touchingToken.GetNextToken(), touchingToken, text) && VerifyModifiers(tree, position, cancellationToken, out modifiers); } return false; } private static bool VerifyModifiers(SyntaxTree tree, int position, CancellationToken cancellationToken, out DeclarationModifiers modifiers) { var touchingToken = tree.FindTokenOnLeftOfPosition(position, cancellationToken); var token = touchingToken.GetPreviousToken(); var foundPartial = touchingToken.IsKindOrHasMatchingText(SyntaxKind.PartialKeyword); var foundAsync = false; while (IsOnSameLine(token, touchingToken, tree.GetText(cancellationToken))) { if (token.IsKindOrHasMatchingText(SyntaxKind.AsyncKeyword)) { foundAsync = true; } foundPartial = foundPartial || token.IsKindOrHasMatchingText(SyntaxKind.PartialKeyword); token = token.GetPreviousToken(); } modifiers = new DeclarationModifiers(isAsync: foundAsync, isPartial: true); return foundPartial; } private static bool IsOnSameLine(SyntaxToken syntaxToken, SyntaxToken touchingToken, SourceText text) { return !syntaxToken.IsKind(SyntaxKind.None) && !touchingToken.IsKind(SyntaxKind.None) && text.Lines.IndexOf(syntaxToken.SpanStart) == text.Lines.IndexOf(touchingToken.SpanStart); } protected override string GetDisplayText(IMethodSymbol method, SemanticModel semanticModel, int position) => method.ToMinimalDisplayString(semanticModel, position, SignatureDisplayFormat); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportCompletionProvider(nameof(PartialMethodCompletionProvider), LanguageNames.CSharp)] [ExtensionOrder(After = nameof(OverrideCompletionProvider))] [Shared] internal partial class PartialMethodCompletionProvider : AbstractPartialMethodCompletionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PartialMethodCompletionProvider() { } protected override bool IncludeAccessibility(IMethodSymbol method, CancellationToken cancellationToken) { var declaration = (MethodDeclarationSyntax)method.DeclaringSyntaxReferences[0].GetSyntax(cancellationToken); foreach (var mod in declaration.Modifiers) { switch (mod.Kind()) { case SyntaxKind.PublicKeyword: case SyntaxKind.ProtectedKeyword: case SyntaxKind.InternalKeyword: case SyntaxKind.PrivateKeyword: return true; } } return false; } protected override SyntaxNode GetSyntax(SyntaxToken token) { return token.GetAncestor<EventFieldDeclarationSyntax>() ?? token.GetAncestor<EventDeclarationSyntax>() ?? token.GetAncestor<PropertyDeclarationSyntax>() ?? token.GetAncestor<IndexerDeclarationSyntax>() ?? (SyntaxNode)token.GetAncestor<MethodDeclarationSyntax>(); } protected override int GetTargetCaretPosition(SyntaxNode caretTarget) { var methodDeclaration = (MethodDeclarationSyntax)caretTarget; return CompletionUtilities.GetTargetCaretPositionForMethod(methodDeclaration); } protected override SyntaxToken GetToken(CompletionItem completionItem, SyntaxTree tree, CancellationToken cancellationToken) { var tokenSpanEnd = MemberInsertionCompletionItem.GetTokenSpanEnd(completionItem); return tree.FindTokenOnLeftOfPosition(tokenSpanEnd, cancellationToken); } public override bool IsInsertionTrigger(SourceText text, int characterPosition, OptionSet options) { var ch = text[characterPosition]; return ch == ' ' || (CompletionUtilities.IsStartingNewWord(text, characterPosition) && options.GetOption(CompletionOptions.TriggerOnTypingLetters2, LanguageNames.CSharp)); } public override ImmutableHashSet<char> TriggerCharacters { get; } = CompletionUtilities.SpaceTriggerCharacter; protected override bool IsPartial(IMethodSymbol method) { var declarations = method.DeclaringSyntaxReferences.Select(r => r.GetSyntax()).OfType<MethodDeclarationSyntax>(); return declarations.Any(d => d.Body == null && d.Modifiers.Any(SyntaxKind.PartialKeyword)); } protected override bool IsPartialMethodCompletionContext(SyntaxTree tree, int position, CancellationToken cancellationToken, out DeclarationModifiers modifiers, out SyntaxToken token) { var touchingToken = tree.FindTokenOnLeftOfPosition(position, cancellationToken); var targetToken = touchingToken.GetPreviousTokenIfTouchingWord(position); var text = tree.GetText(cancellationToken); token = targetToken; modifiers = default; if (targetToken.IsKind(SyntaxKind.VoidKeyword, SyntaxKind.PartialKeyword) || (targetToken.Kind() == SyntaxKind.IdentifierToken && targetToken.HasMatchingText(SyntaxKind.PartialKeyword))) { return !IsOnSameLine(touchingToken.GetNextToken(), touchingToken, text) && VerifyModifiers(tree, position, cancellationToken, out modifiers); } return false; } private static bool VerifyModifiers(SyntaxTree tree, int position, CancellationToken cancellationToken, out DeclarationModifiers modifiers) { var touchingToken = tree.FindTokenOnLeftOfPosition(position, cancellationToken); var token = touchingToken.GetPreviousToken(); var foundPartial = touchingToken.IsKindOrHasMatchingText(SyntaxKind.PartialKeyword); var foundAsync = false; while (IsOnSameLine(token, touchingToken, tree.GetText(cancellationToken))) { if (token.IsKindOrHasMatchingText(SyntaxKind.AsyncKeyword)) { foundAsync = true; } foundPartial = foundPartial || token.IsKindOrHasMatchingText(SyntaxKind.PartialKeyword); token = token.GetPreviousToken(); } modifiers = new DeclarationModifiers(isAsync: foundAsync, isPartial: true); return foundPartial; } private static bool IsOnSameLine(SyntaxToken syntaxToken, SyntaxToken touchingToken, SourceText text) { return !syntaxToken.IsKind(SyntaxKind.None) && !touchingToken.IsKind(SyntaxKind.None) && text.Lines.IndexOf(syntaxToken.SpanStart) == text.Lines.IndexOf(touchingToken.SpanStart); } protected override string GetDisplayText(IMethodSymbol method, SemanticModel semanticModel, int position) => method.ToMinimalDisplayString(semanticModel, position, SignatureDisplayFormat); } }
-1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/CSharp/Impl/Interactive/CSharpVsResetInteractiveCommand.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.Editor; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell; using Roslyn.VisualStudio.Services.Interactive; using System; using System.ComponentModel.Composition; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Interactive { [ExportInteractive(typeof(IResetInteractiveCommand), ContentTypeNames.CSharpContentType)] internal sealed class CSharpVsResetInteractiveCommand : AbstractResetInteractiveCommand { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpVsResetInteractiveCommand( VisualStudioWorkspace workspace, CSharpVsInteractiveWindowProvider interactiveWindowProvider, [Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider) : base(workspace, interactiveWindowProvider, serviceProvider) { } protected override string LanguageName { get { return "C#"; } } protected override string CreateReference(string referenceName) => string.Format("#r \"{0}\"", referenceName); protected override string CreateImport(string namespaceName) => string.Format("using {0};", namespaceName); } }
// Licensed to the .NET Foundation under one or more 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.Editor; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell; using Roslyn.VisualStudio.Services.Interactive; using System; using System.ComponentModel.Composition; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Interactive { [ExportInteractive(typeof(IResetInteractiveCommand), ContentTypeNames.CSharpContentType)] internal sealed class CSharpVsResetInteractiveCommand : AbstractResetInteractiveCommand { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpVsResetInteractiveCommand( VisualStudioWorkspace workspace, CSharpVsInteractiveWindowProvider interactiveWindowProvider, [Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider) : base(workspace, interactiveWindowProvider, serviceProvider) { } protected override string LanguageName { get { return "C#"; } } protected override string CreateReference(string referenceName) => string.Format("#r \"{0}\"", referenceName); protected override string CreateImport(string namespaceName) => string.Format("using {0};", namespaceName); } }
-1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/LanguageServer/ProtocolUnitTests/Formatting/FormatDocumentOnTypeTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Formatting { public class FormatDocumentOnTypeTests : AbstractLanguageServerProtocolTests { [Fact] public async Task TestFormatDocumentOnTypeAsync() { var markup = @"class A { void M() { if (true) {{|type:|} } }"; var expected = @"class A { void M() { if (true) { } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var characterTyped = ";"; var locationTyped = locations["type"].Single(); var documentText = await testLspServer.GetCurrentSolution().GetDocuments(locationTyped.Uri).Single().GetTextAsync(); var results = await RunFormatDocumentOnTypeAsync(testLspServer, characterTyped, locationTyped); var actualText = ApplyTextEdits(results, documentText); Assert.Equal(expected, actualText); } [Fact] public async Task TestFormatDocumentOnType_UseTabsAsync() { var markup = @"class A { void M() { if (true) {{|type:|} } }"; var expected = @"class A { void M() { if (true) { } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var characterTyped = ";"; var locationTyped = locations["type"].Single(); var documentText = await testLspServer.GetCurrentSolution().GetDocuments(locationTyped.Uri).Single().GetTextAsync(); var results = await RunFormatDocumentOnTypeAsync(testLspServer, characterTyped, locationTyped, insertSpaces: false, tabSize: 4); var actualText = ApplyTextEdits(results, documentText); Assert.Equal(expected, actualText); } private static async Task<LSP.TextEdit[]> RunFormatDocumentOnTypeAsync( TestLspServer testLspServer, string characterTyped, LSP.Location locationTyped, bool insertSpaces = true, int tabSize = 4) { return await testLspServer.ExecuteRequestAsync<LSP.DocumentOnTypeFormattingParams, LSP.TextEdit[]>(LSP.Methods.TextDocumentOnTypeFormattingName, CreateDocumentOnTypeFormattingParams( characterTyped, locationTyped, insertSpaces, tabSize), new LSP.ClientCapabilities(), null, CancellationToken.None); } private static LSP.DocumentOnTypeFormattingParams CreateDocumentOnTypeFormattingParams( string characterTyped, LSP.Location locationTyped, bool insertSpaces, int tabSize) => new LSP.DocumentOnTypeFormattingParams() { Position = locationTyped.Range.Start, Character = characterTyped, TextDocument = CreateTextDocumentIdentifier(locationTyped.Uri), Options = new LSP.FormattingOptions() { InsertSpaces = insertSpaces, TabSize = tabSize, } }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Formatting { public class FormatDocumentOnTypeTests : AbstractLanguageServerProtocolTests { [Fact] public async Task TestFormatDocumentOnTypeAsync() { var markup = @"class A { void M() { if (true) {{|type:|} } }"; var expected = @"class A { void M() { if (true) { } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var characterTyped = ";"; var locationTyped = locations["type"].Single(); var documentText = await testLspServer.GetCurrentSolution().GetDocuments(locationTyped.Uri).Single().GetTextAsync(); var results = await RunFormatDocumentOnTypeAsync(testLspServer, characterTyped, locationTyped); var actualText = ApplyTextEdits(results, documentText); Assert.Equal(expected, actualText); } [Fact] public async Task TestFormatDocumentOnType_UseTabsAsync() { var markup = @"class A { void M() { if (true) {{|type:|} } }"; var expected = @"class A { void M() { if (true) { } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var characterTyped = ";"; var locationTyped = locations["type"].Single(); var documentText = await testLspServer.GetCurrentSolution().GetDocuments(locationTyped.Uri).Single().GetTextAsync(); var results = await RunFormatDocumentOnTypeAsync(testLspServer, characterTyped, locationTyped, insertSpaces: false, tabSize: 4); var actualText = ApplyTextEdits(results, documentText); Assert.Equal(expected, actualText); } private static async Task<LSP.TextEdit[]> RunFormatDocumentOnTypeAsync( TestLspServer testLspServer, string characterTyped, LSP.Location locationTyped, bool insertSpaces = true, int tabSize = 4) { return await testLspServer.ExecuteRequestAsync<LSP.DocumentOnTypeFormattingParams, LSP.TextEdit[]>(LSP.Methods.TextDocumentOnTypeFormattingName, CreateDocumentOnTypeFormattingParams( characterTyped, locationTyped, insertSpaces, tabSize), new LSP.ClientCapabilities(), null, CancellationToken.None); } private static LSP.DocumentOnTypeFormattingParams CreateDocumentOnTypeFormattingParams( string characterTyped, LSP.Location locationTyped, bool insertSpaces, int tabSize) => new LSP.DocumentOnTypeFormattingParams() { Position = locationTyped.Range.Start, Character = characterTyped, TextDocument = CreateTextDocumentIdentifier(locationTyped.Uri), Options = new LSP.FormattingOptions() { InsertSpaces = insertSpaces, TabSize = tabSize, } }; } }
-1
dotnet/roslyn
55,246
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-07-29T21:02:48Z
2021-07-29T23:44:30Z
e1612f5acf4bb3371c32f1bfaf2d8bf79d93ddc7
d8a8ed072995758d279d91fc97216ba9834bae5d
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/CallHierarchy/CallHierarchyDetail.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.Navigation; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Language.CallHierarchy; namespace Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy { internal class CallHierarchyDetail : ICallHierarchyItemDetails { private readonly TextSpan _span; private readonly DocumentId _documentId; private readonly Workspace _workspace; private readonly int _endColumn; private readonly int _endLine; private readonly string _sourceFile; private readonly int _startColumn; private readonly int _startLine; private readonly string _text; public CallHierarchyDetail(Location location, Workspace workspace) { _span = location.SourceSpan; _documentId = workspace.CurrentSolution.GetDocumentId(location.SourceTree); _workspace = workspace; _endColumn = location.GetLineSpan().Span.End.Character; _endLine = location.GetLineSpan().EndLinePosition.Line; _sourceFile = location.SourceTree.FilePath; _startColumn = location.GetLineSpan().StartLinePosition.Character; _startLine = location.GetLineSpan().StartLinePosition.Line; _text = ComputeText(location); } private string ComputeText(Location location) { var lineSpan = location.GetLineSpan(); var start = location.SourceTree.GetText().Lines[lineSpan.StartLinePosition.Line].Start; var end = location.SourceTree.GetText().Lines[lineSpan.EndLinePosition.Line].End; return location.SourceTree.GetText().GetSubText(TextSpan.FromBounds(start, end)).ToString(); } public int EndColumn => _endColumn; public int EndLine => _endLine; public string File => _sourceFile; public int StartColumn => _startColumn; public int StartLine => _startLine; public bool SupportsNavigateTo => true; public string Text => _text; public void NavigateTo() { var document = _workspace.CurrentSolution.GetDocument(_documentId); if (document != null) { var navigator = _workspace.Services.GetService<IDocumentNavigationService>(); var options = _workspace.Options.WithChangedOption(NavigationOptions.PreferProvisionalTab, true) .WithChangedOption(NavigationOptions.ActivateTab, false); // TODO: Get the platform to use and pass us an operation context, or create one ourselves. navigator.TryNavigateToSpan(_workspace, document.Id, _span, options, CancellationToken.None); } } } }
// Licensed to the .NET Foundation under one or more 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.Navigation; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Language.CallHierarchy; namespace Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy { internal class CallHierarchyDetail : ICallHierarchyItemDetails { private readonly TextSpan _span; private readonly DocumentId _documentId; private readonly Workspace _workspace; private readonly int _endColumn; private readonly int _endLine; private readonly string _sourceFile; private readonly int _startColumn; private readonly int _startLine; private readonly string _text; public CallHierarchyDetail(Location location, Workspace workspace) { _span = location.SourceSpan; _documentId = workspace.CurrentSolution.GetDocumentId(location.SourceTree); _workspace = workspace; _endColumn = location.GetLineSpan().Span.End.Character; _endLine = location.GetLineSpan().EndLinePosition.Line; _sourceFile = location.SourceTree.FilePath; _startColumn = location.GetLineSpan().StartLinePosition.Character; _startLine = location.GetLineSpan().StartLinePosition.Line; _text = ComputeText(location); } private string ComputeText(Location location) { var lineSpan = location.GetLineSpan(); var start = location.SourceTree.GetText().Lines[lineSpan.StartLinePosition.Line].Start; var end = location.SourceTree.GetText().Lines[lineSpan.EndLinePosition.Line].End; return location.SourceTree.GetText().GetSubText(TextSpan.FromBounds(start, end)).ToString(); } public int EndColumn => _endColumn; public int EndLine => _endLine; public string File => _sourceFile; public int StartColumn => _startColumn; public int StartLine => _startLine; public bool SupportsNavigateTo => true; public string Text => _text; public void NavigateTo() { var document = _workspace.CurrentSolution.GetDocument(_documentId); if (document != null) { var navigator = _workspace.Services.GetService<IDocumentNavigationService>(); var options = _workspace.Options.WithChangedOption(NavigationOptions.PreferProvisionalTab, true) .WithChangedOption(NavigationOptions.ActivateTab, false); // TODO: Get the platform to use and pass us an operation context, or create one ourselves. navigator.TryNavigateToSpan(_workspace, document.Id, _span, options, CancellationToken.None); } } } }
-1